blob: 5bfd5f3189b64d132aaf5e101d8fba47dedbb0ba [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010033#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070034#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000036#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000037#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "dex_compilation_unit.h"
39#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080040#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070041#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000042#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000043#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000044#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080045#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080046#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070048#include "object_lock.h"
Calin Juravlebb0b53f2014-05-23 17:33:29 +010049#include "profiler.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "runtime.h"
51#include "gc/accounting/card_table-inl.h"
52#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/space.h"
55#include "mirror/class_loader.h"
56#include "mirror/class-inl.h"
57#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
60#include "mirror/throwable.h"
61#include "scoped_thread_state_change.h"
62#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070065#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070067#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010068#include "transaction.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000069#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080070#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000072#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073
Brian Carlstrom7940e442013-07-12 13:46:57 -070074namespace art {
75
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070076static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
77
Andreas Gampe70bef0d2015-04-15 02:37:28 -070078// Whether classes-to-compile and methods-to-compile are only applied to the boot image, or, when
79// given, too all compilations.
Andreas Gampeb1fcead2015-04-20 18:53:51 -070080static constexpr bool kRestrictCompilationFiltersToImage = true;
81
Calin Juravle226501b2015-12-11 14:41:31 +000082// Print additional info during profile guided compilation.
83static constexpr bool kDebugProfileGuidedCompilation = false;
84
Brian Carlstrom7940e442013-07-12 13:46:57 -070085static double Percentage(size_t x, size_t y) {
86 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
87}
88
89static void DumpStat(size_t x, size_t y, const char* str) {
90 if (x == 0 && y == 0) {
91 return;
92 }
Ian Rogerse732ef12013-10-09 15:22:24 -070093 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070094}
95
Vladimir Markof096aad2014-01-23 15:51:58 +000096class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070097 public:
98 AOTCompilationStats()
99 : stats_lock_("AOT compilation statistics lock"),
100 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
101 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
102 resolved_types_(0), unresolved_types_(0),
103 resolved_instance_fields_(0), unresolved_instance_fields_(0),
104 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
105 type_based_devirtualization_(0),
106 safe_casts_(0), not_safe_casts_(0) {
107 for (size_t i = 0; i <= kMaxInvokeType; i++) {
108 resolved_methods_[i] = 0;
109 unresolved_methods_[i] = 0;
110 virtual_made_direct_[i] = 0;
111 direct_calls_to_boot_[i] = 0;
112 direct_methods_to_boot_[i] = 0;
113 }
114 }
115
116 void Dump() {
117 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
118 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
119 DumpStat(resolved_types_, unresolved_types_, "types resolved");
120 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
121 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
122 "static fields resolved");
123 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
124 "static fields local to a class");
125 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
126 // Note, the code below subtracts the stat value so that when added to the stat value we have
127 // 100% of samples. TODO: clean this up.
128 DumpStat(type_based_devirtualization_,
129 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
130 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
131 type_based_devirtualization_,
132 "virtual/interface calls made direct based on type information");
133
134 for (size_t i = 0; i <= kMaxInvokeType; i++) {
135 std::ostringstream oss;
136 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
137 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
138 if (virtual_made_direct_[i] > 0) {
139 std::ostringstream oss2;
140 oss2 << static_cast<InvokeType>(i) << " methods made direct";
141 DumpStat(virtual_made_direct_[i],
142 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
143 oss2.str().c_str());
144 }
145 if (direct_calls_to_boot_[i] > 0) {
146 std::ostringstream oss2;
147 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
148 DumpStat(direct_calls_to_boot_[i],
149 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
150 oss2.str().c_str());
151 }
152 if (direct_methods_to_boot_[i] > 0) {
153 std::ostringstream oss2;
154 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
155 DumpStat(direct_methods_to_boot_[i],
156 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
157 oss2.str().c_str());
158 }
159 }
160 }
161
162// Allow lossy statistics in non-debug builds.
163#ifndef NDEBUG
164#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
165#else
166#define STATS_LOCK()
167#endif
168
Mathieu Chartier90443472015-07-16 20:32:27 -0700169 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 STATS_LOCK();
171 types_in_dex_cache_++;
172 }
173
Mathieu Chartier90443472015-07-16 20:32:27 -0700174 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 STATS_LOCK();
176 types_not_in_dex_cache_++;
177 }
178
Mathieu Chartier90443472015-07-16 20:32:27 -0700179 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180 STATS_LOCK();
181 strings_in_dex_cache_++;
182 }
183
Mathieu Chartier90443472015-07-16 20:32:27 -0700184 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 STATS_LOCK();
186 strings_not_in_dex_cache_++;
187 }
188
Mathieu Chartier90443472015-07-16 20:32:27 -0700189 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 STATS_LOCK();
191 resolved_types_++;
192 }
193
Mathieu Chartier90443472015-07-16 20:32:27 -0700194 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 STATS_LOCK();
196 unresolved_types_++;
197 }
198
Mathieu Chartier90443472015-07-16 20:32:27 -0700199 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 STATS_LOCK();
201 resolved_instance_fields_++;
202 }
203
Mathieu Chartier90443472015-07-16 20:32:27 -0700204 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 STATS_LOCK();
206 unresolved_instance_fields_++;
207 }
208
Mathieu Chartier90443472015-07-16 20:32:27 -0700209 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 STATS_LOCK();
211 resolved_local_static_fields_++;
212 }
213
Mathieu Chartier90443472015-07-16 20:32:27 -0700214 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 STATS_LOCK();
216 resolved_static_fields_++;
217 }
218
Mathieu Chartier90443472015-07-16 20:32:27 -0700219 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 STATS_LOCK();
221 unresolved_static_fields_++;
222 }
223
224 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700225 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 STATS_LOCK();
227 type_based_devirtualization_++;
228 }
229
230 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700231 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 DCHECK_LE(type, kMaxInvokeType);
233 STATS_LOCK();
234 resolved_methods_[type]++;
235 }
236
237 // Indicate that a method of the given type was unresolved at compile time as it was in an
238 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700239 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 DCHECK_LE(type, kMaxInvokeType);
241 STATS_LOCK();
242 unresolved_methods_[type]++;
243 }
244
245 // Indicate that a type of virtual method dispatch has been converted into a direct method
246 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700247 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
249 STATS_LOCK();
250 virtual_made_direct_[type]++;
251 }
252
253 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700254 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 DCHECK_LE(type, kMaxInvokeType);
256 STATS_LOCK();
257 direct_calls_to_boot_[type]++;
258 }
259
260 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700261 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 DCHECK_LE(type, kMaxInvokeType);
263 STATS_LOCK();
264 direct_methods_to_boot_[type]++;
265 }
266
Mathieu Chartier90443472015-07-16 20:32:27 -0700267 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000268 STATS_LOCK();
269 if (flags == 0) {
270 unresolved_methods_[type]++;
271 } else {
272 DCHECK_NE((flags & kFlagMethodResolved), 0);
273 resolved_methods_[type]++;
274 if ((flags & kFlagVirtualMadeDirect) != 0) {
275 virtual_made_direct_[type]++;
276 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
277 type_based_devirtualization_++;
278 }
279 } else {
280 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
281 }
282 if ((flags & kFlagDirectCallToBoot) != 0) {
283 direct_calls_to_boot_[type]++;
284 }
285 if ((flags & kFlagDirectMethodToBoot) != 0) {
286 direct_methods_to_boot_[type]++;
287 }
288 }
289 }
290
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700292 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 STATS_LOCK();
294 safe_casts_++;
295 }
296
297 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700298 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299 STATS_LOCK();
300 not_safe_casts_++;
301 }
302
303 private:
304 Mutex stats_lock_;
305
306 size_t types_in_dex_cache_;
307 size_t types_not_in_dex_cache_;
308
309 size_t strings_in_dex_cache_;
310 size_t strings_not_in_dex_cache_;
311
312 size_t resolved_types_;
313 size_t unresolved_types_;
314
315 size_t resolved_instance_fields_;
316 size_t unresolved_instance_fields_;
317
318 size_t resolved_local_static_fields_;
319 size_t resolved_static_fields_;
320 size_t unresolved_static_fields_;
321 // Type based devirtualization for invoke interface and virtual.
322 size_t type_based_devirtualization_;
323
324 size_t resolved_methods_[kMaxInvokeType + 1];
325 size_t unresolved_methods_[kMaxInvokeType + 1];
326 size_t virtual_made_direct_[kMaxInvokeType + 1];
327 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
328 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
329
330 size_t safe_casts_;
331 size_t not_safe_casts_;
332
333 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
334};
335
Jeff Haodcdc85b2015-12-04 14:06:18 -0800336CompilerDriver::CompilerDriver(
337 const CompilerOptions* compiler_options,
338 VerificationResults* verification_results,
339 DexFileToMethodInlinerMap* method_inliner_map,
340 Compiler::Kind compiler_kind,
341 InstructionSet instruction_set,
342 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000343 bool boot_image,
344 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800345 std::unordered_set<std::string>* compiled_classes,
346 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000347 size_t thread_count,
348 bool dump_stats,
349 bool dump_passes,
350 CumulativeLogger* timer,
351 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200352 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000353 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800354 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000355 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700356 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700357 compiler_kind_(compiler_kind),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700359 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360 freezing_constructor_lock_("freezing constructor lock"),
361 compiled_classes_lock_("compiled classes lock"),
362 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800363 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100364 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800365 boot_image_(boot_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800367 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700368 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800369 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800370 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371 stats_(new AOTCompilationStats),
372 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000373 dump_passes_(dump_passes),
374 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700375 compiler_context_(nullptr),
Andreas Gampe57b34292015-01-14 15:45:59 -0800376 support_boot_image_fixup_(instruction_set != kMips && instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000377 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200378 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000379 profile_compilation_info_(profile_compilation_info),
380 max_arena_alloc_(0) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800381 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800382 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700383
Ian Rogers72d32622014-05-06 16:20:11 -0700384 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385
Mathieu Chartiera8077802016-03-16 19:08:31 -0700386 if (compiler_options->VerifyOnlyProfile()) {
387 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
388 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800389 if (boot_image_) {
390 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
391 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392}
393
394CompilerDriver::~CompilerDriver() {
395 Thread* self = Thread::Current();
396 {
397 MutexLock mu(self, compiled_classes_lock_);
398 STLDeleteValues(&compiled_classes_);
399 }
400 {
401 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800402 for (auto& pair : compiled_methods_) {
403 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
404 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 }
Ian Rogers72d32622014-05-06 16:20:11 -0700406 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407}
408
Vladimir Marko35831e82015-09-11 11:59:18 +0100409
Ian Rogersdd7624d2014-03-14 17:43:00 -0700410#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700411 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700412 return CreateTrampoline64(instruction_set_, abi, \
413 type ## _ENTRYPOINT_OFFSET(8, offset)); \
414 } else { \
415 return CreateTrampoline32(instruction_set_, abi, \
416 type ## _ENTRYPOINT_OFFSET(4, offset)); \
417 }
418
Ian Rogers848871b2013-08-05 10:56:33 -0700419const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700420 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700421}
422
Andreas Gampe2da88232014-02-27 12:26:20 -0800423const std::vector<uint8_t>* CompilerDriver::CreateQuickGenericJniTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700424 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800425}
426
Jeff Hao88474b42013-10-23 16:24:40 -0700427const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700428 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700429}
430
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700433}
434
Ian Rogers848871b2013-08-05 10:56:33 -0700435const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700436 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439
440void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700441 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800442 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800444
445 InitializeThreadPools();
446
Andreas Gampe8d295f82015-01-20 14:50:21 -0800447 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700448 // Precompile:
449 // 1) Load image classes
450 // 2) Resolve all classes
451 // 3) Attempt to verify all classes
452 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800453 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700454 // Compile:
455 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
456 // compilation.
457 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800458 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700459 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 if (dump_stats_) {
461 stats_->Dump();
462 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800463
464 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465}
466
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700467static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
468 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
469 const DexFile& dex_file, const DexFile::ClassDef& class_def)
470 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800471 auto* const runtime = Runtime::Current();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700472 if (runtime->UseJit() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700473 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700474 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800475 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700476 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800477 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800478 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700479 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480 CHECK(self->IsExceptionPending());
481 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700482 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700483 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700484 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
485 // references with actual offsets. We cannot re-verify such instructions.
486 //
487 // We store the verification information in the class status in the oat file, which the linker
488 // can validate (checksums) and use to skip load-time verification. It is thus safe to
489 // optimize when a class has been fully verified before.
490 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200491 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700492 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200493 } else if (klass->IsCompileTimeVerified()) {
494 // Class verification has soft-failed. Anyway, ensure at least correctness.
495 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700496 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200497 } else {
498 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700499 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
500 }
501}
502
503static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
504 Thread* self,
505 const CompilerDriver& driver,
506 jobject jclass_loader,
507 const DexFile& dex_file,
508 const DexFile::ClassDef& class_def) {
509 ScopedObjectAccess soa(self);
510 StackHandleScope<1> hs(soa.Self());
511 Handle<mirror::ClassLoader> class_loader(
512 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
513 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
514}
515
516// Does the runtime for the InstructionSet provide an implementation returned by
517// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
518static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
519 switch (isa) {
520 case kArm:
521 case kArm64:
522 case kThumb2:
523 case kMips:
524 case kMips64:
525 case kX86:
526 case kX86_64: return true;
527 default: return false;
528 }
529}
530
531static void CompileMethod(Thread* self,
532 CompilerDriver* driver,
533 const DexFile::CodeItem* code_item,
534 uint32_t access_flags,
535 InvokeType invoke_type,
536 uint16_t class_def_idx,
537 uint32_t method_idx,
538 jobject class_loader,
539 const DexFile& dex_file,
540 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700541 bool compilation_enabled,
542 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700543 REQUIRES(!driver->compiled_methods_lock_) {
544 DCHECK(driver != nullptr);
545 CompiledMethod* compiled_method = nullptr;
546 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
547 MethodReference method_ref(&dex_file, method_idx);
548
549 if ((access_flags & kAccNative) != 0) {
550 // Are we interpreting only and have support for generic JNI down calls?
551 if (!driver->GetCompilerOptions().IsCompilationEnabled() &&
552 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
553 // Leaving this empty will trigger the generic JNI version
554 } else {
555 compiled_method = driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file);
556 CHECK(compiled_method != nullptr);
557 }
558 } else if ((access_flags & kAccAbstract) != 0) {
559 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000560 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700561 const VerifiedMethod* verified_method =
562 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700563 bool compile = compilation_enabled &&
564 // Basic checks, e.g., not <clinit>.
565 driver->GetVerificationResults()
566 ->IsCandidateForCompilation(method_ref, access_flags) &&
567 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700568 verified_method != nullptr &&
569 // Do not have failures that should punt to the interpreter.
570 !verified_method->HasRuntimeThrow() &&
571 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700572 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700573 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000574 driver->IsMethodToCompile(method_ref) &&
575 driver->ShouldCompileBasedOnProfile(method_ref);
576
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700577 if (compile) {
578 // NOTE: if compiler declines to compile this method, it will return null.
579 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
580 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700581 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700582 }
583 if (compiled_method == nullptr &&
584 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
585 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
586 // Do not optimize if a VerifiedMethod is missing. SafeCast elision, for example, relies on
587 // it.
588 compiled_method = optimizer::ArtCompileDEX(
589 driver,
590 code_item,
591 access_flags,
592 invoke_type,
593 class_def_idx,
594 method_idx,
595 class_loader,
596 dex_file,
Andreas Gampe0760a812015-08-26 17:12:51 -0700597 (verified_method != nullptr)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700598 ? dex_to_dex_compilation_level
599 : optimizer::DexToDexCompilationLevel::kRequired);
600 }
601 }
602 if (kTimeCompileMethod) {
603 uint64_t duration_ns = NanoTime() - start_ns;
604 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
605 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
606 << " took " << PrettyDuration(duration_ns);
607 }
608 }
609
610 if (compiled_method != nullptr) {
611 // Count non-relative linker patches.
612 size_t non_relative_linker_patch_count = 0u;
613 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
614 if (!patch.IsPcRelative()) {
615 ++non_relative_linker_patch_count;
616 }
617 }
618 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
619 // When compiling with PIC, there should be zero non-relative linker patches
620 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
621
622 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
623 }
624
625 // Done compiling, delete the verified method to reduce native memory usage. Do not delete in
626 // optimizing compiler, which may need the verified method again for inlining.
627 if (driver->GetCompilerKind() != Compiler::kOptimizing) {
628 driver->GetVerificationResults()->RemoveVerifiedMethod(method_ref);
629 }
630
631 if (self->IsExceptionPending()) {
632 ScopedObjectAccess soa(self);
633 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
634 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200635 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636}
637
Mathieu Chartiere401d142015-04-22 13:56:20 -0700638void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700639 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700640 jobject jclass_loader;
641 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700642 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800643 uint32_t method_idx = method->GetDexMethodIndex();
644 uint32_t access_flags = method->GetAccessFlags();
645 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700646 StackHandleScope<1> hs(self);
647 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648 {
649 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800650 ScopedLocalRef<jobject> local_class_loader(
651 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
653 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700654 dex_file = method->GetDexFile();
655 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800657 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700658
659 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700660 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700661
662 std::vector<const DexFile*> dex_files;
663 dex_files.push_back(dex_file);
664
Andreas Gampeace0dc12016-01-20 13:33:13 -0800665 InitializeThreadPools();
666
667 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668
Brian Carlstrom7940e442013-07-12 13:46:57 -0700669 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700670 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
671 GetDexToDexCompilationLevel(self,
672 *this,
673 jclass_loader,
674 *dex_file,
675 dex_file->GetClassDef(class_def_idx));
676
677 CompileMethod(self,
678 this,
679 code_item,
680 access_flags,
681 invoke_type,
682 class_def_idx,
683 method_idx,
684 jclass_loader,
685 *dex_file,
686 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700687 true,
688 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689
Andreas Gampeace0dc12016-01-20 13:33:13 -0800690 FreeThreadPools();
691
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800693}
694
Andreas Gampeace0dc12016-01-20 13:33:13 -0800695void CompilerDriver::Resolve(jobject class_loader,
696 const std::vector<const DexFile*>& dex_files,
697 TimingLogger* timings) {
698 // Resolution allocates classes and needs to run single-threaded to be deterministic.
699 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
700 ThreadPool* resolve_thread_pool = force_determinism
701 ? single_thread_pool_.get()
702 : parallel_thread_pool_.get();
703 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
704
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 for (size_t i = 0; i != dex_files.size(); ++i) {
706 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700707 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800708 ResolveDexFile(class_loader,
709 *dex_file,
710 dex_files,
711 resolve_thread_pool,
712 resolve_thread_count,
713 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 }
715}
716
Andreas Gampeace0dc12016-01-20 13:33:13 -0800717// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
718// this is single-threaded for simplicity.
719// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
720// stable order.
721
722static void ResolveConstStrings(CompilerDriver* driver,
723 const DexFile& dex_file,
724 const DexFile::CodeItem* code_item) {
725 if (code_item == nullptr) {
726 // Abstract or native method.
727 return;
728 }
729
730 const uint16_t* code_ptr = code_item->insns_;
731 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
732
733 while (code_ptr < code_end) {
734 const Instruction* inst = Instruction::At(code_ptr);
735 switch (inst->Opcode()) {
736 case Instruction::CONST_STRING: {
737 uint32_t string_index = inst->VRegB_21c();
738 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
739 break;
740 }
741 case Instruction::CONST_STRING_JUMBO: {
742 uint32_t string_index = inst->VRegB_31c();
743 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
744 break;
745 }
746
747 default:
748 break;
749 }
750
751 code_ptr += inst->SizeInCodeUnits();
752 }
753}
754
755static void ResolveConstStrings(CompilerDriver* driver,
756 const std::vector<const DexFile*>& dex_files,
757 TimingLogger* timings) {
758 for (const DexFile* dex_file : dex_files) {
759 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
760
761 size_t class_def_count = dex_file->NumClassDefs();
762 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
763 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
764
765 const uint8_t* class_data = dex_file->GetClassData(class_def);
766 if (class_data == nullptr) {
767 // empty class, probably a marker interface
768 continue;
769 }
770
771 ClassDataItemIterator it(*dex_file, class_data);
772 // Skip fields
773 while (it.HasNextStaticField()) {
774 it.Next();
775 }
776 while (it.HasNextInstanceField()) {
777 it.Next();
778 }
779
780 bool compilation_enabled = driver->IsClassToCompile(
781 dex_file->StringByTypeIdx(class_def.class_idx_));
782 if (!compilation_enabled) {
783 // Compilation is skipped, do not resolve const-string in code of this class.
784 // TODO: Make sure that inlining honors this.
785 continue;
786 }
787
788 // Direct methods.
789 int64_t previous_direct_method_idx = -1;
790 while (it.HasNextDirectMethod()) {
791 uint32_t method_idx = it.GetMemberIndex();
792 if (method_idx == previous_direct_method_idx) {
793 // smali can create dex files with two encoded_methods sharing the same method_idx
794 // http://code.google.com/p/smali/issues/detail?id=119
795 it.Next();
796 continue;
797 }
798 previous_direct_method_idx = method_idx;
799 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
800 it.Next();
801 }
802 // Virtual methods.
803 int64_t previous_virtual_method_idx = -1;
804 while (it.HasNextVirtualMethod()) {
805 uint32_t method_idx = it.GetMemberIndex();
806 if (method_idx == previous_virtual_method_idx) {
807 // smali can create dex files with two encoded_methods sharing the same method_idx
808 // http://code.google.com/p/smali/issues/detail?id=119
809 it.Next();
810 continue;
811 }
812 previous_virtual_method_idx = method_idx;
813 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
814 it.Next();
815 }
816 DCHECK(!it.HasNext());
817 }
818 }
819}
820
821inline void CompilerDriver::CheckThreadPools() {
822 DCHECK(parallel_thread_pool_ != nullptr);
823 DCHECK(single_thread_pool_ != nullptr);
824}
825
826void CompilerDriver::PreCompile(jobject class_loader,
827 const std::vector<const DexFile*>& dex_files,
828 TimingLogger* timings) {
829 CheckThreadPools();
830
Brian Carlstrom7940e442013-07-12 13:46:57 -0700831 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800832 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700833
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700834 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
835 const bool never_verify = compiler_options_->NeverVerify();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700836
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700837 // We need to resolve for never_verify since it needs to run dex to dex to add the
838 // RETURN_VOID_NO_BARRIER.
Andreas Gampe82e8c1f2016-03-30 13:28:44 -0700839 if (never_verify || verification_enabled) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800840 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700841 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
842 }
843
844 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800845 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800846 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700847 }
848
849 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700850 return;
851 }
852
Andreas Gampeace0dc12016-01-20 13:33:13 -0800853 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
854 // Resolve strings from const-string. Do this now to have a deterministic image.
855 ResolveConstStrings(this, dex_files, timings);
856 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
857 }
858
859 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800860 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700861
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800862 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
863 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
864 << "situations. Please check the log.";
865 }
866
Andreas Gampeace0dc12016-01-20 13:33:13 -0800867 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800868 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869
870 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800871 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872}
873
Ian Rogersdfb325e2013-10-30 01:00:44 -0700874bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800875 if (image_classes_ != nullptr) {
876 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700877 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800879 // No set of image classes, assume we include all the classes.
880 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
881 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700882}
883
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800884bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800885 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800886 return true;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800887 }
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700888
889 if (classes_to_compile_ == nullptr) {
890 return true;
891 }
892 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800893}
894
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700895bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800896 if (kRestrictCompilationFiltersToImage && !IsBootImage()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700897 return true;
898 }
899
900 if (methods_to_compile_ == nullptr) {
901 return true;
902 }
903
904 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
905 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
906}
907
Calin Juravle226501b2015-12-11 14:41:31 +0000908bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
909 if (profile_compilation_info_ == nullptr) {
910 // If we miss profile information it means that we don't do a profile guided compilation.
911 // Return true, and let the other filters decide if the method should be compiled.
912 return true;
913 }
914 bool result = profile_compilation_info_->ContainsMethod(method_ref);
915
916 if (kDebugProfileGuidedCompilation) {
917 LOG(INFO) << "[ProfileGuidedCompilation] "
918 << (result ? "Compiled" : "Skipped") << " method:"
919 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
920 }
921 return result;
922}
923
Mathieu Chartiera8077802016-03-16 19:08:31 -0700924bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
925 uint16_t class_idx) const {
926 if (!compiler_options_->VerifyOnlyProfile()) {
927 // No profile, verify everything.
928 return true;
929 }
930 DCHECK(profile_compilation_info_ != nullptr);
931 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
932 if (kDebugProfileGuidedCompilation) {
933 LOG(INFO) << "[ProfileGuidedCompilation] "
934 << (result ? "Verified" : "Skipped") << " method:"
935 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
936 }
937 return result;
938}
939
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700940class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
941 public:
942 ResolveCatchBlockExceptionsClassVisitor(
943 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
944 : exceptions_to_resolve_(exceptions_to_resolve) {}
945
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800946 virtual bool operator()(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700947 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -0800948 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100949 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700950 }
951 return true;
952 }
953
954 private:
Vladimir Marko05792b92015-08-03 11:56:49 +0100955 void ResolveExceptionsForMethod(ArtMethod* method_handle, size_t pointer_size)
956 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700957 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
958 if (code_item == nullptr) {
959 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700961 if (code_item->tries_size_ == 0) {
962 return; // nothing to process
963 }
964 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
965 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
966 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
967 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
968 bool has_catch_all = false;
969 if (encoded_catch_handler_size <= 0) {
970 encoded_catch_handler_size = -encoded_catch_handler_size;
971 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700972 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700973 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
974 uint16_t encoded_catch_handler_handlers_type_idx =
975 DecodeUnsignedLeb128(&encoded_catch_handler_list);
976 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +0100977 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
978 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700979 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
980 method_handle->GetDexFile());
981 }
982 // ignore address associated with catch handler
983 DecodeUnsignedLeb128(&encoded_catch_handler_list);
984 }
985 if (has_catch_all) {
986 // ignore catch all address
987 DecodeUnsignedLeb128(&encoded_catch_handler_list);
988 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700989 }
990 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700991
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700992 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
993};
994
995class RecordImageClassesVisitor : public ClassVisitor {
996 public:
997 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
998 : image_classes_(image_classes) {}
999
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001000 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001001 std::string temp;
1002 image_classes_->insert(klass->GetDescriptor(&temp));
1003 return true;
1004 }
1005
1006 private:
1007 std::unordered_set<std::string>* const image_classes_;
1008};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009
1010// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001011void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001012 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001013 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 return;
1015 }
1016
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001017 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 // Make a first class to load all classes explicitly listed in the file
1019 Thread* self = Thread::Current();
1020 ScopedObjectAccess soa(self);
1021 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001022 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001023 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001024 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001025 StackHandleScope<1> hs(self);
1026 Handle<mirror::Class> klass(
1027 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001028 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001029 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001030 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001031 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001032 } else {
1033 ++it;
1034 }
1035 }
1036
1037 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1038 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1039 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001040 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001041 StackHandleScope<1> hs(self);
1042 Handle<mirror::Class> java_lang_Throwable(
1043 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 do {
1045 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001046 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1047 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001048 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1049 uint16_t exception_type_idx = exception_type.first;
1050 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001051 StackHandleScope<2> hs2(self);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001052 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(
1053 *dex_file,
1054 Runtime::Current()->GetLinearAlloc())));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001055 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001056 class_linker->ResolveType(*dex_file,
1057 exception_type_idx,
1058 dex_cache,
1059 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001060 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1062 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1063 LOG(FATAL) << "Failed to resolve class " << descriptor;
1064 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001065 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066 }
1067 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1068 // more are found
1069 } while (!unresolved_exception_types.empty());
1070
1071 // We walk the roots looking for classes so that we'll pick up the
1072 // above classes plus any classes them depend on such super
1073 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001074 RecordImageClassesVisitor visitor(image_classes_.get());
1075 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001076
1077 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001078}
1079
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001080static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1081 std::unordered_set<std::string>* image_classes)
Mathieu Chartier90443472015-07-16 20:32:27 -07001082 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001083 Thread* self = Thread::Current();
1084 StackHandleScope<1> hs(self);
1085 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001086 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001087 std::string temp;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001088 const size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001090 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001091 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1092 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001093 if (!result.second) { // Previously inserted.
1094 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001096 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001097 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001098 StackHandleScope<1> hs2(self);
1099 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001100 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001101 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001102 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001103 StackHandleScope<1> hs2(self);
1104 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001105 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001107 StackHandleScope<1> hs2(self);
1108 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001110 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001111 }
1112}
1113
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001114// Keeps all the data for the update together. Also doubles as the reference visitor.
1115// Note: we can use object pointers because we suspend all threads.
1116class ClinitImageUpdate {
1117 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001118 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1119 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001120 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1121 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001122 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001123 *error_msg = "Could not find DexCache class.";
1124 return nullptr;
1125 }
1126
1127 return res.release();
1128 }
1129
1130 ~ClinitImageUpdate() {
1131 // Allow others to suspend again.
1132 self_->EndAssertNoThreadSuspension(old_cause_);
1133 }
1134
1135 // Visitor for VisitReferences.
1136 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001137 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001138 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1139 if (ref != nullptr) {
1140 VisitClinitClassesObject(ref);
1141 }
1142 }
1143
1144 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001145 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1146 const {}
1147
1148 // Ignore class native roots.
1149 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1150 const {}
1151 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001152
Mathieu Chartier90443472015-07-16 20:32:27 -07001153 void Walk() SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001154 // Use the initial classes as roots for a search.
1155 for (mirror::Class* klass_root : image_classes_) {
1156 VisitClinitClassesObject(klass_root);
1157 }
1158 }
1159
1160 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001161 class FindImageClassesVisitor : public ClassVisitor {
1162 public:
1163 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1164
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001165 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001166 std::string temp;
1167 const char* name = klass->GetDescriptor(&temp);
1168 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1169 data_->image_classes_.push_back(klass);
1170 } else {
1171 // Check whether it is initialized and has a clinit. They must be kept, too.
1172 if (klass->IsInitialized() && klass->FindClassInitializer(
1173 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1174 data_->image_classes_.push_back(klass);
1175 }
1176 }
1177 return true;
1178 }
1179
1180 private:
1181 ClinitImageUpdate* const data_;
1182 };
1183
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001184 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001185 ClassLinker* linker)
Mathieu Chartier90443472015-07-16 20:32:27 -07001186 SHARED_REQUIRES(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001187 image_class_descriptors_(image_class_descriptors), self_(self) {
1188 CHECK(linker != nullptr);
1189 CHECK(image_class_descriptors != nullptr);
1190
1191 // Make sure nobody interferes with us.
1192 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1193
1194 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001195 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1196 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001197
1198 // Find all the already-marked classes.
1199 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001200 FindImageClassesVisitor visitor(this);
1201 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001202 }
1203
1204 void VisitClinitClassesObject(mirror::Object* object) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001205 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001206 DCHECK(object != nullptr);
1207 if (marked_objects_.find(object) != marked_objects_.end()) {
1208 // Already processed.
1209 return;
1210 }
1211
1212 // Mark it.
1213 marked_objects_.insert(object);
1214
1215 if (object->IsClass()) {
1216 // If it is a class, add it.
1217 StackHandleScope<1> hs(self_);
1218 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1219 } else {
1220 // Else visit the object's class.
1221 VisitClinitClassesObject(object->GetClass());
1222 }
1223
Mathieu Chartiere401d142015-04-22 13:56:20 -07001224 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001225 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001226 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001227 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001228 }
1229 }
1230
1231 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001232 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001233 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001234 const mirror::Class* dex_cache_class_;
1235 Thread* const self_;
1236 const char* old_cause_;
1237
1238 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1239};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001240
Ian Rogers3d504072014-03-01 09:16:49 -08001241void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001242 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001243 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001244
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001245 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001246
1247 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001248 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001249
1250 std::string error_msg;
1251 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1252 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001253 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001254 &error_msg));
1255 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1256
1257 // Do the marking.
1258 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001259 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001260}
1261
Vladimir Marko07785bb2015-06-15 18:52:54 +01001262bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1263 Runtime* runtime = Runtime::Current();
1264 if (!runtime->IsAotCompiler()) {
1265 DCHECK(runtime->UseJit());
1266 // Having the klass reference here implies that the klass is already loaded.
1267 return true;
1268 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001269 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001270 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1271 // loaded because we don't even know what class loader will be used to load them.
1272 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1273 return class_in_image;
1274 }
1275 std::string temp;
1276 const char* descriptor = klass->GetDescriptor(&temp);
1277 return IsImageClass(descriptor);
1278}
1279
Mathieu Chartier590fee92013-09-13 13:46:47 -07001280bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001281 bool result = false;
1282 if ((IsBootImage() &&
1283 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) ||
1284 Runtime::Current()->UseJit()) {
1285 ScopedObjectAccess soa(Thread::Current());
1286 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1287 soa.Self(), dex_file, false);
1288 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1289 result = (resolved_class != nullptr);
1290 }
1291
1292 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001293 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001294 } else {
1295 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001296 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001297 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001298}
1299
1300bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1301 uint32_t string_idx) {
1302 // See also Compiler::ResolveDexFile
1303
1304 bool result = false;
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001305 if (IsBootImage() || Runtime::Current()->UseJit()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001306 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001307 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001308 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1309 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1310 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001311 if (IsBootImage()) {
1312 // We resolve all const-string strings when building for the image.
1313 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1314 result = true;
1315 } else {
1316 // Just check whether the dex cache already has the string.
1317 DCHECK(Runtime::Current()->UseJit());
1318 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1319 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001320 }
1321 if (result) {
1322 stats_->StringInDexCache();
1323 } else {
1324 stats_->StringNotInDexCache();
1325 }
1326 return result;
1327}
1328
1329bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
1330 uint32_t type_idx,
1331 bool* type_known_final, bool* type_known_abstract,
1332 bool* equals_referrers_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001333 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001334 *type_known_final = false;
1335 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001336 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001337 *type_known_abstract = false;
1338 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001339 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001340 *equals_referrers_class = false;
1341 }
1342 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001343 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1344 soa.Self(), dex_file, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001345 // Get type from dex cache assuming it was populated by the verifier
1346 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001347 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001348 stats_->TypeNeedsAccessCheck();
1349 return false; // Unknown class needs access checks.
1350 }
1351 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001352 if (equals_referrers_class != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353 *equals_referrers_class = (method_id.class_idx_ == type_idx);
1354 }
David Brazdil38f64d32016-01-18 17:13:41 +00001355 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1356 if (!is_accessible) {
1357 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1358 if (referrer_class == nullptr) {
1359 stats_->TypeNeedsAccessCheck();
1360 return false; // Incomplete referrer knowledge needs access check.
1361 }
1362 // Perform access check, will return true if access is ok or false if we're going to have to
1363 // check this at runtime (for example for class loaders).
1364 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001365 }
David Brazdil38f64d32016-01-18 17:13:41 +00001366 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367 stats_->TypeDoesntNeedAccessCheck();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001368 if (type_known_final != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
1370 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001371 if (type_known_abstract != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001372 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
1373 }
1374 } else {
1375 stats_->TypeNeedsAccessCheck();
1376 }
David Brazdil38f64d32016-01-18 17:13:41 +00001377 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378}
1379
1380bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
1381 const DexFile& dex_file,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001382 uint32_t type_idx,
1383 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001384 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001385 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(
1386 soa.Self(), dex_file, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001387 // Get type from dex cache assuming it was populated by the verifier.
1388 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001389 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001391 // Be conservative.
1392 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 return false; // Unknown class needs access checks.
1394 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001395 *finalizable = resolved_class->IsFinalizable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001397 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1398 if (!is_accessible) {
1399 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1400 if (referrer_class == nullptr) {
1401 stats_->TypeNeedsAccessCheck();
1402 return false; // Incomplete referrer knowledge needs access check.
1403 }
1404 // Perform access and instantiable checks, will return true if access is ok or false if we're
1405 // going to have to check this at runtime (for example for class loaders).
1406 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001407 }
David Brazdil38f64d32016-01-18 17:13:41 +00001408 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001409 if (result) {
1410 stats_->TypeDoesntNeedAccessCheck();
1411 } else {
1412 stats_->TypeNeedsAccessCheck();
1413 }
1414 return result;
1415}
1416
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001417bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1418 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001419 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001420 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001421 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001422 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1423 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001424 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1425 if (resolved_class == nullptr) {
1426 return false;
1427 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001428 if (GetCompilerOptions().GetCompilePic()) {
1429 // Do not allow a direct class pointer to be used when compiling for position-independent
1430 return false;
1431 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001432 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001433 gc::Heap* heap = runtime->GetHeap();
1434 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001435 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001436 if (compiling_boot) {
1437 // boot -> boot class pointers.
1438 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001439 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001440 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1441 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001442 if (is_image_class && support_boot_image_fixup) {
1443 *is_type_initialized = resolved_class->IsInitialized();
1444 *use_direct_type_ptr = false;
1445 *direct_type_ptr = 0;
1446 return true;
1447 } else {
1448 return false;
1449 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001450 } else if (runtime->UseJit() && !heap->IsMovableObject(resolved_class)) {
1451 *is_type_initialized = resolved_class->IsInitialized();
1452 // If the class may move around, then don't embed it as a direct pointer.
1453 *use_direct_type_ptr = true;
1454 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1455 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001456 } else {
1457 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001458 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001459 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001460 // boot -> app class pointers.
1461 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001462 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1463 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001464 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1465 return true;
1466 } else {
1467 // app -> app class pointers.
1468 // Give up because app does not have an image and class
1469 // isn't created at compile time. TODO: implement this
1470 // if/when each app gets an image.
1471 return false;
1472 }
1473 }
1474}
1475
Fred Shihe7f82e22014-08-06 10:46:37 -07001476bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1477 bool* use_direct_ptr,
1478 uintptr_t* direct_type_ptr) {
1479 CHECK(ref != nullptr);
1480 CHECK(use_direct_ptr != nullptr);
1481 CHECK(direct_type_ptr != nullptr);
1482
1483 ScopedObjectAccess soa(Thread::Current());
1484 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001485 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001486 bool unused_finalizable;
1487 // Make sure we have a finished Reference class object before attempting to use it.
1488 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1489 reference_class->GetDexTypeIndex(), &is_initialized,
1490 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1491 !is_initialized) {
1492 return false;
1493 }
1494 ref->first = &reference_class->GetDexFile();
1495 ref->second = reference_class->GetDexClassDefIndex();
1496 return true;
1497}
1498
1499uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1500 ScopedObjectAccess soa(Thread::Current());
1501 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1502 DCHECK(klass->IsInitialized());
1503 return klass->GetSlowPathFlagOffset().Uint32Value();
1504}
1505
1506uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1507 ScopedObjectAccess soa(Thread::Current());
1508 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1509 DCHECK(klass->IsInitialized());
1510 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1511}
1512
Vladimir Marko20f85592015-03-19 10:07:02 +00001513DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001514 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001515 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001516 : DexCacheArraysLayout();
1517}
1518
Vladimir Markobe0e5462014-02-26 11:24:15 +00001519void CompilerDriver::ProcessedInstanceField(bool resolved) {
1520 if (!resolved) {
1521 stats_->UnresolvedInstanceField();
1522 } else {
1523 stats_->ResolvedInstanceField();
1524 }
1525}
1526
1527void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1528 if (!resolved) {
1529 stats_->UnresolvedStaticField();
1530 } else if (local) {
1531 stats_->ResolvedLocalStaticField();
1532 } else {
1533 stats_->ResolvedStaticField();
1534 }
1535}
1536
Vladimir Markof096aad2014-01-23 15:51:58 +00001537void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1538 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001539}
1540
Mathieu Chartierc7853442015-03-27 14:35:38 -07001541ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1542 const DexCompilationUnit* mUnit, bool is_put,
1543 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001544 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001545 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001546 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001547 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001548 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001549 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001550 Handle<mirror::ClassLoader> class_loader_handle(
1551 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001552 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001553 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001554 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001555 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001556 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001557 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001558 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001559 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001560 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001561 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001562 ProcessedInstanceField(can_link);
1563 return can_link ? resolved_field : nullptr;
1564}
1565
1566bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1567 bool is_put, MemberOffset* field_offset,
1568 bool* is_volatile) {
1569 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001570 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001571
Mathieu Chartierc7853442015-03-27 14:35:38 -07001572 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001573 // Conservative defaults.
1574 *is_volatile = true;
1575 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001576 return false;
1577 } else {
1578 *is_volatile = resolved_field->IsVolatile();
1579 *field_offset = resolved_field->GetOffset();
1580 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001581 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001582}
1583
1584bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +00001585 bool is_put, MemberOffset* field_offset,
1586 uint32_t* storage_index, bool* is_referrers_class,
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001587 bool* is_volatile, bool* is_initialized,
1588 Primitive::Type* type) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001590 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001591 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001592 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001593 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001594 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001595 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001596 Handle<mirror::ClassLoader> class_loader_handle(
1597 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001598 resolved_field =
Mathieu Chartier736b5602015-09-02 14:54:11 -07001599 ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, true);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001600 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001601 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001603 bool result = false;
1604 if (resolved_field != nullptr && referrer_class != nullptr) {
1605 *is_volatile = IsFieldVolatile(resolved_field);
1606 std::pair<bool, bool> fast_path = IsFastStaticField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001607 dex_cache.Get(), referrer_class, resolved_field, field_idx, storage_index);
Vladimir Markobe0e5462014-02-26 11:24:15 +00001608 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001609 }
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001610 if (result) {
1611 *field_offset = GetFieldOffset(resolved_field);
1612 *is_referrers_class = IsStaticFieldInReferrerClass(referrer_class, resolved_field);
1613 // *is_referrers_class == true implies no worrying about class initialization.
1614 *is_initialized = (*is_referrers_class) ||
1615 (IsStaticFieldsClassInitialized(referrer_class, resolved_field) &&
1616 CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index));
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001617 *type = resolved_field->GetTypeAsPrimitiveType();
Vladimir Marko66c6d7b2014-10-16 15:41:48 +01001618 } else {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001619 // Conservative defaults.
1620 *is_volatile = true;
1621 *field_offset = MemberOffset(static_cast<size_t>(-1));
1622 *storage_index = -1;
1623 *is_referrers_class = false;
1624 *is_initialized = false;
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +01001625 *type = Primitive::kPrimVoid;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001626 }
1627 ProcessedStaticField(result, *is_referrers_class);
1628 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001629}
1630
Ian Rogers83883d72013-10-21 21:07:24 -07001631void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1632 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001633 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001635 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001636 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001637 uintptr_t* direct_code,
1638 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001639 // For direct and static methods compute possible direct_code and direct_method values, ie
1640 // an address for the Method* being invoked and an address of the code for that Method*.
1641 // For interface calls compute a value for direct_method that is the interface method being
1642 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001643 *direct_code = 0;
1644 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001645 Runtime* const runtime = Runtime::Current();
1646 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001647 auto* cl = runtime->GetClassLinker();
1648 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001649 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001650 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001651 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1652 const bool force_relocations = (compiling_boot ||
1653 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001654 if (sharp_type != kStatic && sharp_type != kDirect) {
1655 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001656 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001657 // TODO: support patching on all architectures.
1658 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001659 mirror::Class* declaring_class = method->GetDeclaringClass();
1660 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001661 if (!use_dex_cache) {
1662 if (!method_code_in_boot) {
1663 use_dex_cache = true;
1664 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001665 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001666 method->IsStatic() && !declaring_class->IsInitialized();
1667 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001668 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1669 // class.
1670 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001671 }
1672 }
Ian Rogers83883d72013-10-21 21:07:24 -07001673 }
Mathieu Chartier28a35882015-02-26 18:28:07 -08001674 if (runtime->UseJit()) {
1675 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1676 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001677 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001678 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1679 use_dex_cache = true;
1680 }
1681 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001682 if (method_code_in_boot) {
1683 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001684 }
Alex Lighta59dd802014-07-02 16:28:08 -07001685 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001686 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001687 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001688 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1689 } else {
1690 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001691 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1692 !cl->IsQuickToInterpreterBridge(
1693 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001694 }
1695 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001696 // We can only branch directly to Methods that are resolved in the DexCache.
1697 // Otherwise we won't invoke the resolution trampoline.
1698 use_dex_cache = true;
1699 }
1700 }
1701 // The method is defined not within this dex file. We need a dex cache slot within the current
1702 // dex file or direct pointers.
1703 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001704 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1705 if (target_method->dex_file == dex_cache->GetDexFile() &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07001706 !(runtime->UseJit() && dex_cache->GetResolvedMethod(
1707 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001708 target_method->dex_method_index = method->GetDexMethodIndex();
1709 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001710 if (no_guarantee_of_dex_cache_entry) {
1711 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1713 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001714 if (dex_method_idx != DexFile::kDexNoIndex) {
1715 target_method->dex_method_index = dex_method_idx;
1716 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001717 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001718 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001719 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001720 }
Ian Rogers83883d72013-10-21 21:07:24 -07001721 must_use_direct_pointers = true;
1722 }
1723 }
1724 }
1725 if (use_dex_cache) {
1726 if (must_use_direct_pointers) {
1727 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1728 // pointers are required as the dex cache lacks an appropriate entry.
1729 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1730 } else {
1731 *type = sharp_type;
1732 }
1733 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001735 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1736 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001737 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001738 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1739 method_in_image = true;
1740 break;
1741 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001742 }
Mathieu Chartier6ced4092015-02-27 16:10:48 -08001743 if (method_in_image || compiling_boot || runtime->UseJit()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001744 // 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 -08001745 // In the case where we are the JIT, we can always use direct pointers since we know where
1746 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1747 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001748 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001749 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001750 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1751 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001752 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001753 target_method->dex_method_index = method->GetDexMethodIndex();
1754 } else if (!must_use_direct_pointers) {
1755 // Set the code and rely on the dex cache for the method.
1756 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001757 if (force_relocations) {
1758 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001759 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001760 target_method->dex_method_index = method->GetDexMethodIndex();
1761 } else {
1762 *direct_code = compiler_->GetEntryPointOf(method);
1763 }
Ian Rogers83883d72013-10-21 21:07:24 -07001764 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001765 // Direct pointers were required but none were available.
1766 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001767 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001768 }
1769}
1770
1771bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001772 bool update_stats, bool enable_devirtualization,
1773 InvokeType* invoke_type, MethodReference* target_method,
1774 int* vtable_idx, uintptr_t* direct_code,
1775 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001776 InvokeType orig_invoke_type = *invoke_type;
1777 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001778 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001779 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001780 StackHandleScope<2> hs(soa.Self());
1781 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001782 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1783 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001784 uint32_t method_idx = target_method->dex_method_index;
1785 ArtMethod* resolved_method = ResolveMethod(
1786 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1787 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1788 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001789 bool result = false;
1790 if (resolved_method != nullptr) {
1791 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001792
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001793 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001794 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1795
1796 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001797 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001798 invoke_type, target_method, devirt_target, direct_code, direct_method);
1799 result = stats_flags != 0;
1800 } else {
1801 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001802 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1803 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001804 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001805 target_method->dex_method_index)) ||
1806 *invoke_type == kSuper) {
1807 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1808 } else {
1809 // Sharpening failed so generate a regular resolved method dispatch.
1810 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001811 GetCodeAndMethodForDirectCall(
1812 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1813 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001814 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 }
1816 }
1817 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001818 if (!result) {
1819 // Conservative defaults.
1820 *vtable_idx = -1;
1821 *direct_code = 0u;
1822 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823 }
1824 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001825 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001826 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001827 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001828}
1829
Vladimir Marko2730db02014-01-27 11:15:17 +00001830const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1831 uint32_t method_idx) const {
1832 MethodReference ref(dex_file, method_idx);
1833 return verification_results_->GetVerifiedMethod(ref);
1834}
1835
1836bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001837 if (!compiler_options_->IsVerificationEnabled()) {
1838 // If we didn't verify, every cast has to be treated as non-safe.
1839 return false;
1840 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001841 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1842 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001843 if (result) {
1844 stats_->SafeCast();
1845 } else {
1846 stats_->NotASafeCast();
1847 }
1848 return result;
1849}
1850
Mathieu Chartier90443472015-07-16 20:32:27 -07001851class CompilationVisitor {
1852 public:
1853 virtual ~CompilationVisitor() {}
1854 virtual void Visit(size_t index) = 0;
1855};
1856
Brian Carlstrom7940e442013-07-12 13:46:57 -07001857class ParallelCompilationManager {
1858 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001859 ParallelCompilationManager(ClassLinker* class_linker,
1860 jobject class_loader,
1861 CompilerDriver* compiler,
1862 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001863 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001864 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001865 : index_(0),
1866 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001867 class_loader_(class_loader),
1868 compiler_(compiler),
1869 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001870 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001871 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872
1873 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001874 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001875 return class_linker_;
1876 }
1877
1878 jobject GetClassLoader() const {
1879 return class_loader_;
1880 }
1881
1882 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001883 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001884 return compiler_;
1885 }
1886
1887 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001888 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001889 return dex_file_;
1890 }
1891
Andreas Gampede7b4362014-07-28 18:38:57 -07001892 const std::vector<const DexFile*>& GetDexFiles() const {
1893 return dex_files_;
1894 }
1895
Mathieu Chartier90443472015-07-16 20:32:27 -07001896 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1897 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898 Thread* self = Thread::Current();
1899 self->AssertNoPendingException();
1900 CHECK_GT(work_units, 0U);
1901
Ian Rogers3e5cf302014-05-20 16:40:37 -07001902 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001903 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001904 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001905 }
1906 thread_pool_->StartWorkers(self);
1907
1908 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1909 // thread destructor's called below perform join).
1910 CHECK_NE(self->GetState(), kRunnable);
1911
1912 // Wait for all the worker threads to finish.
1913 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001914
1915 // And stop the workers accepting jobs.
1916 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001917 }
1918
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001919 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001920 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001921 }
1922
Brian Carlstrom7940e442013-07-12 13:46:57 -07001923 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001924 class ForAllClosure : public Task {
1925 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001926 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001927 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001928 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001929 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001930
1931 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001932 while (true) {
1933 const size_t index = manager_->NextIndex();
1934 if (UNLIKELY(index >= end_)) {
1935 break;
1936 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001937 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938 self->AssertNoPendingException();
1939 }
1940 }
1941
1942 virtual void Finalize() {
1943 delete this;
1944 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001945
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001947 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001949 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001950 };
1951
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001952 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001953 ClassLinker* const class_linker_;
1954 const jobject class_loader_;
1955 CompilerDriver* const compiler_;
1956 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001957 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001958 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001959
1960 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001961};
1962
Jeff Hao0e49b422013-11-08 12:16:56 -08001963// A fast version of SkipClass above if the class pointer is available
1964// that avoids the expensive FindInClassPath search.
1965static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -07001966 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001967 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001968 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1969 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001970 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001971 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1972 << dex_file.GetLocation() << " previously found in "
1973 << original_dex_file.GetLocation();
1974 }
1975 return true;
1976 }
1977 return false;
1978}
1979
Mathieu Chartier70b63482014-06-27 17:19:04 -07001980static void CheckAndClearResolveException(Thread* self)
Mathieu Chartier90443472015-07-16 20:32:27 -07001981 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001982 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001983 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001984 std::string temp;
1985 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1986 const char* expected_exceptions[] = {
1987 "Ljava/lang/IllegalAccessError;",
1988 "Ljava/lang/IncompatibleClassChangeError;",
1989 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001990 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001991 "Ljava/lang/NoClassDefFoundError;",
1992 "Ljava/lang/NoSuchFieldError;",
1993 "Ljava/lang/NoSuchMethodError;"
1994 };
1995 bool found = false;
1996 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1997 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1998 found = true;
1999 }
2000 }
2001 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002002 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002003 }
2004 self->ClearException();
2005}
2006
Mathieu Chartier90443472015-07-16 20:32:27 -07002007class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2008 public:
2009 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2010 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002011
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002012 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002013 ATRACE_CALL();
2014 Thread* const self = Thread::Current();
2015 jobject jclass_loader = manager_->GetClassLoader();
2016 const DexFile& dex_file = *manager_->GetDexFile();
2017 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002018
Mathieu Chartier90443472015-07-16 20:32:27 -07002019 // If an instance field is final then we need to have a barrier on the return, static final
2020 // fields are assigned within the lock held for class initialization. Conservatively assume
2021 // constructor barriers are always required.
2022 bool requires_constructor_barrier = true;
2023
2024 // Method and Field are the worst. We can't resolve without either
2025 // context from the code use (to disambiguate virtual vs direct
2026 // method and instance vs static field) or from class
2027 // definitions. While the compiler will resolve what it can as it
2028 // needs it, here we try to resolve fields and methods used in class
2029 // definitions, since many of them many never be referenced by
2030 // generated code.
2031 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2032 ScopedObjectAccess soa(self);
2033 StackHandleScope<2> hs(soa.Self());
2034 Handle<mirror::ClassLoader> class_loader(
2035 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002036 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2037 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002038 // Resolve the class.
2039 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2040 class_loader);
2041 bool resolve_fields_and_methods;
2042 if (klass == nullptr) {
2043 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2044 // attempt to resolve methods and fields when there is no declaring class.
2045 CheckAndClearResolveException(soa.Self());
2046 resolve_fields_and_methods = false;
2047 } else {
2048 // We successfully resolved a class, should we skip it?
2049 if (SkipClass(jclass_loader, dex_file, klass)) {
2050 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002051 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002052 // We want to resolve the methods and fields eagerly.
2053 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002054 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002055 // Note the class_data pointer advances through the headers,
2056 // static fields, instance fields, direct methods, and virtual
2057 // methods.
2058 const uint8_t* class_data = dex_file.GetClassData(class_def);
2059 if (class_data == nullptr) {
2060 // Empty class such as a marker interface.
2061 requires_constructor_barrier = false;
2062 } else {
2063 ClassDataItemIterator it(dex_file, class_data);
2064 while (it.HasNextStaticField()) {
2065 if (resolve_fields_and_methods) {
2066 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2067 dex_cache, class_loader, true);
2068 if (field == nullptr) {
2069 CheckAndClearResolveException(soa.Self());
2070 }
Ian Rogers68b56852014-08-29 20:19:11 -07002071 }
2072 it.Next();
2073 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002074 // We require a constructor barrier if there are final instance fields.
2075 requires_constructor_barrier = false;
2076 while (it.HasNextInstanceField()) {
2077 if (it.MemberIsFinal()) {
2078 requires_constructor_barrier = true;
2079 }
2080 if (resolve_fields_and_methods) {
2081 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2082 dex_cache, class_loader, false);
2083 if (field == nullptr) {
2084 CheckAndClearResolveException(soa.Self());
2085 }
Ian Rogers68b56852014-08-29 20:19:11 -07002086 }
2087 it.Next();
2088 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002089 if (resolve_fields_and_methods) {
2090 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002091 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002092 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2093 it.GetMethodInvokeType(class_def));
2094 if (method == nullptr) {
2095 CheckAndClearResolveException(soa.Self());
2096 }
2097 it.Next();
2098 }
2099 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002100 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002101 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2102 it.GetMethodInvokeType(class_def));
2103 if (method == nullptr) {
2104 CheckAndClearResolveException(soa.Self());
2105 }
2106 it.Next();
2107 }
2108 DCHECK(!it.HasNext());
2109 }
2110 }
2111 if (requires_constructor_barrier) {
2112 manager_->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002113 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002114 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002115
Mathieu Chartier90443472015-07-16 20:32:27 -07002116 private:
2117 const ParallelCompilationManager* const manager_;
2118};
2119
2120class ResolveTypeVisitor : public CompilationVisitor {
2121 public:
2122 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2123 }
2124 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002125 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002126 ScopedObjectAccess soa(Thread::Current());
2127 ClassLinker* class_linker = manager_->GetClassLinker();
2128 const DexFile& dex_file = *manager_->GetDexFile();
2129 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002130 Handle<mirror::ClassLoader> class_loader(
2131 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002132 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2133 dex_file,
2134 class_linker->GetOrCreateAllocatorForClassLoader(class_loader.Get()))));
Mathieu Chartier90443472015-07-16 20:32:27 -07002135 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002136
Mathieu Chartier90443472015-07-16 20:32:27 -07002137 if (klass == nullptr) {
2138 soa.Self()->AssertPendingException();
2139 mirror::Throwable* exception = soa.Self()->GetException();
2140 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2141 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2142 // There's little point continuing compilation if the heap is exhausted.
2143 LOG(FATAL) << "Out of memory during type resolution for compilation";
2144 }
2145 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002146 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002147 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002148
2149 private:
2150 const ParallelCompilationManager* const manager_;
2151};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002152
Andreas Gampeace0dc12016-01-20 13:33:13 -08002153void CompilerDriver::ResolveDexFile(jobject class_loader,
2154 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002155 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002156 ThreadPool* thread_pool,
2157 size_t thread_count,
2158 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002159 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2160
2161 // TODO: we could resolve strings here, although the string table is largely filled with class
2162 // and method names.
2163
Andreas Gampede7b4362014-07-28 18:38:57 -07002164 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2165 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002166 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002167 // For images we resolve all types, such as array, whereas for applications just those with
2168 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002169 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002170 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002171 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002172 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002173
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002174 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002175 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002176 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002177}
2178
Andreas Gampeace0dc12016-01-20 13:33:13 -08002179void CompilerDriver::SetVerified(jobject class_loader,
2180 const std::vector<const DexFile*>& dex_files,
2181 TimingLogger* timings) {
2182 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002183 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002184 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002185 SetVerifiedDexFile(class_loader,
2186 *dex_file,
2187 dex_files,
2188 parallel_thread_pool_.get(),
2189 parallel_thread_count_,
2190 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002191 }
2192}
2193
Andreas Gampeace0dc12016-01-20 13:33:13 -08002194void CompilerDriver::Verify(jobject class_loader,
2195 const std::vector<const DexFile*>& dex_files,
2196 TimingLogger* timings) {
2197 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2198 // as all should have been resolved before. As such, doing this in parallel should still
2199 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002200 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002201 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002202 VerifyDexFile(class_loader,
2203 *dex_file,
2204 dex_files,
2205 parallel_thread_pool_.get(),
2206 parallel_thread_count_,
2207 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002208 }
2209}
2210
Mathieu Chartier90443472015-07-16 20:32:27 -07002211class VerifyClassVisitor : public CompilationVisitor {
2212 public:
Andreas Gampe7fe30232016-03-25 16:58:00 -07002213 VerifyClassVisitor(const ParallelCompilationManager* manager, LogSeverity log_level)
2214 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002215
Mathieu Chartier90443472015-07-16 20:32:27 -07002216 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2217 ATRACE_CALL();
2218 ScopedObjectAccess soa(Thread::Current());
2219 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002220 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2221 // Skip verification since the class is not in the profile.
2222 return;
2223 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002224 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2225 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2226 ClassLinker* class_linker = manager_->GetClassLinker();
2227 jobject jclass_loader = manager_->GetClassLoader();
2228 StackHandleScope<3> hs(soa.Self());
2229 Handle<mirror::ClassLoader> class_loader(
2230 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2231 Handle<mirror::Class> klass(
2232 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2233 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002234 CHECK(soa.Self()->IsExceptionPending());
2235 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002236
2237 /*
2238 * At compile time, we can still structurally verify the class even if FindClass fails.
2239 * This is to ensure the class is structurally sound for compilation. An unsound class
2240 * will be rejected by the verifier and later skipped during compilation in the compiler.
2241 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002242 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2243 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002244 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002245 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2246 &dex_file,
2247 dex_cache,
2248 class_loader,
2249 &class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002250 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002251 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002252 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002253 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002254 verifier::MethodVerifier::kHardFailure) {
2255 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2256 << " because: " << error_msg;
2257 manager_->GetCompiler()->SetHadHardVerifierFailure();
2258 }
2259 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2260 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002261 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002262
2263 if (klass->IsErroneous()) {
2264 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2265 CHECK(soa.Self()->IsExceptionPending());
2266 soa.Self()->ClearException();
2267 manager_->GetCompiler()->SetHadHardVerifierFailure();
2268 }
2269
2270 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2271 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2272
2273 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2274 // we rely on things working OK without verification when the decryption dialog is brought up.
2275 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002276 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2277 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002278 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002279 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002280 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002281
2282 private:
2283 const ParallelCompilationManager* const manager_;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002284 const LogSeverity log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002285};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002286
Andreas Gampeace0dc12016-01-20 13:33:13 -08002287void CompilerDriver::VerifyDexFile(jobject class_loader,
2288 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002289 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002290 ThreadPool* thread_pool,
2291 size_t thread_count,
2292 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002293 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002294 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002295 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2296 thread_pool);
Andreas Gampe7fe30232016-03-25 16:58:00 -07002297 LogSeverity log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2298 ? LogSeverity::INTERNAL_FATAL
2299 : LogSeverity::WARNING;
2300 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002301 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002302}
2303
Mathieu Chartier90443472015-07-16 20:32:27 -07002304class SetVerifiedClassVisitor : public CompilationVisitor {
2305 public:
2306 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2307
2308 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2309 ATRACE_CALL();
2310 ScopedObjectAccess soa(Thread::Current());
2311 const DexFile& dex_file = *manager_->GetDexFile();
2312 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2313 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2314 ClassLinker* class_linker = manager_->GetClassLinker();
2315 jobject jclass_loader = manager_->GetClassLoader();
2316 StackHandleScope<3> hs(soa.Self());
2317 Handle<mirror::ClassLoader> class_loader(
2318 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2319 Handle<mirror::Class> klass(
2320 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2321 // Class might have failed resolution. Then don't set it to verified.
2322 if (klass.Get() != nullptr) {
2323 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2324 // very wrong.
2325 if (klass->IsResolved()) {
2326 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2327 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2328 // Set class status to verified.
2329 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2330 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2331 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002332 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002333 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002334 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002335 }
2336 // Record the final class status if necessary.
2337 ClassReference ref(manager_->GetDexFile(), class_def_index);
2338 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002339 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002340 } else {
2341 Thread* self = soa.Self();
2342 DCHECK(self->IsExceptionPending());
2343 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002344 }
2345 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002346
2347 private:
2348 const ParallelCompilationManager* const manager_;
2349};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002350
Andreas Gampeace0dc12016-01-20 13:33:13 -08002351void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2352 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002353 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002354 ThreadPool* thread_pool,
2355 size_t thread_count,
2356 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002357 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2358 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2359 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2360 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002361 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002362 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002363}
2364
Mathieu Chartier90443472015-07-16 20:32:27 -07002365class InitializeClassVisitor : public CompilationVisitor {
2366 public:
2367 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002368
Mathieu Chartier90443472015-07-16 20:32:27 -07002369 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2370 ATRACE_CALL();
2371 jobject jclass_loader = manager_->GetClassLoader();
2372 const DexFile& dex_file = *manager_->GetDexFile();
2373 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2374 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2375 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002376
Mathieu Chartier90443472015-07-16 20:32:27 -07002377 ScopedObjectAccess soa(Thread::Current());
2378 StackHandleScope<3> hs(soa.Self());
2379 Handle<mirror::ClassLoader> class_loader(
2380 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2381 Handle<mirror::Class> klass(
2382 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2383
2384 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2385 // Only try to initialize classes that were successfully verified.
2386 if (klass->IsVerified()) {
2387 // Attempt to initialize the class but bail if we either need to initialize the super-class
2388 // or static fields.
2389 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002390 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002391 // We don't want non-trivial class initialization occurring on multiple threads due to
2392 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2393 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2394 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2395 // after first initializing its parents, whose locks are acquired. This leads to a
2396 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2397 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2398 // than use a special Object for the purpose we use the Class of java.lang.Class.
2399 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2400 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2401 // Attempt to initialize allowing initialization of parent classes but still not static
2402 // fields.
2403 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2404 if (!klass->IsInitialized()) {
2405 // We need to initialize static fields, we only do this for image classes that aren't
2406 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002407 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002408 manager_->GetCompiler()->IsImageClass(descriptor) &&
2409 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2410 if (can_init_static_fields) {
2411 VLOG(compiler) << "Initializing: " << descriptor;
2412 // TODO multithreading support. We should ensure the current compilation thread has
2413 // exclusive access to the runtime and the transaction. To achieve this, we could use
2414 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2415 // checks in Thread::AssertThreadSuspensionIsAllowable.
2416 Runtime* const runtime = Runtime::Current();
2417 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002418
Mathieu Chartier90443472015-07-16 20:32:27 -07002419 // Run the class initializer in transaction mode.
2420 runtime->EnterTransactionMode(&transaction);
2421 const mirror::Class::Status old_status = klass->GetStatus();
2422 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2423 true);
2424 // TODO we detach transaction from runtime to indicate we quit the transactional
2425 // mode which prevents the GC from visiting objects modified during the transaction.
2426 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002427
Mathieu Chartier90443472015-07-16 20:32:27 -07002428 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2429 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002430
Mathieu Chartier90443472015-07-16 20:32:27 -07002431 if (!success) {
2432 CHECK(soa.Self()->IsExceptionPending());
2433 mirror::Throwable* exception = soa.Self()->GetException();
2434 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2435 << exception->Dump();
2436 std::ostream* file_log = manager_->GetCompiler()->
2437 GetCompilerOptions().GetInitFailureOutput();
2438 if (file_log != nullptr) {
2439 *file_log << descriptor << "\n";
2440 *file_log << exception->Dump() << "\n";
2441 }
2442 soa.Self()->ClearException();
2443 transaction.Rollback();
2444 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002445 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002446 }
2447 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002448 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002449 }
2450 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002451 // Record the final class status if necessary.
2452 ClassReference ref(manager_->GetDexFile(), class_def_index);
2453 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002454 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002455 // Clear any class not found or verification exceptions.
2456 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002457 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002458
2459 private:
2460 const ParallelCompilationManager* const manager_;
2461};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002462
Andreas Gampeace0dc12016-01-20 13:33:13 -08002463void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2464 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002465 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002466 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002467 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002468
2469 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2470 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2471 ThreadPool* init_thread_pool = force_determinism
2472 ? single_thread_pool_.get()
2473 : parallel_thread_pool_.get();
2474 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2475
Brian Carlstrom7940e442013-07-12 13:46:57 -07002476 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002477 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002478 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002479 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002480 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002481 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002482 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002483 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002484 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002485}
2486
2487void CompilerDriver::InitializeClasses(jobject class_loader,
2488 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002489 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002490 for (size_t i = 0; i != dex_files.size(); ++i) {
2491 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002492 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002493 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002494 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002495 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002496 // Prune garbage objects created during aborted transactions.
2497 Runtime::Current()->GetHeap()->CollectGarbage(true);
2498 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002499}
2500
Andreas Gampeace0dc12016-01-20 13:33:13 -08002501void CompilerDriver::Compile(jobject class_loader,
2502 const std::vector<const DexFile*>& dex_files,
2503 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002504 if (kDebugProfileGuidedCompilation) {
2505 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2506 ((profile_compilation_info_ == nullptr)
2507 ? "null"
2508 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002509 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002510 for (size_t i = 0; i != dex_files.size(); ++i) {
2511 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002512 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002513 CompileDexFile(class_loader,
2514 *dex_file,
2515 dex_files,
2516 parallel_thread_pool_.get(),
2517 parallel_thread_count_,
2518 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002519 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2520 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2521 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002522 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002523 }
Andreas Gampe8d295f82015-01-20 14:50:21 -08002524 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002525}
2526
Mathieu Chartier90443472015-07-16 20:32:27 -07002527class CompileClassVisitor : public CompilationVisitor {
2528 public:
2529 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2530
2531 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2532 ATRACE_CALL();
2533 const DexFile& dex_file = *manager_->GetDexFile();
2534 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2535 ClassLinker* class_linker = manager_->GetClassLinker();
2536 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002537 ClassReference ref(&dex_file, class_def_index);
2538 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2539 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002540 return;
2541 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002542 // Use a scoped object access to perform to the quick SkipClass check.
2543 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2544 ScopedObjectAccess soa(Thread::Current());
2545 StackHandleScope<3> hs(soa.Self());
2546 Handle<mirror::ClassLoader> class_loader(
2547 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2548 Handle<mirror::Class> klass(
2549 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2550 Handle<mirror::DexCache> dex_cache;
2551 if (klass.Get() == nullptr) {
2552 soa.Self()->AssertPendingException();
2553 soa.Self()->ClearException();
2554 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2555 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2556 return;
2557 } else {
2558 dex_cache = hs.NewHandle(klass->GetDexCache());
2559 }
2560
Mathieu Chartier90443472015-07-16 20:32:27 -07002561 const uint8_t* class_data = dex_file.GetClassData(class_def);
2562 if (class_data == nullptr) {
2563 // empty class, probably a marker interface
2564 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002565 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002566
Mathieu Chartier736b5602015-09-02 14:54:11 -07002567 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002568 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002569
Mathieu Chartier90443472015-07-16 20:32:27 -07002570 CompilerDriver* const driver = manager_->GetCompiler();
2571
2572 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002573 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002574 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002575
Mathieu Chartier90443472015-07-16 20:32:27 -07002576 ClassDataItemIterator it(dex_file, class_data);
2577 // Skip fields
2578 while (it.HasNextStaticField()) {
2579 it.Next();
2580 }
2581 while (it.HasNextInstanceField()) {
2582 it.Next();
2583 }
2584
2585 bool compilation_enabled = driver->IsClassToCompile(
2586 dex_file.StringByTypeIdx(class_def.class_idx_));
2587
2588 // Compile direct methods
2589 int64_t previous_direct_method_idx = -1;
2590 while (it.HasNextDirectMethod()) {
2591 uint32_t method_idx = it.GetMemberIndex();
2592 if (method_idx == previous_direct_method_idx) {
2593 // smali can create dex files with two encoded_methods sharing the same method_idx
2594 // http://code.google.com/p/smali/issues/detail?id=119
2595 it.Next();
2596 continue;
2597 }
2598 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002599 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002600 it.GetMethodInvokeType(class_def), class_def_index,
2601 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002602 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002603 it.Next();
2604 }
2605 // Compile virtual methods
2606 int64_t previous_virtual_method_idx = -1;
2607 while (it.HasNextVirtualMethod()) {
2608 uint32_t method_idx = it.GetMemberIndex();
2609 if (method_idx == previous_virtual_method_idx) {
2610 // smali can create dex files with two encoded_methods sharing the same method_idx
2611 // http://code.google.com/p/smali/issues/detail?id=119
2612 it.Next();
2613 continue;
2614 }
2615 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002616 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002617 it.GetMethodInvokeType(class_def), class_def_index,
2618 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002619 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002620 it.Next();
2621 }
2622 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002623 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002624
2625 private:
2626 const ParallelCompilationManager* const manager_;
2627};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002628
Andreas Gampeace0dc12016-01-20 13:33:13 -08002629void CompilerDriver::CompileDexFile(jobject class_loader,
2630 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002631 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002632 ThreadPool* thread_pool,
2633 size_t thread_count,
2634 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002635 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002636 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002637 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002638 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002639 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002640}
2641
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002642void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2643 CompiledMethod* const compiled_method,
2644 size_t non_relative_linker_patch_count) {
2645 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2646 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2647 {
2648 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2649 compiled_methods_.Put(method_ref, compiled_method);
2650 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002651 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002652 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2653 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002654}
2655
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002656void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2657 CompiledMethod* compiled_method = nullptr;
2658 {
2659 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2660 auto it = compiled_methods_.find(method_ref);
2661 if (it != compiled_methods_.end()) {
2662 compiled_method = it->second;
2663 compiled_methods_.erase(it);
2664 }
2665 }
2666 if (compiled_method != nullptr) {
2667 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2668 }
2669}
2670
Brian Carlstrom7940e442013-07-12 13:46:57 -07002671CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2672 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2673 ClassTable::const_iterator it = compiled_classes_.find(ref);
2674 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002675 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002676 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002677 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002678 return it->second;
2679}
2680
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002681void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2682 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2683 auto it = compiled_classes_.find(ref);
2684 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2685 // An entry doesn't exist or the status is lower than the new status.
2686 if (it != compiled_classes_.end()) {
2687 CHECK_GT(status, it->second->GetStatus());
2688 delete it->second;
2689 }
2690 switch (status) {
2691 case mirror::Class::kStatusNotReady:
2692 case mirror::Class::kStatusError:
2693 case mirror::Class::kStatusRetryVerificationAtRuntime:
2694 case mirror::Class::kStatusVerified:
2695 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002696 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002697 break; // Expected states.
2698 default:
2699 LOG(FATAL) << "Unexpected class status for class "
2700 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2701 << " of " << status;
2702 }
2703 CompiledClass* compiled_class = new CompiledClass(status);
2704 compiled_classes_.Overwrite(ref, compiled_class);
2705 }
2706}
2707
Brian Carlstrom7940e442013-07-12 13:46:57 -07002708CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2709 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2710 MethodTable::const_iterator it = compiled_methods_.find(ref);
2711 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002712 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002713 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002714 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002715 return it->second;
2716}
2717
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002718bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2719 uint16_t class_def_idx,
2720 const DexFile& dex_file) const {
2721 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2722 if (verified_method != nullptr) {
2723 return !verified_method->HasVerificationFailures();
2724 }
2725
2726 // If we can't find verification metadata, check if this is a system class (we trust that system
2727 // classes have their methods verified). If it's not, be conservative and assume the method
2728 // has not been verified successfully.
2729
2730 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2731 // even if methods are not found in the verification cache.
2732 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2733 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2734 Thread* self = Thread::Current();
2735 ScopedObjectAccess soa(self);
2736 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2737 if (!is_system_class) {
2738 self->ClearException();
2739 }
2740 return is_system_class;
2741}
2742
Vladimir Markof4da6752014-08-01 19:04:18 +01002743size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2744 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2745 return non_relative_linker_patch_count_;
2746}
2747
Brian Carlstrom7940e442013-07-12 13:46:57 -07002748void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002749 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002750 WriterMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002751 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2752}
2753
2754bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Calin Juravle27df7582015-04-17 19:12:31 +01002755 uint16_t class_def_index) const {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002756 ReaderMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002757 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2758}
2759
Andreas Gampe8d295f82015-01-20 14:50:21 -08002760std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002761 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002762 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002763 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002764 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002765 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002766#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002767 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002768 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2769 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002770 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2771 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002772#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002773 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002774 return oss.str();
2775}
2776
Jeff Hao848f70a2014-01-15 13:49:50 -08002777bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2778 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2779 return strcmp(type, "Ljava/lang/String;") == 0;
2780}
2781
2782bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2783 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
2784 size_t pointer_size = InstructionSetPointerSize(GetInstructionSet());
2785 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2786 return inliner->IsStringInitMethodIndex(method_index);
2787}
2788
Jeff Haodcdc85b2015-12-04 14:06:18 -08002789bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2790 const DexFile* inlined_into) const {
2791 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2792 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002793 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2794 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002795 return false;
2796 }
2797
2798 return true;
2799}
2800
Andreas Gampeace0dc12016-01-20 13:33:13 -08002801void CompilerDriver::InitializeThreadPools() {
2802 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2803 parallel_thread_pool_.reset(
2804 new ThreadPool("Compiler driver thread pool", parallel_count));
2805 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2806}
2807
2808void CompilerDriver::FreeThreadPools() {
2809 parallel_thread_pool_.reset();
2810 single_thread_pool_.reset();
2811}
2812
Brian Carlstrom7940e442013-07-12 13:46:57 -07002813} // namespace art