blob: d0a8335a99a8f62ee1d560203af9edc0fb8930c8 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Andreas Gampeb0f370e2014-09-25 22:51:40 -070019#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070020#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include <unistd.h>
22
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010029#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070030#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080032#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010035#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070036#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000038#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000039#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "dex_compilation_unit.h"
41#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080042#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070043#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000044#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000045#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000046#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080047#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080048#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070050#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "runtime.h"
52#include "gc/accounting/card_table-inl.h"
53#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/space.h"
56#include "mirror/class_loader.h"
57#include "mirror/class-inl.h"
58#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
61#include "mirror/throwable.h"
62#include "scoped_thread_state_change.h"
63#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070066#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070068#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010069#include "transaction.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010070#include "utils/array_ref.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000071#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080072#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000074#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
Brian Carlstrom7940e442013-07-12 13:46:57 -070076namespace art {
77
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070078static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
79
Calin Juravle226501b2015-12-11 14:41:31 +000080// Print additional info during profile guided compilation.
81static constexpr bool kDebugProfileGuidedCompilation = false;
82
Brian Carlstrom7940e442013-07-12 13:46:57 -070083static double Percentage(size_t x, size_t y) {
84 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
85}
86
87static void DumpStat(size_t x, size_t y, const char* str) {
88 if (x == 0 && y == 0) {
89 return;
90 }
Ian Rogerse732ef12013-10-09 15:22:24 -070091 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070092}
93
Vladimir Markof096aad2014-01-23 15:51:58 +000094class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070095 public:
96 AOTCompilationStats()
97 : stats_lock_("AOT compilation statistics lock"),
98 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
99 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
100 resolved_types_(0), unresolved_types_(0),
101 resolved_instance_fields_(0), unresolved_instance_fields_(0),
102 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
103 type_based_devirtualization_(0),
104 safe_casts_(0), not_safe_casts_(0) {
105 for (size_t i = 0; i <= kMaxInvokeType; i++) {
106 resolved_methods_[i] = 0;
107 unresolved_methods_[i] = 0;
108 virtual_made_direct_[i] = 0;
109 direct_calls_to_boot_[i] = 0;
110 direct_methods_to_boot_[i] = 0;
111 }
112 }
113
114 void Dump() {
115 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
116 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
117 DumpStat(resolved_types_, unresolved_types_, "types resolved");
118 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
119 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
120 "static fields resolved");
121 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
122 "static fields local to a class");
123 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
124 // Note, the code below subtracts the stat value so that when added to the stat value we have
125 // 100% of samples. TODO: clean this up.
126 DumpStat(type_based_devirtualization_,
127 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
128 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
129 type_based_devirtualization_,
130 "virtual/interface calls made direct based on type information");
131
132 for (size_t i = 0; i <= kMaxInvokeType; i++) {
133 std::ostringstream oss;
134 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
135 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
136 if (virtual_made_direct_[i] > 0) {
137 std::ostringstream oss2;
138 oss2 << static_cast<InvokeType>(i) << " methods made direct";
139 DumpStat(virtual_made_direct_[i],
140 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
141 oss2.str().c_str());
142 }
143 if (direct_calls_to_boot_[i] > 0) {
144 std::ostringstream oss2;
145 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
146 DumpStat(direct_calls_to_boot_[i],
147 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
148 oss2.str().c_str());
149 }
150 if (direct_methods_to_boot_[i] > 0) {
151 std::ostringstream oss2;
152 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
153 DumpStat(direct_methods_to_boot_[i],
154 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
155 oss2.str().c_str());
156 }
157 }
158 }
159
160// Allow lossy statistics in non-debug builds.
161#ifndef NDEBUG
162#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
163#else
164#define STATS_LOCK()
165#endif
166
Mathieu Chartier90443472015-07-16 20:32:27 -0700167 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 STATS_LOCK();
169 types_in_dex_cache_++;
170 }
171
Mathieu Chartier90443472015-07-16 20:32:27 -0700172 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 STATS_LOCK();
174 types_not_in_dex_cache_++;
175 }
176
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 STATS_LOCK();
179 strings_in_dex_cache_++;
180 }
181
Mathieu Chartier90443472015-07-16 20:32:27 -0700182 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 STATS_LOCK();
184 strings_not_in_dex_cache_++;
185 }
186
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 STATS_LOCK();
189 resolved_types_++;
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 STATS_LOCK();
194 unresolved_types_++;
195 }
196
Mathieu Chartier90443472015-07-16 20:32:27 -0700197 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 STATS_LOCK();
199 resolved_instance_fields_++;
200 }
201
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 STATS_LOCK();
204 unresolved_instance_fields_++;
205 }
206
Mathieu Chartier90443472015-07-16 20:32:27 -0700207 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 STATS_LOCK();
209 resolved_local_static_fields_++;
210 }
211
Mathieu Chartier90443472015-07-16 20:32:27 -0700212 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 STATS_LOCK();
214 resolved_static_fields_++;
215 }
216
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 STATS_LOCK();
219 unresolved_static_fields_++;
220 }
221
222 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 STATS_LOCK();
225 type_based_devirtualization_++;
226 }
227
228 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 DCHECK_LE(type, kMaxInvokeType);
231 STATS_LOCK();
232 resolved_methods_[type]++;
233 }
234
235 // Indicate that a method of the given type was unresolved at compile time as it was in an
236 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 DCHECK_LE(type, kMaxInvokeType);
239 STATS_LOCK();
240 unresolved_methods_[type]++;
241 }
242
243 // Indicate that a type of virtual method dispatch has been converted into a direct method
244 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700245 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
247 STATS_LOCK();
248 virtual_made_direct_[type]++;
249 }
250
251 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700252 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 DCHECK_LE(type, kMaxInvokeType);
254 STATS_LOCK();
255 direct_calls_to_boot_[type]++;
256 }
257
258 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700259 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 DCHECK_LE(type, kMaxInvokeType);
261 STATS_LOCK();
262 direct_methods_to_boot_[type]++;
263 }
264
Mathieu Chartier90443472015-07-16 20:32:27 -0700265 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000266 STATS_LOCK();
267 if (flags == 0) {
268 unresolved_methods_[type]++;
269 } else {
270 DCHECK_NE((flags & kFlagMethodResolved), 0);
271 resolved_methods_[type]++;
272 if ((flags & kFlagVirtualMadeDirect) != 0) {
273 virtual_made_direct_[type]++;
274 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
275 type_based_devirtualization_++;
276 }
277 } else {
278 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
279 }
280 if ((flags & kFlagDirectCallToBoot) != 0) {
281 direct_calls_to_boot_[type]++;
282 }
283 if ((flags & kFlagDirectMethodToBoot) != 0) {
284 direct_methods_to_boot_[type]++;
285 }
286 }
287 }
288
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700290 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 STATS_LOCK();
292 safe_casts_++;
293 }
294
295 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 STATS_LOCK();
298 not_safe_casts_++;
299 }
300
301 private:
302 Mutex stats_lock_;
303
304 size_t types_in_dex_cache_;
305 size_t types_not_in_dex_cache_;
306
307 size_t strings_in_dex_cache_;
308 size_t strings_not_in_dex_cache_;
309
310 size_t resolved_types_;
311 size_t unresolved_types_;
312
313 size_t resolved_instance_fields_;
314 size_t unresolved_instance_fields_;
315
316 size_t resolved_local_static_fields_;
317 size_t resolved_static_fields_;
318 size_t unresolved_static_fields_;
319 // Type based devirtualization for invoke interface and virtual.
320 size_t type_based_devirtualization_;
321
322 size_t resolved_methods_[kMaxInvokeType + 1];
323 size_t unresolved_methods_[kMaxInvokeType + 1];
324 size_t virtual_made_direct_[kMaxInvokeType + 1];
325 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
326 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
327
328 size_t safe_casts_;
329 size_t not_safe_casts_;
330
331 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
332};
333
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100334class CompilerDriver::DexFileMethodSet {
335 public:
336 explicit DexFileMethodSet(const DexFile& dex_file)
337 : dex_file_(dex_file),
338 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
339 }
340 DexFileMethodSet(DexFileMethodSet&& other) = default;
341
342 const DexFile& GetDexFile() const { return dex_file_; }
343
344 BitVector& GetMethodIndexes() { return method_indexes_; }
345 const BitVector& GetMethodIndexes() const { return method_indexes_; }
346
347 private:
348 const DexFile& dex_file_;
349 BitVector method_indexes_;
350};
351
Jeff Haodcdc85b2015-12-04 14:06:18 -0800352CompilerDriver::CompilerDriver(
353 const CompilerOptions* compiler_options,
354 VerificationResults* verification_results,
355 DexFileToMethodInlinerMap* method_inliner_map,
356 Compiler::Kind compiler_kind,
357 InstructionSet instruction_set,
358 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000359 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700360 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000361 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800362 std::unordered_set<std::string>* compiled_classes,
363 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000364 size_t thread_count,
365 bool dump_stats,
366 bool dump_passes,
367 CumulativeLogger* timer,
368 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200369 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000370 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800371 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000372 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700373 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700374 compiler_kind_(compiler_kind),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700375 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700376 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700377 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 compiled_classes_lock_("compiled classes lock"),
379 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800380 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100381 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800382 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700383 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800385 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700386 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800387 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800388 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389 stats_(new AOTCompilationStats),
390 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000391 dump_passes_(dump_passes),
392 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700393 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700394 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000395 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200396 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000397 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100398 max_arena_alloc_(0),
399 dex_to_dex_references_lock_("dex-to-dex references lock"),
400 dex_to_dex_references_(),
401 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800402 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800403 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700404
Ian Rogers72d32622014-05-06 16:20:11 -0700405 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700406
Mathieu Chartiera8077802016-03-16 19:08:31 -0700407 if (compiler_options->VerifyOnlyProfile()) {
408 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
409 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800410 if (boot_image_) {
411 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
412 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700413}
414
415CompilerDriver::~CompilerDriver() {
416 Thread* self = Thread::Current();
417 {
418 MutexLock mu(self, compiled_classes_lock_);
419 STLDeleteValues(&compiled_classes_);
420 }
421 {
422 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800423 for (auto& pair : compiled_methods_) {
424 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
425 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426 }
Ian Rogers72d32622014-05-06 16:20:11 -0700427 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428}
429
Vladimir Marko35831e82015-09-11 11:59:18 +0100430
Ian Rogersdd7624d2014-03-14 17:43:00 -0700431#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700432 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700433 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 } else { \
436 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700437 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438 }
439
Vladimir Marko93205e32016-04-13 11:59:46 +0100440std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700441 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700442}
443
Vladimir Marko93205e32016-04-13 11:59:46 +0100444std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
445 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700446 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800447}
448
Vladimir Marko93205e32016-04-13 11:59:46 +0100449std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
450 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700451 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700452}
453
Vladimir Marko93205e32016-04-13 11:59:46 +0100454std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
455 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700456 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457}
458
Vladimir Marko93205e32016-04-13 11:59:46 +0100459std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
460 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700461 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700463#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700464
465void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700466 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800467 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700468 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800469
470 InitializeThreadPools();
471
Andreas Gampe8d295f82015-01-20 14:50:21 -0800472 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700473 // Precompile:
474 // 1) Load image classes
475 // 2) Resolve all classes
476 // 3) Attempt to verify all classes
477 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800478 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700479 // Compile:
480 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
481 // compilation.
482 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800483 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700484 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485 if (dump_stats_) {
486 stats_->Dump();
487 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800488
489 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490}
491
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700492static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
493 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
494 const DexFile& dex_file, const DexFile::ClassDef& class_def)
495 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800496 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100497 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700498 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700499 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800500 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700501 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800502 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800503 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700504 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700505 CHECK(self->IsExceptionPending());
506 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700507 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700508 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700509 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
510 // references with actual offsets. We cannot re-verify such instructions.
511 //
512 // We store the verification information in the class status in the oat file, which the linker
513 // can validate (checksums) and use to skip load-time verification. It is thus safe to
514 // optimize when a class has been fully verified before.
515 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200516 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700517 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200518 } else if (klass->IsCompileTimeVerified()) {
519 // Class verification has soft-failed. Anyway, ensure at least correctness.
520 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700521 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200522 } else {
523 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700524 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
525 }
526}
527
528static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
529 Thread* self,
530 const CompilerDriver& driver,
531 jobject jclass_loader,
532 const DexFile& dex_file,
533 const DexFile::ClassDef& class_def) {
534 ScopedObjectAccess soa(self);
535 StackHandleScope<1> hs(soa.Self());
536 Handle<mirror::ClassLoader> class_loader(
537 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
538 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
539}
540
541// Does the runtime for the InstructionSet provide an implementation returned by
542// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
543static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
544 switch (isa) {
545 case kArm:
546 case kArm64:
547 case kThumb2:
548 case kMips:
549 case kMips64:
550 case kX86:
551 case kX86_64: return true;
552 default: return false;
553 }
554}
555
556static void CompileMethod(Thread* self,
557 CompilerDriver* driver,
558 const DexFile::CodeItem* code_item,
559 uint32_t access_flags,
560 InvokeType invoke_type,
561 uint16_t class_def_idx,
562 uint32_t method_idx,
563 jobject class_loader,
564 const DexFile& dex_file,
565 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700566 bool compilation_enabled,
567 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700568 REQUIRES(!driver->compiled_methods_lock_) {
569 DCHECK(driver != nullptr);
570 CompiledMethod* compiled_method = nullptr;
571 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
572 MethodReference method_ref(&dex_file, method_idx);
573
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100574 if (driver->GetCurrentDexToDexMethods() != nullptr) {
575 // This is the second pass when we dex-to-dex compile previously marked methods.
576 // TODO: Refactor the compilation to avoid having to distinguish the two passes
577 // here. That should be done on a higher level. http://b/29089975
578 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
579 const VerifiedMethod* verified_method =
580 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
581 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
582 // for example, relies on it.
583 compiled_method = optimizer::ArtCompileDEX(
584 driver,
585 code_item,
586 access_flags,
587 invoke_type,
588 class_def_idx,
589 method_idx,
590 class_loader,
591 dex_file,
592 (verified_method != nullptr)
593 ? dex_to_dex_compilation_level
594 : optimizer::DexToDexCompilationLevel::kRequired);
595 }
596 } else if ((access_flags & kAccNative) != 0) {
Vladimir Markof6d1e0f2016-05-23 15:32:42 +0100597 // Are we extracting only and have support for generic JNI down calls?
598 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700599 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
600 // Leaving this empty will trigger the generic JNI version
601 } else {
602 compiled_method = driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file);
603 CHECK(compiled_method != nullptr);
604 }
605 } else if ((access_flags & kAccAbstract) != 0) {
606 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000607 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700608 const VerifiedMethod* verified_method =
609 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700610 bool compile = compilation_enabled &&
611 // Basic checks, e.g., not <clinit>.
612 driver->GetVerificationResults()
613 ->IsCandidateForCompilation(method_ref, access_flags) &&
614 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700615 verified_method != nullptr &&
616 // Do not have failures that should punt to the interpreter.
617 !verified_method->HasRuntimeThrow() &&
618 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700619 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700620 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000621 driver->IsMethodToCompile(method_ref) &&
622 driver->ShouldCompileBasedOnProfile(method_ref);
623
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700624 if (compile) {
625 // NOTE: if compiler declines to compile this method, it will return null.
626 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
627 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700628 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700629 }
630 if (compiled_method == nullptr &&
631 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100632 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700633 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100634 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700635 }
636 }
637 if (kTimeCompileMethod) {
638 uint64_t duration_ns = NanoTime() - start_ns;
639 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
640 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
641 << " took " << PrettyDuration(duration_ns);
642 }
643 }
644
645 if (compiled_method != nullptr) {
646 // Count non-relative linker patches.
647 size_t non_relative_linker_patch_count = 0u;
648 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
649 if (!patch.IsPcRelative()) {
650 ++non_relative_linker_patch_count;
651 }
652 }
653 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
654 // When compiling with PIC, there should be zero non-relative linker patches
655 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
656
657 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
658 }
659
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700660 if (self->IsExceptionPending()) {
661 ScopedObjectAccess soa(self);
662 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
663 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200664 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665}
666
Mathieu Chartiere401d142015-04-22 13:56:20 -0700667void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700669 jobject jclass_loader;
670 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700671 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800672 uint32_t method_idx = method->GetDexMethodIndex();
673 uint32_t access_flags = method->GetAccessFlags();
674 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700675 StackHandleScope<1> hs(self);
676 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700677 {
678 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800679 ScopedLocalRef<jobject> local_class_loader(
680 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700681 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
682 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700683 dex_file = method->GetDexFile();
684 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800686 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700687
688 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700689 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700690
691 std::vector<const DexFile*> dex_files;
692 dex_files.push_back(dex_file);
693
Andreas Gampeace0dc12016-01-20 13:33:13 -0800694 InitializeThreadPools();
695
696 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700699 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
700 GetDexToDexCompilationLevel(self,
701 *this,
702 jclass_loader,
703 *dex_file,
704 dex_file->GetClassDef(class_def_idx));
705
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100706 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700707 CompileMethod(self,
708 this,
709 code_item,
710 access_flags,
711 invoke_type,
712 class_def_idx,
713 method_idx,
714 jclass_loader,
715 *dex_file,
716 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700717 true,
718 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100720 ArrayRef<DexFileMethodSet> dex_to_dex_references;
721 {
722 // From this point on, we shall not modify dex_to_dex_references_, so
723 // just grab a reference to it that we use without holding the mutex.
724 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
725 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
726 }
727 if (!dex_to_dex_references.empty()) {
728 DCHECK_EQ(dex_to_dex_references.size(), 1u);
729 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
730 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
731 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
732 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
733 CompileMethod(self,
734 this,
735 code_item,
736 access_flags,
737 invoke_type,
738 class_def_idx,
739 method_idx,
740 jclass_loader,
741 *dex_file,
742 dex_to_dex_compilation_level,
743 true,
744 dex_cache);
745 current_dex_to_dex_methods_ = nullptr;
746 }
747
Andreas Gampeace0dc12016-01-20 13:33:13 -0800748 FreeThreadPools();
749
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800751}
752
Andreas Gampeace0dc12016-01-20 13:33:13 -0800753void CompilerDriver::Resolve(jobject class_loader,
754 const std::vector<const DexFile*>& dex_files,
755 TimingLogger* timings) {
756 // Resolution allocates classes and needs to run single-threaded to be deterministic.
757 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
758 ThreadPool* resolve_thread_pool = force_determinism
759 ? single_thread_pool_.get()
760 : parallel_thread_pool_.get();
761 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
762
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763 for (size_t i = 0; i != dex_files.size(); ++i) {
764 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700765 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800766 ResolveDexFile(class_loader,
767 *dex_file,
768 dex_files,
769 resolve_thread_pool,
770 resolve_thread_count,
771 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772 }
773}
774
Andreas Gampeace0dc12016-01-20 13:33:13 -0800775// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
776// this is single-threaded for simplicity.
777// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
778// stable order.
779
780static void ResolveConstStrings(CompilerDriver* driver,
781 const DexFile& dex_file,
782 const DexFile::CodeItem* code_item) {
783 if (code_item == nullptr) {
784 // Abstract or native method.
785 return;
786 }
787
788 const uint16_t* code_ptr = code_item->insns_;
789 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
790
791 while (code_ptr < code_end) {
792 const Instruction* inst = Instruction::At(code_ptr);
793 switch (inst->Opcode()) {
794 case Instruction::CONST_STRING: {
795 uint32_t string_index = inst->VRegB_21c();
796 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
797 break;
798 }
799 case Instruction::CONST_STRING_JUMBO: {
800 uint32_t string_index = inst->VRegB_31c();
801 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
802 break;
803 }
804
805 default:
806 break;
807 }
808
809 code_ptr += inst->SizeInCodeUnits();
810 }
811}
812
813static void ResolveConstStrings(CompilerDriver* driver,
814 const std::vector<const DexFile*>& dex_files,
815 TimingLogger* timings) {
816 for (const DexFile* dex_file : dex_files) {
817 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
818
819 size_t class_def_count = dex_file->NumClassDefs();
820 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
821 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
822
823 const uint8_t* class_data = dex_file->GetClassData(class_def);
824 if (class_data == nullptr) {
825 // empty class, probably a marker interface
826 continue;
827 }
828
829 ClassDataItemIterator it(*dex_file, class_data);
830 // Skip fields
831 while (it.HasNextStaticField()) {
832 it.Next();
833 }
834 while (it.HasNextInstanceField()) {
835 it.Next();
836 }
837
838 bool compilation_enabled = driver->IsClassToCompile(
839 dex_file->StringByTypeIdx(class_def.class_idx_));
840 if (!compilation_enabled) {
841 // Compilation is skipped, do not resolve const-string in code of this class.
842 // TODO: Make sure that inlining honors this.
843 continue;
844 }
845
846 // Direct methods.
847 int64_t previous_direct_method_idx = -1;
848 while (it.HasNextDirectMethod()) {
849 uint32_t method_idx = it.GetMemberIndex();
850 if (method_idx == previous_direct_method_idx) {
851 // smali can create dex files with two encoded_methods sharing the same method_idx
852 // http://code.google.com/p/smali/issues/detail?id=119
853 it.Next();
854 continue;
855 }
856 previous_direct_method_idx = method_idx;
857 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
858 it.Next();
859 }
860 // Virtual methods.
861 int64_t previous_virtual_method_idx = -1;
862 while (it.HasNextVirtualMethod()) {
863 uint32_t method_idx = it.GetMemberIndex();
864 if (method_idx == previous_virtual_method_idx) {
865 // smali can create dex files with two encoded_methods sharing the same method_idx
866 // http://code.google.com/p/smali/issues/detail?id=119
867 it.Next();
868 continue;
869 }
870 previous_virtual_method_idx = method_idx;
871 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
872 it.Next();
873 }
874 DCHECK(!it.HasNext());
875 }
876 }
877}
878
879inline void CompilerDriver::CheckThreadPools() {
880 DCHECK(parallel_thread_pool_ != nullptr);
881 DCHECK(single_thread_pool_ != nullptr);
882}
883
884void CompilerDriver::PreCompile(jobject class_loader,
885 const std::vector<const DexFile*>& dex_files,
886 TimingLogger* timings) {
887 CheckThreadPools();
888
Brian Carlstrom7940e442013-07-12 13:46:57 -0700889 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800890 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700891
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700892 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
893 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700894 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700895
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700896 // We need to resolve for never_verify since it needs to run dex to dex to add the
897 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700898 // Let the verifier resolve as needed for the verify_only_profile case.
899 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800900 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700901 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
902 }
903
904 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800905 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800906 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700907 }
908
909 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700910 return;
911 }
912
Andreas Gampeace0dc12016-01-20 13:33:13 -0800913 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
914 // Resolve strings from const-string. Do this now to have a deterministic image.
915 ResolveConstStrings(this, dex_files, timings);
916 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
917 }
918
919 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800920 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800922 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
923 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
924 << "situations. Please check the log.";
925 }
926
Andreas Gampeace0dc12016-01-20 13:33:13 -0800927 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800928 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929
930 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800931 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700932}
933
Ian Rogersdfb325e2013-10-30 01:00:44 -0700934bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800935 if (image_classes_ != nullptr) {
936 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700937 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700938 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800939 // No set of image classes, assume we include all the classes.
940 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
941 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942}
943
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800944bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700945 if (classes_to_compile_ == nullptr) {
946 return true;
947 }
948 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800949}
950
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700951bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700952 if (methods_to_compile_ == nullptr) {
953 return true;
954 }
955
956 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
957 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
958}
959
Calin Juravle226501b2015-12-11 14:41:31 +0000960bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
961 if (profile_compilation_info_ == nullptr) {
962 // If we miss profile information it means that we don't do a profile guided compilation.
963 // Return true, and let the other filters decide if the method should be compiled.
964 return true;
965 }
966 bool result = profile_compilation_info_->ContainsMethod(method_ref);
967
968 if (kDebugProfileGuidedCompilation) {
969 LOG(INFO) << "[ProfileGuidedCompilation] "
970 << (result ? "Compiled" : "Skipped") << " method:"
971 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
972 }
973 return result;
974}
975
Mathieu Chartiera8077802016-03-16 19:08:31 -0700976bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
977 uint16_t class_idx) const {
978 if (!compiler_options_->VerifyOnlyProfile()) {
979 // No profile, verify everything.
980 return true;
981 }
982 DCHECK(profile_compilation_info_ != nullptr);
983 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
984 if (kDebugProfileGuidedCompilation) {
985 LOG(INFO) << "[ProfileGuidedCompilation] "
986 << (result ? "Verified" : "Skipped") << " method:"
987 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
988 }
989 return result;
990}
991
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700992class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
993 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -0700994 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700995 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
996 : exceptions_to_resolve_(exceptions_to_resolve) {}
997
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800998 virtual bool operator()(mirror::Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700999 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001000 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001001 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001002 }
1003 return true;
1004 }
1005
1006 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001007 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Vladimir Marko05792b92015-08-03 11:56:49 +01001008 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001009 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1010 if (code_item == nullptr) {
1011 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001013 if (code_item->tries_size_ == 0) {
1014 return; // nothing to process
1015 }
1016 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1017 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1018 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1019 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1020 bool has_catch_all = false;
1021 if (encoded_catch_handler_size <= 0) {
1022 encoded_catch_handler_size = -encoded_catch_handler_size;
1023 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001025 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1026 uint16_t encoded_catch_handler_handlers_type_idx =
1027 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1028 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001029 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1030 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001031 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1032 method_handle->GetDexFile());
1033 }
1034 // ignore address associated with catch handler
1035 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1036 }
1037 if (has_catch_all) {
1038 // ignore catch all address
1039 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1040 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041 }
1042 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001043
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001044 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1045};
1046
1047class RecordImageClassesVisitor : public ClassVisitor {
1048 public:
1049 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1050 : image_classes_(image_classes) {}
1051
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001052 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001053 std::string temp;
1054 image_classes_->insert(klass->GetDescriptor(&temp));
1055 return true;
1056 }
1057
1058 private:
1059 std::unordered_set<std::string>* const image_classes_;
1060};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061
1062// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001063void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001064 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001065 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066 return;
1067 }
1068
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001069 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001070 // Make a first class to load all classes explicitly listed in the file
1071 Thread* self = Thread::Current();
1072 ScopedObjectAccess soa(self);
1073 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001074 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001075 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001076 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001077 StackHandleScope<1> hs(self);
1078 Handle<mirror::Class> klass(
1079 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001080 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001081 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001082 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001083 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084 } else {
1085 ++it;
1086 }
1087 }
1088
1089 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1090 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1091 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001092 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001093 StackHandleScope<1> hs(self);
1094 Handle<mirror::Class> java_lang_Throwable(
1095 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001096 do {
1097 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001098 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1099 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001100 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1101 uint16_t exception_type_idx = exception_type.first;
1102 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001103 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001104 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1105 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001106 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001107 class_linker->ResolveType(*dex_file,
1108 exception_type_idx,
1109 dex_cache,
1110 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001111 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001112 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1113 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1114 LOG(FATAL) << "Failed to resolve class " << descriptor;
1115 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001116 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001117 }
1118 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1119 // more are found
1120 } while (!unresolved_exception_types.empty());
1121
1122 // We walk the roots looking for classes so that we'll pick up the
1123 // above classes plus any classes them depend on such super
1124 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001125 RecordImageClassesVisitor visitor(image_classes_.get());
1126 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001127
1128 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001129}
1130
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001131static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1132 std::unordered_set<std::string>* image_classes)
Mathieu Chartier90443472015-07-16 20:32:27 -07001133 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001134 Thread* self = Thread::Current();
1135 StackHandleScope<1> hs(self);
1136 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001137 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001138 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001139 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001140 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001141 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001142 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1143 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001144 if (!result.second) { // Previously inserted.
1145 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001146 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001147 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001148 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001149 StackHandleScope<1> hs2(self);
1150 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001151 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001152 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001153 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001154 StackHandleScope<1> hs2(self);
1155 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001156 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001157 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001158 StackHandleScope<1> hs2(self);
1159 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001160 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001161 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001162 }
1163}
1164
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001165// Keeps all the data for the update together. Also doubles as the reference visitor.
1166// Note: we can use object pointers because we suspend all threads.
1167class ClinitImageUpdate {
1168 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001169 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1170 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001171 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1172 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001174 *error_msg = "Could not find DexCache class.";
1175 return nullptr;
1176 }
1177
1178 return res.release();
1179 }
1180
1181 ~ClinitImageUpdate() {
1182 // Allow others to suspend again.
1183 self_->EndAssertNoThreadSuspension(old_cause_);
1184 }
1185
1186 // Visitor for VisitReferences.
1187 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001188 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001189 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1190 if (ref != nullptr) {
1191 VisitClinitClassesObject(ref);
1192 }
1193 }
1194
1195 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001196 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1197 const {}
1198
1199 // Ignore class native roots.
1200 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1201 const {}
1202 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001203
Mathieu Chartier90443472015-07-16 20:32:27 -07001204 void Walk() SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001205 // Use the initial classes as roots for a search.
1206 for (mirror::Class* klass_root : image_classes_) {
1207 VisitClinitClassesObject(klass_root);
1208 }
1209 }
1210
1211 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001212 class FindImageClassesVisitor : public ClassVisitor {
1213 public:
1214 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1215
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001216 bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001217 std::string temp;
1218 const char* name = klass->GetDescriptor(&temp);
1219 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1220 data_->image_classes_.push_back(klass);
1221 } else {
1222 // Check whether it is initialized and has a clinit. They must be kept, too.
1223 if (klass->IsInitialized() && klass->FindClassInitializer(
1224 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1225 data_->image_classes_.push_back(klass);
1226 }
1227 }
1228 return true;
1229 }
1230
1231 private:
1232 ClinitImageUpdate* const data_;
1233 };
1234
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001235 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001236 ClassLinker* linker)
Mathieu Chartier90443472015-07-16 20:32:27 -07001237 SHARED_REQUIRES(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001238 image_class_descriptors_(image_class_descriptors), self_(self) {
1239 CHECK(linker != nullptr);
1240 CHECK(image_class_descriptors != nullptr);
1241
1242 // Make sure nobody interferes with us.
1243 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1244
1245 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001246 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1247 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001248
1249 // Find all the already-marked classes.
1250 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001251 FindImageClassesVisitor visitor(this);
1252 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001253 }
1254
1255 void VisitClinitClassesObject(mirror::Object* object) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001256 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001257 DCHECK(object != nullptr);
1258 if (marked_objects_.find(object) != marked_objects_.end()) {
1259 // Already processed.
1260 return;
1261 }
1262
1263 // Mark it.
1264 marked_objects_.insert(object);
1265
1266 if (object->IsClass()) {
1267 // If it is a class, add it.
1268 StackHandleScope<1> hs(self_);
1269 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1270 } else {
1271 // Else visit the object's class.
1272 VisitClinitClassesObject(object->GetClass());
1273 }
1274
Mathieu Chartiere401d142015-04-22 13:56:20 -07001275 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001276 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001277 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001278 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001279 }
1280 }
1281
1282 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001283 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001284 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001285 const mirror::Class* dex_cache_class_;
1286 Thread* const self_;
1287 const char* old_cause_;
1288
1289 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1290};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001291
Ian Rogers3d504072014-03-01 09:16:49 -08001292void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001293 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001294 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001296 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001297
1298 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001299 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001300
1301 std::string error_msg;
1302 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1303 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001304 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001305 &error_msg));
1306 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1307
1308 // Do the marking.
1309 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001310 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001311}
1312
Vladimir Marko07785bb2015-06-15 18:52:54 +01001313bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1314 Runtime* runtime = Runtime::Current();
1315 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001316 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001317 // Having the klass reference here implies that the klass is already loaded.
1318 return true;
1319 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001320 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001321 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1322 // loaded because we don't even know what class loader will be used to load them.
1323 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1324 return class_in_image;
1325 }
1326 std::string temp;
1327 const char* descriptor = klass->GetDescriptor(&temp);
1328 return IsImageClass(descriptor);
1329}
1330
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001331void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1332 MutexLock lock(self, dex_to_dex_references_lock_);
1333 // Since we're compiling one dex file at a time, we need to look for the
1334 // current dex file entry only at the end of dex_to_dex_references_.
1335 if (dex_to_dex_references_.empty() ||
1336 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1337 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1338 }
1339 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1340}
1341
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001342bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1343 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001344 bool result = false;
1345 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001346 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1347 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001348 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001349 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1350 result = (resolved_class != nullptr);
1351 }
1352
1353 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001354 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001355 } else {
1356 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001357 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001358 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001359}
1360
1361bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1362 uint32_t string_idx) {
1363 // See also Compiler::ResolveDexFile
1364
1365 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001366 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001368 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001369 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1370 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1371 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001372 if (IsBootImage()) {
1373 // We resolve all const-string strings when building for the image.
1374 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1375 result = true;
1376 } else {
1377 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001378 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001379 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1380 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001381 }
1382 if (result) {
1383 stats_->StringInDexCache();
1384 } else {
1385 stats_->StringNotInDexCache();
1386 }
1387 return result;
1388}
1389
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001390bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1391 Handle<mirror::DexCache> dex_cache,
1392 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 // Get type from dex cache assuming it was populated by the verifier
1394 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001395 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 stats_->TypeNeedsAccessCheck();
1397 return false; // Unknown class needs access checks.
1398 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001399 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001400 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1401 if (!is_accessible) {
1402 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1403 if (referrer_class == nullptr) {
1404 stats_->TypeNeedsAccessCheck();
1405 return false; // Incomplete referrer knowledge needs access check.
1406 }
1407 // Perform access check, will return true if access is ok or false if we're going to have to
1408 // check this at runtime (for example for class loaders).
1409 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001410 }
David Brazdil38f64d32016-01-18 17:13:41 +00001411 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001412 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001413 } else {
1414 stats_->TypeNeedsAccessCheck();
1415 }
David Brazdil38f64d32016-01-18 17:13:41 +00001416 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001417}
1418
1419bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001420 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001421 uint32_t type_idx,
1422 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 // Get type from dex cache assuming it was populated by the verifier.
1424 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001425 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001426 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001427 // Be conservative.
1428 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 return false; // Unknown class needs access checks.
1430 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001431 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001432 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001433 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1434 if (!is_accessible) {
1435 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1436 if (referrer_class == nullptr) {
1437 stats_->TypeNeedsAccessCheck();
1438 return false; // Incomplete referrer knowledge needs access check.
1439 }
1440 // Perform access and instantiable checks, will return true if access is ok or false if we're
1441 // going to have to check this at runtime (for example for class loaders).
1442 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001443 }
David Brazdil38f64d32016-01-18 17:13:41 +00001444 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001445 if (result) {
1446 stats_->TypeDoesntNeedAccessCheck();
1447 } else {
1448 stats_->TypeNeedsAccessCheck();
1449 }
1450 return result;
1451}
1452
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001453bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1454 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001455 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001456 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001457 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001458 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1459 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001460 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1461 if (resolved_class == nullptr) {
1462 return false;
1463 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001464 if (GetCompilerOptions().GetCompilePic()) {
1465 // Do not allow a direct class pointer to be used when compiling for position-independent
1466 return false;
1467 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001468 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001469 gc::Heap* heap = runtime->GetHeap();
1470 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001471 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001472 if (compiling_boot) {
1473 // boot -> boot class pointers.
1474 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001475 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001476 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1477 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001478 if (is_image_class && support_boot_image_fixup) {
1479 *is_type_initialized = resolved_class->IsInitialized();
1480 *use_direct_type_ptr = false;
1481 *direct_type_ptr = 0;
1482 return true;
1483 } else {
1484 return false;
1485 }
Calin Juravleffc87072016-04-20 14:22:09 +01001486 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001487 *is_type_initialized = resolved_class->IsInitialized();
1488 // If the class may move around, then don't embed it as a direct pointer.
1489 *use_direct_type_ptr = true;
1490 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1491 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001492 } else {
1493 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001494 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001495 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001496 // boot -> app class pointers.
1497 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001498 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1499 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001500 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1501 return true;
1502 } else {
1503 // app -> app class pointers.
1504 // Give up because app does not have an image and class
1505 // isn't created at compile time. TODO: implement this
1506 // if/when each app gets an image.
1507 return false;
1508 }
1509 }
1510}
1511
Fred Shihe7f82e22014-08-06 10:46:37 -07001512bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1513 bool* use_direct_ptr,
1514 uintptr_t* direct_type_ptr) {
1515 CHECK(ref != nullptr);
1516 CHECK(use_direct_ptr != nullptr);
1517 CHECK(direct_type_ptr != nullptr);
1518
1519 ScopedObjectAccess soa(Thread::Current());
1520 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001521 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001522 bool unused_finalizable;
1523 // Make sure we have a finished Reference class object before attempting to use it.
1524 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1525 reference_class->GetDexTypeIndex(), &is_initialized,
1526 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1527 !is_initialized) {
1528 return false;
1529 }
1530 ref->first = &reference_class->GetDexFile();
1531 ref->second = reference_class->GetDexClassDefIndex();
1532 return true;
1533}
1534
1535uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1536 ScopedObjectAccess soa(Thread::Current());
1537 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1538 DCHECK(klass->IsInitialized());
1539 return klass->GetSlowPathFlagOffset().Uint32Value();
1540}
1541
1542uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1543 ScopedObjectAccess soa(Thread::Current());
1544 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1545 DCHECK(klass->IsInitialized());
1546 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1547}
1548
Vladimir Marko20f85592015-03-19 10:07:02 +00001549DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001550 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001551 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001552 : DexCacheArraysLayout();
1553}
1554
Vladimir Markobe0e5462014-02-26 11:24:15 +00001555void CompilerDriver::ProcessedInstanceField(bool resolved) {
1556 if (!resolved) {
1557 stats_->UnresolvedInstanceField();
1558 } else {
1559 stats_->ResolvedInstanceField();
1560 }
1561}
1562
1563void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1564 if (!resolved) {
1565 stats_->UnresolvedStaticField();
1566 } else if (local) {
1567 stats_->ResolvedLocalStaticField();
1568 } else {
1569 stats_->ResolvedStaticField();
1570 }
1571}
1572
Vladimir Markof096aad2014-01-23 15:51:58 +00001573void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1574 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001575}
1576
Mathieu Chartierc7853442015-03-27 14:35:38 -07001577ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1578 const DexCompilationUnit* mUnit, bool is_put,
1579 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001580 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001581 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001582 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001583 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001584 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001585 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001586 Handle<mirror::ClassLoader> class_loader_handle(
1587 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001588 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001589 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001590 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001591 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001592 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001593 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001594 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001595 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001596 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001597 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001598 ProcessedInstanceField(can_link);
1599 return can_link ? resolved_field : nullptr;
1600}
1601
1602bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1603 bool is_put, MemberOffset* field_offset,
1604 bool* is_volatile) {
1605 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001606 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001607
Mathieu Chartierc7853442015-03-27 14:35:38 -07001608 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001609 // Conservative defaults.
1610 *is_volatile = true;
1611 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001612 return false;
1613 } else {
1614 *is_volatile = resolved_field->IsVolatile();
1615 *field_offset = resolved_field->GetOffset();
1616 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001617 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001618}
1619
Ian Rogers83883d72013-10-21 21:07:24 -07001620void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1621 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001622 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001623 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001624 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001625 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001626 uintptr_t* direct_code,
1627 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001628 // For direct and static methods compute possible direct_code and direct_method values, ie
1629 // an address for the Method* being invoked and an address of the code for that Method*.
1630 // For interface calls compute a value for direct_method that is the interface method being
1631 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001632 *direct_code = 0;
1633 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001634 Runtime* const runtime = Runtime::Current();
1635 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 auto* cl = runtime->GetClassLinker();
1637 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001638 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001639 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001640 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1641 const bool force_relocations = (compiling_boot ||
1642 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001643 if (sharp_type != kStatic && sharp_type != kDirect) {
1644 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001645 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001646 // TODO: support patching on all architectures.
1647 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001648 mirror::Class* declaring_class = method->GetDeclaringClass();
1649 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001650 if (!use_dex_cache) {
1651 if (!method_code_in_boot) {
1652 use_dex_cache = true;
1653 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001654 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001655 method->IsStatic() && !declaring_class->IsInitialized();
1656 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001657 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1658 // class.
1659 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001660 }
1661 }
Ian Rogers83883d72013-10-21 21:07:24 -07001662 }
Calin Juravleffc87072016-04-20 14:22:09 +01001663 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001664 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1665 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001666 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001667 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1668 use_dex_cache = true;
1669 }
1670 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001671 if (method_code_in_boot) {
1672 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001673 }
Alex Lighta59dd802014-07-02 16:28:08 -07001674 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001675 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001676 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001677 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1678 } else {
1679 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001680 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1681 !cl->IsQuickToInterpreterBridge(
1682 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001683 }
1684 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001685 // We can only branch directly to Methods that are resolved in the DexCache.
1686 // Otherwise we won't invoke the resolution trampoline.
1687 use_dex_cache = true;
1688 }
1689 }
1690 // The method is defined not within this dex file. We need a dex cache slot within the current
1691 // dex file or direct pointers.
1692 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001693 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1694 if (target_method->dex_file == dex_cache->GetDexFile() &&
Calin Juravleffc87072016-04-20 14:22:09 +01001695 !(runtime->UseJitCompilation() && dex_cache->GetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001696 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001697 target_method->dex_method_index = method->GetDexMethodIndex();
1698 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001699 if (no_guarantee_of_dex_cache_entry) {
1700 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1702 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001703 if (dex_method_idx != DexFile::kDexNoIndex) {
1704 target_method->dex_method_index = dex_method_idx;
1705 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001706 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001707 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001708 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001709 }
Ian Rogers83883d72013-10-21 21:07:24 -07001710 must_use_direct_pointers = true;
1711 }
1712 }
1713 }
1714 if (use_dex_cache) {
1715 if (must_use_direct_pointers) {
1716 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1717 // pointers are required as the dex cache lacks an appropriate entry.
1718 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1719 } else {
1720 *type = sharp_type;
1721 }
1722 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001723 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001724 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1725 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001726 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001727 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1728 method_in_image = true;
1729 break;
1730 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001731 }
Calin Juravleffc87072016-04-20 14:22:09 +01001732 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001733 // 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 -08001734 // In the case where we are the JIT, we can always use direct pointers since we know where
1735 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1736 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001737 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001738 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001739 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1740 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001741 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001742 target_method->dex_method_index = method->GetDexMethodIndex();
1743 } else if (!must_use_direct_pointers) {
1744 // Set the code and rely on the dex cache for the method.
1745 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001746 if (force_relocations) {
1747 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001748 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001749 target_method->dex_method_index = method->GetDexMethodIndex();
1750 } else {
1751 *direct_code = compiler_->GetEntryPointOf(method);
1752 }
Ian Rogers83883d72013-10-21 21:07:24 -07001753 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001754 // Direct pointers were required but none were available.
1755 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001756 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001757 }
1758}
1759
1760bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001761 bool update_stats, bool enable_devirtualization,
1762 InvokeType* invoke_type, MethodReference* target_method,
1763 int* vtable_idx, uintptr_t* direct_code,
1764 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001765 InvokeType orig_invoke_type = *invoke_type;
1766 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001767 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001768 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001769 StackHandleScope<2> hs(soa.Self());
1770 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001771 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1772 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001773 uint32_t method_idx = target_method->dex_method_index;
1774 ArtMethod* resolved_method = ResolveMethod(
1775 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1776 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1777 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001778 bool result = false;
1779 if (resolved_method != nullptr) {
1780 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001781
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001782 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001783 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1784
1785 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001786 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001787 invoke_type, target_method, devirt_target, direct_code, direct_method);
1788 result = stats_flags != 0;
1789 } else {
1790 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001791 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1792 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001793 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001794 target_method->dex_method_index)) ||
1795 *invoke_type == kSuper) {
1796 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1797 } else {
1798 // Sharpening failed so generate a regular resolved method dispatch.
1799 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001800 GetCodeAndMethodForDirectCall(
1801 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1802 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001803 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001804 }
1805 }
1806 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001807 if (!result) {
1808 // Conservative defaults.
1809 *vtable_idx = -1;
1810 *direct_code = 0u;
1811 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001812 }
1813 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001814 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001816 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001817}
1818
Vladimir Marko2730db02014-01-27 11:15:17 +00001819const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1820 uint32_t method_idx) const {
1821 MethodReference ref(dex_file, method_idx);
1822 return verification_results_->GetVerifiedMethod(ref);
1823}
1824
1825bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001826 if (!compiler_options_->IsVerificationEnabled()) {
1827 // If we didn't verify, every cast has to be treated as non-safe.
1828 return false;
1829 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001830 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1831 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001832 if (result) {
1833 stats_->SafeCast();
1834 } else {
1835 stats_->NotASafeCast();
1836 }
1837 return result;
1838}
1839
Mathieu Chartier90443472015-07-16 20:32:27 -07001840class CompilationVisitor {
1841 public:
1842 virtual ~CompilationVisitor() {}
1843 virtual void Visit(size_t index) = 0;
1844};
1845
Brian Carlstrom7940e442013-07-12 13:46:57 -07001846class ParallelCompilationManager {
1847 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001848 ParallelCompilationManager(ClassLinker* class_linker,
1849 jobject class_loader,
1850 CompilerDriver* compiler,
1851 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001852 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001853 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001854 : index_(0),
1855 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001856 class_loader_(class_loader),
1857 compiler_(compiler),
1858 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001859 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001860 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001861
1862 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001863 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864 return class_linker_;
1865 }
1866
1867 jobject GetClassLoader() const {
1868 return class_loader_;
1869 }
1870
1871 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001872 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 return compiler_;
1874 }
1875
1876 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001877 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001878 return dex_file_;
1879 }
1880
Andreas Gampede7b4362014-07-28 18:38:57 -07001881 const std::vector<const DexFile*>& GetDexFiles() const {
1882 return dex_files_;
1883 }
1884
Mathieu Chartier90443472015-07-16 20:32:27 -07001885 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1886 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001887 Thread* self = Thread::Current();
1888 self->AssertNoPendingException();
1889 CHECK_GT(work_units, 0U);
1890
Ian Rogers3e5cf302014-05-20 16:40:37 -07001891 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001892 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001893 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001894 }
1895 thread_pool_->StartWorkers(self);
1896
1897 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1898 // thread destructor's called below perform join).
1899 CHECK_NE(self->GetState(), kRunnable);
1900
1901 // Wait for all the worker threads to finish.
1902 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001903
1904 // And stop the workers accepting jobs.
1905 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001906 }
1907
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001908 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001909 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001910 }
1911
Brian Carlstrom7940e442013-07-12 13:46:57 -07001912 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001913 class ForAllClosure : public Task {
1914 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001915 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001916 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001917 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001918 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001919
1920 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001921 while (true) {
1922 const size_t index = manager_->NextIndex();
1923 if (UNLIKELY(index >= end_)) {
1924 break;
1925 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001926 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001927 self->AssertNoPendingException();
1928 }
1929 }
1930
1931 virtual void Finalize() {
1932 delete this;
1933 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001934
Brian Carlstrom7940e442013-07-12 13:46:57 -07001935 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001936 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001937 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001938 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001939 };
1940
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001941 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001942 ClassLinker* const class_linker_;
1943 const jobject class_loader_;
1944 CompilerDriver* const compiler_;
1945 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001946 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001947 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001948
1949 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001950};
1951
Jeff Hao0e49b422013-11-08 12:16:56 -08001952// A fast version of SkipClass above if the class pointer is available
1953// that avoids the expensive FindInClassPath search.
1954static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -07001955 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001956 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001957 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1958 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001959 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001960 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1961 << dex_file.GetLocation() << " previously found in "
1962 << original_dex_file.GetLocation();
1963 }
1964 return true;
1965 }
1966 return false;
1967}
1968
Mathieu Chartier70b63482014-06-27 17:19:04 -07001969static void CheckAndClearResolveException(Thread* self)
Mathieu Chartier90443472015-07-16 20:32:27 -07001970 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001971 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001972 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001973 std::string temp;
1974 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1975 const char* expected_exceptions[] = {
1976 "Ljava/lang/IllegalAccessError;",
1977 "Ljava/lang/IncompatibleClassChangeError;",
1978 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001979 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001980 "Ljava/lang/NoClassDefFoundError;",
1981 "Ljava/lang/NoSuchFieldError;",
1982 "Ljava/lang/NoSuchMethodError;"
1983 };
1984 bool found = false;
1985 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1986 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1987 found = true;
1988 }
1989 }
1990 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001991 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001992 }
1993 self->ClearException();
1994}
1995
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001996bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1997 uint16_t class_def_idx) const {
1998 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1999 const uint8_t* class_data = dex_file.GetClassData(class_def);
2000 if (class_data == nullptr) {
2001 // Empty class such as a marker interface.
2002 return false;
2003 }
2004 ClassDataItemIterator it(dex_file, class_data);
2005 while (it.HasNextStaticField()) {
2006 it.Next();
2007 }
2008 // We require a constructor barrier if there are final instance fields.
2009 while (it.HasNextInstanceField()) {
2010 if (it.MemberIsFinal()) {
2011 return true;
2012 }
2013 it.Next();
2014 }
2015 return false;
2016}
2017
Mathieu Chartier90443472015-07-16 20:32:27 -07002018class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2019 public:
2020 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2021 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002022
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002023 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002024 ATRACE_CALL();
2025 Thread* const self = Thread::Current();
2026 jobject jclass_loader = manager_->GetClassLoader();
2027 const DexFile& dex_file = *manager_->GetDexFile();
2028 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002029
Mathieu Chartier90443472015-07-16 20:32:27 -07002030 // If an instance field is final then we need to have a barrier on the return, static final
2031 // fields are assigned within the lock held for class initialization. Conservatively assume
2032 // constructor barriers are always required.
2033 bool requires_constructor_barrier = true;
2034
2035 // Method and Field are the worst. We can't resolve without either
2036 // context from the code use (to disambiguate virtual vs direct
2037 // method and instance vs static field) or from class
2038 // definitions. While the compiler will resolve what it can as it
2039 // needs it, here we try to resolve fields and methods used in class
2040 // definitions, since many of them many never be referenced by
2041 // generated code.
2042 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2043 ScopedObjectAccess soa(self);
2044 StackHandleScope<2> hs(soa.Self());
2045 Handle<mirror::ClassLoader> class_loader(
2046 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002047 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2048 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002049 // Resolve the class.
2050 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2051 class_loader);
2052 bool resolve_fields_and_methods;
2053 if (klass == nullptr) {
2054 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2055 // attempt to resolve methods and fields when there is no declaring class.
2056 CheckAndClearResolveException(soa.Self());
2057 resolve_fields_and_methods = false;
2058 } else {
2059 // We successfully resolved a class, should we skip it?
2060 if (SkipClass(jclass_loader, dex_file, klass)) {
2061 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002062 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002063 // We want to resolve the methods and fields eagerly.
2064 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002065 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002066 // Note the class_data pointer advances through the headers,
2067 // static fields, instance fields, direct methods, and virtual
2068 // methods.
2069 const uint8_t* class_data = dex_file.GetClassData(class_def);
2070 if (class_data == nullptr) {
2071 // Empty class such as a marker interface.
2072 requires_constructor_barrier = false;
2073 } else {
2074 ClassDataItemIterator it(dex_file, class_data);
2075 while (it.HasNextStaticField()) {
2076 if (resolve_fields_and_methods) {
2077 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2078 dex_cache, class_loader, true);
2079 if (field == nullptr) {
2080 CheckAndClearResolveException(soa.Self());
2081 }
Ian Rogers68b56852014-08-29 20:19:11 -07002082 }
2083 it.Next();
2084 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002085 // We require a constructor barrier if there are final instance fields.
2086 requires_constructor_barrier = false;
2087 while (it.HasNextInstanceField()) {
2088 if (it.MemberIsFinal()) {
2089 requires_constructor_barrier = true;
2090 }
2091 if (resolve_fields_and_methods) {
2092 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2093 dex_cache, class_loader, false);
2094 if (field == nullptr) {
2095 CheckAndClearResolveException(soa.Self());
2096 }
Ian Rogers68b56852014-08-29 20:19:11 -07002097 }
2098 it.Next();
2099 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002100 if (resolve_fields_and_methods) {
2101 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002102 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002103 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2104 it.GetMethodInvokeType(class_def));
2105 if (method == nullptr) {
2106 CheckAndClearResolveException(soa.Self());
2107 }
2108 it.Next();
2109 }
2110 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002111 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002112 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2113 it.GetMethodInvokeType(class_def));
2114 if (method == nullptr) {
2115 CheckAndClearResolveException(soa.Self());
2116 }
2117 it.Next();
2118 }
2119 DCHECK(!it.HasNext());
2120 }
2121 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002122 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2123 &dex_file,
2124 class_def_index,
2125 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002126 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002127
Mathieu Chartier90443472015-07-16 20:32:27 -07002128 private:
2129 const ParallelCompilationManager* const manager_;
2130};
2131
2132class ResolveTypeVisitor : public CompilationVisitor {
2133 public:
2134 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2135 }
2136 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002137 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002138 ScopedObjectAccess soa(Thread::Current());
2139 ClassLinker* class_linker = manager_->GetClassLinker();
2140 const DexFile& dex_file = *manager_->GetDexFile();
2141 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002142 Handle<mirror::ClassLoader> class_loader(
2143 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002144 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2145 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002146 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002147 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002148
Mathieu Chartier90443472015-07-16 20:32:27 -07002149 if (klass == nullptr) {
2150 soa.Self()->AssertPendingException();
2151 mirror::Throwable* exception = soa.Self()->GetException();
2152 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2153 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2154 // There's little point continuing compilation if the heap is exhausted.
2155 LOG(FATAL) << "Out of memory during type resolution for compilation";
2156 }
2157 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002158 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002159 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002160
2161 private:
2162 const ParallelCompilationManager* const manager_;
2163};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002164
Andreas Gampeace0dc12016-01-20 13:33:13 -08002165void CompilerDriver::ResolveDexFile(jobject class_loader,
2166 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002167 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002168 ThreadPool* thread_pool,
2169 size_t thread_count,
2170 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002171 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2172
2173 // TODO: we could resolve strings here, although the string table is largely filled with class
2174 // and method names.
2175
Andreas Gampede7b4362014-07-28 18:38:57 -07002176 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2177 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002178 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002179 // For images we resolve all types, such as array, whereas for applications just those with
2180 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002181 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002182 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002183 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002184 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002185
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002186 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002187 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002188 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002189}
2190
Andreas Gampeace0dc12016-01-20 13:33:13 -08002191void CompilerDriver::SetVerified(jobject class_loader,
2192 const std::vector<const DexFile*>& dex_files,
2193 TimingLogger* timings) {
2194 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002195 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002196 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002197 SetVerifiedDexFile(class_loader,
2198 *dex_file,
2199 dex_files,
2200 parallel_thread_pool_.get(),
2201 parallel_thread_count_,
2202 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002203 }
2204}
2205
Andreas Gampeace0dc12016-01-20 13:33:13 -08002206void CompilerDriver::Verify(jobject class_loader,
2207 const std::vector<const DexFile*>& dex_files,
2208 TimingLogger* timings) {
2209 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2210 // as all should have been resolved before. As such, doing this in parallel should still
2211 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002212 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002213 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002214 VerifyDexFile(class_loader,
2215 *dex_file,
2216 dex_files,
2217 parallel_thread_pool_.get(),
2218 parallel_thread_count_,
2219 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002220 }
2221}
2222
Mathieu Chartier90443472015-07-16 20:32:27 -07002223class VerifyClassVisitor : public CompilationVisitor {
2224 public:
Andreas Gampe7fe30232016-03-25 16:58:00 -07002225 VerifyClassVisitor(const ParallelCompilationManager* manager, LogSeverity log_level)
2226 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002227
Mathieu Chartier90443472015-07-16 20:32:27 -07002228 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2229 ATRACE_CALL();
2230 ScopedObjectAccess soa(Thread::Current());
2231 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002232 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2233 // Skip verification since the class is not in the profile.
2234 return;
2235 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002236 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2237 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2238 ClassLinker* class_linker = manager_->GetClassLinker();
2239 jobject jclass_loader = manager_->GetClassLoader();
2240 StackHandleScope<3> hs(soa.Self());
2241 Handle<mirror::ClassLoader> class_loader(
2242 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2243 Handle<mirror::Class> klass(
2244 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2245 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002246 CHECK(soa.Self()->IsExceptionPending());
2247 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002248
2249 /*
2250 * At compile time, we can still structurally verify the class even if FindClass fails.
2251 * This is to ensure the class is structurally sound for compilation. An unsound class
2252 * will be rejected by the verifier and later skipped during compilation in the compiler.
2253 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002254 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2255 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002256 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002257 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2258 &dex_file,
2259 dex_cache,
2260 class_loader,
2261 &class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002262 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002263 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002264 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002265 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002266 verifier::MethodVerifier::kHardFailure) {
2267 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2268 << " because: " << error_msg;
2269 manager_->GetCompiler()->SetHadHardVerifierFailure();
2270 }
2271 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2272 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002273 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002274
2275 if (klass->IsErroneous()) {
2276 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2277 CHECK(soa.Self()->IsExceptionPending());
2278 soa.Self()->ClearException();
2279 manager_->GetCompiler()->SetHadHardVerifierFailure();
2280 }
2281
2282 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2283 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2284
2285 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2286 // we rely on things working OK without verification when the decryption dialog is brought up.
2287 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002288 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2289 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002290 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002291 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002292 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002293
2294 private:
2295 const ParallelCompilationManager* const manager_;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002296 const LogSeverity log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002297};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002298
Andreas Gampeace0dc12016-01-20 13:33:13 -08002299void CompilerDriver::VerifyDexFile(jobject class_loader,
2300 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002301 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002302 ThreadPool* thread_pool,
2303 size_t thread_count,
2304 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002305 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002306 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002307 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2308 thread_pool);
Andreas Gampe7fe30232016-03-25 16:58:00 -07002309 LogSeverity log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2310 ? LogSeverity::INTERNAL_FATAL
2311 : LogSeverity::WARNING;
2312 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002313 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002314}
2315
Mathieu Chartier90443472015-07-16 20:32:27 -07002316class SetVerifiedClassVisitor : public CompilationVisitor {
2317 public:
2318 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2319
2320 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2321 ATRACE_CALL();
2322 ScopedObjectAccess soa(Thread::Current());
2323 const DexFile& dex_file = *manager_->GetDexFile();
2324 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2325 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2326 ClassLinker* class_linker = manager_->GetClassLinker();
2327 jobject jclass_loader = manager_->GetClassLoader();
2328 StackHandleScope<3> hs(soa.Self());
2329 Handle<mirror::ClassLoader> class_loader(
2330 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2331 Handle<mirror::Class> klass(
2332 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2333 // Class might have failed resolution. Then don't set it to verified.
2334 if (klass.Get() != nullptr) {
2335 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2336 // very wrong.
2337 if (klass->IsResolved()) {
2338 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2339 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2340 // Set class status to verified.
2341 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2342 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2343 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002344 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002345 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002346 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002347 }
2348 // Record the final class status if necessary.
2349 ClassReference ref(manager_->GetDexFile(), class_def_index);
2350 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002351 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002352 } else {
2353 Thread* self = soa.Self();
2354 DCHECK(self->IsExceptionPending());
2355 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002356 }
2357 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002358
2359 private:
2360 const ParallelCompilationManager* const manager_;
2361};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002362
Andreas Gampeace0dc12016-01-20 13:33:13 -08002363void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2364 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002365 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002366 ThreadPool* thread_pool,
2367 size_t thread_count,
2368 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002369 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2370 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2371 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2372 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002373 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002374 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002375}
2376
Mathieu Chartier90443472015-07-16 20:32:27 -07002377class InitializeClassVisitor : public CompilationVisitor {
2378 public:
2379 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002380
Mathieu Chartier90443472015-07-16 20:32:27 -07002381 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2382 ATRACE_CALL();
2383 jobject jclass_loader = manager_->GetClassLoader();
2384 const DexFile& dex_file = *manager_->GetDexFile();
2385 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2386 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2387 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002388
Mathieu Chartier90443472015-07-16 20:32:27 -07002389 ScopedObjectAccess soa(Thread::Current());
2390 StackHandleScope<3> hs(soa.Self());
2391 Handle<mirror::ClassLoader> class_loader(
2392 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2393 Handle<mirror::Class> klass(
2394 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2395
2396 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2397 // Only try to initialize classes that were successfully verified.
2398 if (klass->IsVerified()) {
2399 // Attempt to initialize the class but bail if we either need to initialize the super-class
2400 // or static fields.
2401 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002402 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002403 // We don't want non-trivial class initialization occurring on multiple threads due to
2404 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2405 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2406 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2407 // after first initializing its parents, whose locks are acquired. This leads to a
2408 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2409 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2410 // than use a special Object for the purpose we use the Class of java.lang.Class.
2411 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2412 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2413 // Attempt to initialize allowing initialization of parent classes but still not static
2414 // fields.
2415 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2416 if (!klass->IsInitialized()) {
2417 // We need to initialize static fields, we only do this for image classes that aren't
2418 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002419 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002420 manager_->GetCompiler()->IsImageClass(descriptor) &&
2421 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2422 if (can_init_static_fields) {
2423 VLOG(compiler) << "Initializing: " << descriptor;
2424 // TODO multithreading support. We should ensure the current compilation thread has
2425 // exclusive access to the runtime and the transaction. To achieve this, we could use
2426 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2427 // checks in Thread::AssertThreadSuspensionIsAllowable.
2428 Runtime* const runtime = Runtime::Current();
2429 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002430
Mathieu Chartier90443472015-07-16 20:32:27 -07002431 // Run the class initializer in transaction mode.
2432 runtime->EnterTransactionMode(&transaction);
2433 const mirror::Class::Status old_status = klass->GetStatus();
2434 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2435 true);
2436 // TODO we detach transaction from runtime to indicate we quit the transactional
2437 // mode which prevents the GC from visiting objects modified during the transaction.
2438 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002439
Mathieu Chartier90443472015-07-16 20:32:27 -07002440 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2441 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002442
Mathieu Chartier90443472015-07-16 20:32:27 -07002443 if (!success) {
2444 CHECK(soa.Self()->IsExceptionPending());
2445 mirror::Throwable* exception = soa.Self()->GetException();
2446 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2447 << exception->Dump();
2448 std::ostream* file_log = manager_->GetCompiler()->
2449 GetCompilerOptions().GetInitFailureOutput();
2450 if (file_log != nullptr) {
2451 *file_log << descriptor << "\n";
2452 *file_log << exception->Dump() << "\n";
2453 }
2454 soa.Self()->ClearException();
2455 transaction.Rollback();
2456 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002457 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002458 }
2459 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002460 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002461 }
2462 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002463 // Record the final class status if necessary.
2464 ClassReference ref(manager_->GetDexFile(), class_def_index);
2465 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002466 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002467 // Clear any class not found or verification exceptions.
2468 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002469 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002470
2471 private:
2472 const ParallelCompilationManager* const manager_;
2473};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002474
Andreas Gampeace0dc12016-01-20 13:33:13 -08002475void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2476 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002477 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002478 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002479 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002480
2481 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2482 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2483 ThreadPool* init_thread_pool = force_determinism
2484 ? single_thread_pool_.get()
2485 : parallel_thread_pool_.get();
2486 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2487
Brian Carlstrom7940e442013-07-12 13:46:57 -07002488 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002489 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002490 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002491 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002492 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002493 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002494 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002495 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002496 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002497}
2498
Mathieu Chartier91288d82016-04-28 09:44:54 -07002499class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002500 public:
2501 virtual bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002502 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2503 return true;
2504 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002505 if (klass->IsArrayClass()) {
2506 StackHandleScope<1> hs(Thread::Current());
2507 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2508 hs.NewHandle(klass),
2509 true,
2510 true);
2511 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002512 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002513 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002514 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002515 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002516
2517 private:
2518 void FillIMTAndConflictTables(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
2519 if (!klass->ShouldHaveImt()) {
2520 return;
2521 }
2522 if (visited_classes_.find(klass) != visited_classes_.end()) {
2523 return;
2524 }
2525 if (klass->HasSuperClass()) {
2526 FillIMTAndConflictTables(klass->GetSuperClass());
2527 }
2528 if (!klass->IsTemp()) {
2529 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2530 }
2531 visited_classes_.insert(klass);
2532 }
2533
2534 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002535};
2536
Brian Carlstrom7940e442013-07-12 13:46:57 -07002537void CompilerDriver::InitializeClasses(jobject class_loader,
2538 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002539 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002540 for (size_t i = 0; i != dex_files.size(); ++i) {
2541 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002542 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002543 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002544 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002545 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002546 // Make sure that we call EnsureIntiailized on all the array classes to call
2547 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2548 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002549 // Also create conflict tables.
2550 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002551 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002552 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2553 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002554 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002555 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002556 // Prune garbage objects created during aborted transactions.
2557 Runtime::Current()->GetHeap()->CollectGarbage(true);
2558 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002559}
2560
Andreas Gampeace0dc12016-01-20 13:33:13 -08002561void CompilerDriver::Compile(jobject class_loader,
2562 const std::vector<const DexFile*>& dex_files,
2563 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002564 if (kDebugProfileGuidedCompilation) {
2565 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2566 ((profile_compilation_info_ == nullptr)
2567 ? "null"
2568 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002569 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002570
2571 DCHECK(current_dex_to_dex_methods_ == nullptr);
2572 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002573 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002574 CompileDexFile(class_loader,
2575 *dex_file,
2576 dex_files,
2577 parallel_thread_pool_.get(),
2578 parallel_thread_count_,
2579 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002580 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2581 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2582 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002583 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002584 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002585
2586 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2587 {
2588 // From this point on, we shall not modify dex_to_dex_references_, so
2589 // just grab a reference to it that we use without holding the mutex.
2590 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2591 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2592 }
2593 for (const auto& method_set : dex_to_dex_references) {
2594 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2595 CompileDexFile(class_loader,
2596 method_set.GetDexFile(),
2597 dex_files,
2598 parallel_thread_pool_.get(),
2599 parallel_thread_count_,
2600 timings);
2601 }
2602 current_dex_to_dex_methods_ = nullptr;
2603
Andreas Gampe8d295f82015-01-20 14:50:21 -08002604 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002605}
2606
Mathieu Chartier90443472015-07-16 20:32:27 -07002607class CompileClassVisitor : public CompilationVisitor {
2608 public:
2609 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2610
2611 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2612 ATRACE_CALL();
2613 const DexFile& dex_file = *manager_->GetDexFile();
2614 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2615 ClassLinker* class_linker = manager_->GetClassLinker();
2616 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002617 ClassReference ref(&dex_file, class_def_index);
2618 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2619 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002620 return;
2621 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002622 // Use a scoped object access to perform to the quick SkipClass check.
2623 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2624 ScopedObjectAccess soa(Thread::Current());
2625 StackHandleScope<3> hs(soa.Self());
2626 Handle<mirror::ClassLoader> class_loader(
2627 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2628 Handle<mirror::Class> klass(
2629 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2630 Handle<mirror::DexCache> dex_cache;
2631 if (klass.Get() == nullptr) {
2632 soa.Self()->AssertPendingException();
2633 soa.Self()->ClearException();
2634 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2635 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2636 return;
2637 } else {
2638 dex_cache = hs.NewHandle(klass->GetDexCache());
2639 }
2640
Mathieu Chartier90443472015-07-16 20:32:27 -07002641 const uint8_t* class_data = dex_file.GetClassData(class_def);
2642 if (class_data == nullptr) {
2643 // empty class, probably a marker interface
2644 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002645 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002646
Mathieu Chartier736b5602015-09-02 14:54:11 -07002647 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002648 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002649
Mathieu Chartier90443472015-07-16 20:32:27 -07002650 CompilerDriver* const driver = manager_->GetCompiler();
2651
2652 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002653 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002654 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002655
Mathieu Chartier90443472015-07-16 20:32:27 -07002656 ClassDataItemIterator it(dex_file, class_data);
2657 // Skip fields
2658 while (it.HasNextStaticField()) {
2659 it.Next();
2660 }
2661 while (it.HasNextInstanceField()) {
2662 it.Next();
2663 }
2664
2665 bool compilation_enabled = driver->IsClassToCompile(
2666 dex_file.StringByTypeIdx(class_def.class_idx_));
2667
2668 // Compile direct methods
2669 int64_t previous_direct_method_idx = -1;
2670 while (it.HasNextDirectMethod()) {
2671 uint32_t method_idx = it.GetMemberIndex();
2672 if (method_idx == previous_direct_method_idx) {
2673 // smali can create dex files with two encoded_methods sharing the same method_idx
2674 // http://code.google.com/p/smali/issues/detail?id=119
2675 it.Next();
2676 continue;
2677 }
2678 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002679 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002680 it.GetMethodInvokeType(class_def), class_def_index,
2681 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002682 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002683 it.Next();
2684 }
2685 // Compile virtual methods
2686 int64_t previous_virtual_method_idx = -1;
2687 while (it.HasNextVirtualMethod()) {
2688 uint32_t method_idx = it.GetMemberIndex();
2689 if (method_idx == previous_virtual_method_idx) {
2690 // smali can create dex files with two encoded_methods sharing the same method_idx
2691 // http://code.google.com/p/smali/issues/detail?id=119
2692 it.Next();
2693 continue;
2694 }
2695 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002696 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002697 it.GetMethodInvokeType(class_def), class_def_index,
2698 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002699 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002700 it.Next();
2701 }
2702 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002703 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002704
2705 private:
2706 const ParallelCompilationManager* const manager_;
2707};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002708
Andreas Gampeace0dc12016-01-20 13:33:13 -08002709void CompilerDriver::CompileDexFile(jobject class_loader,
2710 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002711 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002712 ThreadPool* thread_pool,
2713 size_t thread_count,
2714 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002715 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002716 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002717 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002718 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002719 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002720}
2721
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002722void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2723 CompiledMethod* const compiled_method,
2724 size_t non_relative_linker_patch_count) {
2725 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2726 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2727 {
2728 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2729 compiled_methods_.Put(method_ref, compiled_method);
2730 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002731 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002732 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2733 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002734}
2735
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002736void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2737 CompiledMethod* compiled_method = nullptr;
2738 {
2739 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2740 auto it = compiled_methods_.find(method_ref);
2741 if (it != compiled_methods_.end()) {
2742 compiled_method = it->second;
2743 compiled_methods_.erase(it);
2744 }
2745 }
2746 if (compiled_method != nullptr) {
2747 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2748 }
2749}
2750
Brian Carlstrom7940e442013-07-12 13:46:57 -07002751CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2752 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2753 ClassTable::const_iterator it = compiled_classes_.find(ref);
2754 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002755 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002756 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002757 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002758 return it->second;
2759}
2760
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002761void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2762 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2763 auto it = compiled_classes_.find(ref);
2764 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2765 // An entry doesn't exist or the status is lower than the new status.
2766 if (it != compiled_classes_.end()) {
2767 CHECK_GT(status, it->second->GetStatus());
2768 delete it->second;
2769 }
2770 switch (status) {
2771 case mirror::Class::kStatusNotReady:
2772 case mirror::Class::kStatusError:
2773 case mirror::Class::kStatusRetryVerificationAtRuntime:
2774 case mirror::Class::kStatusVerified:
2775 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002776 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002777 break; // Expected states.
2778 default:
2779 LOG(FATAL) << "Unexpected class status for class "
2780 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2781 << " of " << status;
2782 }
2783 CompiledClass* compiled_class = new CompiledClass(status);
2784 compiled_classes_.Overwrite(ref, compiled_class);
2785 }
2786}
2787
Brian Carlstrom7940e442013-07-12 13:46:57 -07002788CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2789 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2790 MethodTable::const_iterator it = compiled_methods_.find(ref);
2791 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002792 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002793 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002794 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002795 return it->second;
2796}
2797
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002798bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2799 uint16_t class_def_idx,
2800 const DexFile& dex_file) const {
2801 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2802 if (verified_method != nullptr) {
2803 return !verified_method->HasVerificationFailures();
2804 }
2805
2806 // If we can't find verification metadata, check if this is a system class (we trust that system
2807 // classes have their methods verified). If it's not, be conservative and assume the method
2808 // has not been verified successfully.
2809
2810 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2811 // even if methods are not found in the verification cache.
2812 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2813 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2814 Thread* self = Thread::Current();
2815 ScopedObjectAccess soa(self);
2816 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2817 if (!is_system_class) {
2818 self->ClearException();
2819 }
2820 return is_system_class;
2821}
2822
Vladimir Markof4da6752014-08-01 19:04:18 +01002823size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2824 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2825 return non_relative_linker_patch_count_;
2826}
2827
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002828void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2829 const DexFile* dex_file,
2830 uint16_t class_def_index,
2831 bool requires) {
2832 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2833 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002834}
2835
Mathieu Chartier371bd832016-04-07 10:19:48 -07002836bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2837 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002838 uint16_t class_def_index) {
2839 ClassReference class_ref(dex_file, class_def_index);
2840 {
2841 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2842 auto it = requires_constructor_barrier_.find(class_ref);
2843 if (it != requires_constructor_barrier_.end()) {
2844 return it->second;
2845 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002846 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002847 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2848 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2849 requires_constructor_barrier_.emplace(class_ref, requires);
2850 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002851}
2852
Andreas Gampe8d295f82015-01-20 14:50:21 -08002853std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002854 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002855 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002856 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002857 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002858 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002859#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002860 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002861 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2862 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002863 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2864 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002865#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002866 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002867 return oss.str();
2868}
2869
Jeff Hao848f70a2014-01-15 13:49:50 -08002870bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2871 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2872 return strcmp(type, "Ljava/lang/String;") == 0;
2873}
2874
2875bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2876 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
Andreas Gampe542451c2016-07-26 09:02:02 -07002877 PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
Jeff Hao848f70a2014-01-15 13:49:50 -08002878 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2879 return inliner->IsStringInitMethodIndex(method_index);
2880}
2881
Jeff Haodcdc85b2015-12-04 14:06:18 -08002882bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2883 const DexFile* inlined_into) const {
2884 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2885 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002886 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2887 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002888 return false;
2889 }
2890
2891 return true;
2892}
2893
Andreas Gampeace0dc12016-01-20 13:33:13 -08002894void CompilerDriver::InitializeThreadPools() {
2895 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2896 parallel_thread_pool_.reset(
2897 new ThreadPool("Compiler driver thread pool", parallel_count));
2898 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2899}
2900
2901void CompilerDriver::FreeThreadPools() {
2902 parallel_thread_pool_.reset();
2903 single_thread_pool_.reset();
2904}
2905
Brian Carlstrom7940e442013-07-12 13:46:57 -07002906} // namespace art