xref: /aosp_15_r20/art/dex2oat/driver/compiler_driver.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1*795d594fSAndroid Build Coastguard Worker /*
2*795d594fSAndroid Build Coastguard Worker  * Copyright (C) 2011 The Android Open Source Project
3*795d594fSAndroid Build Coastguard Worker  *
4*795d594fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*795d594fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*795d594fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*795d594fSAndroid Build Coastguard Worker  *
8*795d594fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*795d594fSAndroid Build Coastguard Worker  *
10*795d594fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*795d594fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*795d594fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*795d594fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*795d594fSAndroid Build Coastguard Worker  * limitations under the License.
15*795d594fSAndroid Build Coastguard Worker  */
16*795d594fSAndroid Build Coastguard Worker 
17*795d594fSAndroid Build Coastguard Worker #include "compiler_driver.h"
18*795d594fSAndroid Build Coastguard Worker 
19*795d594fSAndroid Build Coastguard Worker #include <unistd.h>
20*795d594fSAndroid Build Coastguard Worker 
21*795d594fSAndroid Build Coastguard Worker #ifndef __APPLE__
22*795d594fSAndroid Build Coastguard Worker #include <malloc.h>  // For mallinfo
23*795d594fSAndroid Build Coastguard Worker #endif
24*795d594fSAndroid Build Coastguard Worker 
25*795d594fSAndroid Build Coastguard Worker #include <string_view>
26*795d594fSAndroid Build Coastguard Worker #include <vector>
27*795d594fSAndroid Build Coastguard Worker 
28*795d594fSAndroid Build Coastguard Worker #include <android-base/logging.h>
29*795d594fSAndroid Build Coastguard Worker #include <android-base/strings.h>
30*795d594fSAndroid Build Coastguard Worker 
31*795d594fSAndroid Build Coastguard Worker #include "aot_class_linker.h"
32*795d594fSAndroid Build Coastguard Worker #include "art_field-inl.h"
33*795d594fSAndroid Build Coastguard Worker #include "art_method-inl.h"
34*795d594fSAndroid Build Coastguard Worker #include "base/arena_allocator.h"
35*795d594fSAndroid Build Coastguard Worker #include "base/array_ref.h"
36*795d594fSAndroid Build Coastguard Worker #include "base/bit_vector.h"
37*795d594fSAndroid Build Coastguard Worker #include "base/hash_set.h"
38*795d594fSAndroid Build Coastguard Worker #include "base/logging.h"  // For VLOG
39*795d594fSAndroid Build Coastguard Worker #include "base/pointer_size.h"
40*795d594fSAndroid Build Coastguard Worker #include "base/stl_util.h"
41*795d594fSAndroid Build Coastguard Worker #include "base/systrace.h"
42*795d594fSAndroid Build Coastguard Worker #include "base/time_utils.h"
43*795d594fSAndroid Build Coastguard Worker #include "base/timing_logger.h"
44*795d594fSAndroid Build Coastguard Worker #include "class_linker-inl.h"
45*795d594fSAndroid Build Coastguard Worker #include "class_root-inl.h"
46*795d594fSAndroid Build Coastguard Worker #include "common_throws.h"
47*795d594fSAndroid Build Coastguard Worker #include "compiled_method-inl.h"
48*795d594fSAndroid Build Coastguard Worker #include "compiler.h"
49*795d594fSAndroid Build Coastguard Worker #include "compiler_callbacks.h"
50*795d594fSAndroid Build Coastguard Worker #include "compiler_driver-inl.h"
51*795d594fSAndroid Build Coastguard Worker #include "dex/class_accessor-inl.h"
52*795d594fSAndroid Build Coastguard Worker #include "dex/descriptors_names.h"
53*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file-inl.h"
54*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file_annotations.h"
55*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file_exception_helpers.h"
56*795d594fSAndroid Build Coastguard Worker #include "dex/dex_instruction-inl.h"
57*795d594fSAndroid Build Coastguard Worker #include "dex/verification_results.h"
58*795d594fSAndroid Build Coastguard Worker #include "driver/compiler_options.h"
59*795d594fSAndroid Build Coastguard Worker #include "driver/dex_compilation_unit.h"
60*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/card_table-inl.h"
61*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/heap_bitmap.h"
62*795d594fSAndroid Build Coastguard Worker #include "gc/space/image_space.h"
63*795d594fSAndroid Build Coastguard Worker #include "gc/space/space.h"
64*795d594fSAndroid Build Coastguard Worker #include "handle_scope-inl.h"
65*795d594fSAndroid Build Coastguard Worker #include "intrinsics_enum.h"
66*795d594fSAndroid Build Coastguard Worker #include "intrinsics_list.h"
67*795d594fSAndroid Build Coastguard Worker #include "jni/jni_internal.h"
68*795d594fSAndroid Build Coastguard Worker #include "linker/linker_patch.h"
69*795d594fSAndroid Build Coastguard Worker #include "mirror/class-inl.h"
70*795d594fSAndroid Build Coastguard Worker #include "mirror/class_loader.h"
71*795d594fSAndroid Build Coastguard Worker #include "mirror/dex_cache-inl.h"
72*795d594fSAndroid Build Coastguard Worker #include "mirror/object-inl.h"
73*795d594fSAndroid Build Coastguard Worker #include "mirror/object-refvisitor-inl.h"
74*795d594fSAndroid Build Coastguard Worker #include "mirror/object_array-inl.h"
75*795d594fSAndroid Build Coastguard Worker #include "mirror/throwable.h"
76*795d594fSAndroid Build Coastguard Worker #include "object_lock.h"
77*795d594fSAndroid Build Coastguard Worker #include "profile/profile_compilation_info.h"
78*795d594fSAndroid Build Coastguard Worker #include "runtime.h"
79*795d594fSAndroid Build Coastguard Worker #include "runtime_intrinsics.h"
80*795d594fSAndroid Build Coastguard Worker #include "scoped_thread_state_change-inl.h"
81*795d594fSAndroid Build Coastguard Worker #include "thread.h"
82*795d594fSAndroid Build Coastguard Worker #include "thread_list.h"
83*795d594fSAndroid Build Coastguard Worker #include "thread_pool.h"
84*795d594fSAndroid Build Coastguard Worker #include "trampolines/trampoline_compiler.h"
85*795d594fSAndroid Build Coastguard Worker #include "utils/atomic_dex_ref_map-inl.h"
86*795d594fSAndroid Build Coastguard Worker #include "utils/swap_space.h"
87*795d594fSAndroid Build Coastguard Worker #include "vdex_file.h"
88*795d594fSAndroid Build Coastguard Worker #include "verifier/class_verifier.h"
89*795d594fSAndroid Build Coastguard Worker #include "verifier/verifier_deps.h"
90*795d594fSAndroid Build Coastguard Worker #include "verifier/verifier_enums.h"
91*795d594fSAndroid Build Coastguard Worker #include "well_known_classes-inl.h"
92*795d594fSAndroid Build Coastguard Worker 
93*795d594fSAndroid Build Coastguard Worker namespace art {
94*795d594fSAndroid Build Coastguard Worker 
95*795d594fSAndroid Build Coastguard Worker static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
96*795d594fSAndroid Build Coastguard Worker 
97*795d594fSAndroid Build Coastguard Worker // Print additional info during profile guided compilation.
98*795d594fSAndroid Build Coastguard Worker static constexpr bool kDebugProfileGuidedCompilation = false;
99*795d594fSAndroid Build Coastguard Worker 
100*795d594fSAndroid Build Coastguard Worker // Max encoded fields allowed for initializing app image. Hardcode the number for now
101*795d594fSAndroid Build Coastguard Worker // because 5000 should be large enough.
102*795d594fSAndroid Build Coastguard Worker static constexpr uint32_t kMaxEncodedFields = 5000;
103*795d594fSAndroid Build Coastguard Worker 
Percentage(size_t x,size_t y)104*795d594fSAndroid Build Coastguard Worker static double Percentage(size_t x, size_t y) {
105*795d594fSAndroid Build Coastguard Worker   return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
106*795d594fSAndroid Build Coastguard Worker }
107*795d594fSAndroid Build Coastguard Worker 
DumpStat(size_t x,size_t y,const char * str)108*795d594fSAndroid Build Coastguard Worker static void DumpStat(size_t x, size_t y, const char* str) {
109*795d594fSAndroid Build Coastguard Worker   if (x == 0 && y == 0) {
110*795d594fSAndroid Build Coastguard Worker     return;
111*795d594fSAndroid Build Coastguard Worker   }
112*795d594fSAndroid Build Coastguard Worker   LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
113*795d594fSAndroid Build Coastguard Worker }
114*795d594fSAndroid Build Coastguard Worker 
115*795d594fSAndroid Build Coastguard Worker class CompilerDriver::AOTCompilationStats {
116*795d594fSAndroid Build Coastguard Worker  public:
AOTCompilationStats()117*795d594fSAndroid Build Coastguard Worker   AOTCompilationStats()
118*795d594fSAndroid Build Coastguard Worker       : stats_lock_("AOT compilation statistics lock") {}
119*795d594fSAndroid Build Coastguard Worker 
Dump()120*795d594fSAndroid Build Coastguard Worker   void Dump() {
121*795d594fSAndroid Build Coastguard Worker     DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
122*795d594fSAndroid Build Coastguard Worker     DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
123*795d594fSAndroid Build Coastguard Worker              "static fields resolved");
124*795d594fSAndroid Build Coastguard Worker     DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
125*795d594fSAndroid Build Coastguard Worker              "static fields local to a class");
126*795d594fSAndroid Build Coastguard Worker     DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
127*795d594fSAndroid Build Coastguard Worker     // Note, the code below subtracts the stat value so that when added to the stat value we have
128*795d594fSAndroid Build Coastguard Worker     // 100% of samples. TODO: clean this up.
129*795d594fSAndroid Build Coastguard Worker     DumpStat(type_based_devirtualization_,
130*795d594fSAndroid Build Coastguard Worker              resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
131*795d594fSAndroid Build Coastguard Worker              resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
132*795d594fSAndroid Build Coastguard Worker              type_based_devirtualization_,
133*795d594fSAndroid Build Coastguard Worker              "virtual/interface calls made direct based on type information");
134*795d594fSAndroid Build Coastguard Worker 
135*795d594fSAndroid Build Coastguard Worker     const size_t total = std::accumulate(
136*795d594fSAndroid Build Coastguard Worker         class_status_count_,
137*795d594fSAndroid Build Coastguard Worker         class_status_count_ + static_cast<size_t>(ClassStatus::kLast) + 1,
138*795d594fSAndroid Build Coastguard Worker         0u);
139*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i <= static_cast<size_t>(ClassStatus::kLast); ++i) {
140*795d594fSAndroid Build Coastguard Worker       std::ostringstream oss;
141*795d594fSAndroid Build Coastguard Worker       oss << "classes with status " << static_cast<ClassStatus>(i);
142*795d594fSAndroid Build Coastguard Worker       DumpStat(class_status_count_[i], total - class_status_count_[i], oss.str().c_str());
143*795d594fSAndroid Build Coastguard Worker     }
144*795d594fSAndroid Build Coastguard Worker 
145*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i <= kMaxInvokeType; i++) {
146*795d594fSAndroid Build Coastguard Worker       std::ostringstream oss;
147*795d594fSAndroid Build Coastguard Worker       oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
148*795d594fSAndroid Build Coastguard Worker       DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
149*795d594fSAndroid Build Coastguard Worker       if (virtual_made_direct_[i] > 0) {
150*795d594fSAndroid Build Coastguard Worker         std::ostringstream oss2;
151*795d594fSAndroid Build Coastguard Worker         oss2 << static_cast<InvokeType>(i) << " methods made direct";
152*795d594fSAndroid Build Coastguard Worker         DumpStat(virtual_made_direct_[i],
153*795d594fSAndroid Build Coastguard Worker                  resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
154*795d594fSAndroid Build Coastguard Worker                  oss2.str().c_str());
155*795d594fSAndroid Build Coastguard Worker       }
156*795d594fSAndroid Build Coastguard Worker       if (direct_calls_to_boot_[i] > 0) {
157*795d594fSAndroid Build Coastguard Worker         std::ostringstream oss2;
158*795d594fSAndroid Build Coastguard Worker         oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
159*795d594fSAndroid Build Coastguard Worker         DumpStat(direct_calls_to_boot_[i],
160*795d594fSAndroid Build Coastguard Worker                  resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
161*795d594fSAndroid Build Coastguard Worker                  oss2.str().c_str());
162*795d594fSAndroid Build Coastguard Worker       }
163*795d594fSAndroid Build Coastguard Worker       if (direct_methods_to_boot_[i] > 0) {
164*795d594fSAndroid Build Coastguard Worker         std::ostringstream oss2;
165*795d594fSAndroid Build Coastguard Worker         oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
166*795d594fSAndroid Build Coastguard Worker         DumpStat(direct_methods_to_boot_[i],
167*795d594fSAndroid Build Coastguard Worker                  resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
168*795d594fSAndroid Build Coastguard Worker                  oss2.str().c_str());
169*795d594fSAndroid Build Coastguard Worker       }
170*795d594fSAndroid Build Coastguard Worker     }
171*795d594fSAndroid Build Coastguard Worker   }
172*795d594fSAndroid Build Coastguard Worker 
173*795d594fSAndroid Build Coastguard Worker // Allow lossy statistics in non-debug builds.
174*795d594fSAndroid Build Coastguard Worker #ifndef NDEBUG
175*795d594fSAndroid Build Coastguard Worker #define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
176*795d594fSAndroid Build Coastguard Worker #else
177*795d594fSAndroid Build Coastguard Worker #define STATS_LOCK()
178*795d594fSAndroid Build Coastguard Worker #endif
179*795d594fSAndroid Build Coastguard Worker 
ResolvedInstanceField()180*795d594fSAndroid Build Coastguard Worker   void ResolvedInstanceField() REQUIRES(!stats_lock_) {
181*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
182*795d594fSAndroid Build Coastguard Worker     resolved_instance_fields_++;
183*795d594fSAndroid Build Coastguard Worker   }
184*795d594fSAndroid Build Coastguard Worker 
UnresolvedInstanceField()185*795d594fSAndroid Build Coastguard Worker   void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
186*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
187*795d594fSAndroid Build Coastguard Worker     unresolved_instance_fields_++;
188*795d594fSAndroid Build Coastguard Worker   }
189*795d594fSAndroid Build Coastguard Worker 
ResolvedLocalStaticField()190*795d594fSAndroid Build Coastguard Worker   void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
191*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
192*795d594fSAndroid Build Coastguard Worker     resolved_local_static_fields_++;
193*795d594fSAndroid Build Coastguard Worker   }
194*795d594fSAndroid Build Coastguard Worker 
ResolvedStaticField()195*795d594fSAndroid Build Coastguard Worker   void ResolvedStaticField() REQUIRES(!stats_lock_) {
196*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
197*795d594fSAndroid Build Coastguard Worker     resolved_static_fields_++;
198*795d594fSAndroid Build Coastguard Worker   }
199*795d594fSAndroid Build Coastguard Worker 
UnresolvedStaticField()200*795d594fSAndroid Build Coastguard Worker   void UnresolvedStaticField() REQUIRES(!stats_lock_) {
201*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
202*795d594fSAndroid Build Coastguard Worker     unresolved_static_fields_++;
203*795d594fSAndroid Build Coastguard Worker   }
204*795d594fSAndroid Build Coastguard Worker 
205*795d594fSAndroid Build Coastguard Worker   // Indicate that type information from the verifier led to devirtualization.
PreciseTypeDevirtualization()206*795d594fSAndroid Build Coastguard Worker   void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
207*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
208*795d594fSAndroid Build Coastguard Worker     type_based_devirtualization_++;
209*795d594fSAndroid Build Coastguard Worker   }
210*795d594fSAndroid Build Coastguard Worker 
211*795d594fSAndroid Build Coastguard Worker   // A check-cast could be eliminated due to verifier type analysis.
SafeCast()212*795d594fSAndroid Build Coastguard Worker   void SafeCast() REQUIRES(!stats_lock_) {
213*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
214*795d594fSAndroid Build Coastguard Worker     safe_casts_++;
215*795d594fSAndroid Build Coastguard Worker   }
216*795d594fSAndroid Build Coastguard Worker 
217*795d594fSAndroid Build Coastguard Worker   // A check-cast couldn't be eliminated due to verifier type analysis.
NotASafeCast()218*795d594fSAndroid Build Coastguard Worker   void NotASafeCast() REQUIRES(!stats_lock_) {
219*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
220*795d594fSAndroid Build Coastguard Worker     not_safe_casts_++;
221*795d594fSAndroid Build Coastguard Worker   }
222*795d594fSAndroid Build Coastguard Worker 
223*795d594fSAndroid Build Coastguard Worker   // Register a class status.
AddClassStatus(ClassStatus status)224*795d594fSAndroid Build Coastguard Worker   void AddClassStatus(ClassStatus status) REQUIRES(!stats_lock_) {
225*795d594fSAndroid Build Coastguard Worker     STATS_LOCK();
226*795d594fSAndroid Build Coastguard Worker     ++class_status_count_[static_cast<size_t>(status)];
227*795d594fSAndroid Build Coastguard Worker   }
228*795d594fSAndroid Build Coastguard Worker 
229*795d594fSAndroid Build Coastguard Worker  private:
230*795d594fSAndroid Build Coastguard Worker   Mutex stats_lock_;
231*795d594fSAndroid Build Coastguard Worker 
232*795d594fSAndroid Build Coastguard Worker   size_t resolved_instance_fields_ = 0u;
233*795d594fSAndroid Build Coastguard Worker   size_t unresolved_instance_fields_ = 0u;
234*795d594fSAndroid Build Coastguard Worker 
235*795d594fSAndroid Build Coastguard Worker   size_t resolved_local_static_fields_ = 0u;
236*795d594fSAndroid Build Coastguard Worker   size_t resolved_static_fields_ = 0u;
237*795d594fSAndroid Build Coastguard Worker   size_t unresolved_static_fields_ = 0u;
238*795d594fSAndroid Build Coastguard Worker   // Type based devirtualization for invoke interface and virtual.
239*795d594fSAndroid Build Coastguard Worker   size_t type_based_devirtualization_ = 0u;
240*795d594fSAndroid Build Coastguard Worker 
241*795d594fSAndroid Build Coastguard Worker   size_t resolved_methods_[kMaxInvokeType + 1] = {};
242*795d594fSAndroid Build Coastguard Worker   size_t unresolved_methods_[kMaxInvokeType + 1] = {};
243*795d594fSAndroid Build Coastguard Worker   size_t virtual_made_direct_[kMaxInvokeType + 1] = {};
244*795d594fSAndroid Build Coastguard Worker   size_t direct_calls_to_boot_[kMaxInvokeType + 1] = {};
245*795d594fSAndroid Build Coastguard Worker   size_t direct_methods_to_boot_[kMaxInvokeType + 1] = {};
246*795d594fSAndroid Build Coastguard Worker 
247*795d594fSAndroid Build Coastguard Worker   size_t safe_casts_ = 0u;
248*795d594fSAndroid Build Coastguard Worker   size_t not_safe_casts_ = 0u;
249*795d594fSAndroid Build Coastguard Worker 
250*795d594fSAndroid Build Coastguard Worker   size_t class_status_count_[static_cast<size_t>(ClassStatus::kLast) + 1] = {};
251*795d594fSAndroid Build Coastguard Worker 
252*795d594fSAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
253*795d594fSAndroid Build Coastguard Worker };
254*795d594fSAndroid Build Coastguard Worker 
CompilerDriver(const CompilerOptions * compiler_options,const VerificationResults * verification_results,size_t thread_count,int swap_fd)255*795d594fSAndroid Build Coastguard Worker CompilerDriver::CompilerDriver(
256*795d594fSAndroid Build Coastguard Worker     const CompilerOptions* compiler_options,
257*795d594fSAndroid Build Coastguard Worker     const VerificationResults* verification_results,
258*795d594fSAndroid Build Coastguard Worker     size_t thread_count,
259*795d594fSAndroid Build Coastguard Worker     int swap_fd)
260*795d594fSAndroid Build Coastguard Worker     : compiler_options_(compiler_options),
261*795d594fSAndroid Build Coastguard Worker       verification_results_(verification_results),
262*795d594fSAndroid Build Coastguard Worker       compiler_(),
263*795d594fSAndroid Build Coastguard Worker       number_of_soft_verifier_failures_(0),
264*795d594fSAndroid Build Coastguard Worker       had_hard_verifier_failure_(false),
265*795d594fSAndroid Build Coastguard Worker       parallel_thread_count_(thread_count),
266*795d594fSAndroid Build Coastguard Worker       stats_(new AOTCompilationStats),
267*795d594fSAndroid Build Coastguard Worker       compiled_method_storage_(swap_fd),
268*795d594fSAndroid Build Coastguard Worker       max_arena_alloc_(0) {
269*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options_ != nullptr);
270*795d594fSAndroid Build Coastguard Worker 
271*795d594fSAndroid Build Coastguard Worker   compiled_method_storage_.SetDedupeEnabled(compiler_options_->DeduplicateCode());
272*795d594fSAndroid Build Coastguard Worker   compiler_.reset(Compiler::Create(*compiler_options, &compiled_method_storage_));
273*795d594fSAndroid Build Coastguard Worker }
274*795d594fSAndroid Build Coastguard Worker 
~CompilerDriver()275*795d594fSAndroid Build Coastguard Worker CompilerDriver::~CompilerDriver() {
276*795d594fSAndroid Build Coastguard Worker   compiled_methods_.Visit(
277*795d594fSAndroid Build Coastguard Worker       [this]([[maybe_unused]] const DexFileReference& ref, CompiledMethod* method) {
278*795d594fSAndroid Build Coastguard Worker         if (method != nullptr) {
279*795d594fSAndroid Build Coastguard Worker           CompiledMethod::ReleaseSwapAllocatedCompiledMethod(GetCompiledMethodStorage(), method);
280*795d594fSAndroid Build Coastguard Worker         }
281*795d594fSAndroid Build Coastguard Worker       });
282*795d594fSAndroid Build Coastguard Worker }
283*795d594fSAndroid Build Coastguard Worker 
284*795d594fSAndroid Build Coastguard Worker 
285*795d594fSAndroid Build Coastguard Worker #define CREATE_TRAMPOLINE(type, abi, offset)                                            \
286*795d594fSAndroid Build Coastguard Worker     if (Is64BitInstructionSet(GetCompilerOptions().GetInstructionSet())) {              \
287*795d594fSAndroid Build Coastguard Worker       return CreateTrampoline64(GetCompilerOptions().GetInstructionSet(),               \
288*795d594fSAndroid Build Coastguard Worker                                 abi,                                                    \
289*795d594fSAndroid Build Coastguard Worker                                 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset));  \
290*795d594fSAndroid Build Coastguard Worker     } else {                                                                            \
291*795d594fSAndroid Build Coastguard Worker       return CreateTrampoline32(GetCompilerOptions().GetInstructionSet(),               \
292*795d594fSAndroid Build Coastguard Worker                                 abi,                                                    \
293*795d594fSAndroid Build Coastguard Worker                                 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset));  \
294*795d594fSAndroid Build Coastguard Worker     }
295*795d594fSAndroid Build Coastguard Worker 
CreateJniDlsymLookupTrampoline() const296*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookupTrampoline() const {
297*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
298*795d594fSAndroid Build Coastguard Worker }
299*795d594fSAndroid Build Coastguard Worker 
300*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>>
CreateJniDlsymLookupCriticalTrampoline() const301*795d594fSAndroid Build Coastguard Worker CompilerDriver::CreateJniDlsymLookupCriticalTrampoline() const {
302*795d594fSAndroid Build Coastguard Worker   // @CriticalNative calls do not have the `JNIEnv*` parameter, so this trampoline uses the
303*795d594fSAndroid Build Coastguard Worker   // architecture-dependent access to `Thread*` using the managed code ABI, i.e. `kQuickAbi`.
304*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(JNI, kQuickAbi, pDlsymLookupCritical)
305*795d594fSAndroid Build Coastguard Worker }
306*795d594fSAndroid Build Coastguard Worker 
CreateQuickGenericJniTrampoline() const307*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
308*795d594fSAndroid Build Coastguard Worker     const {
309*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
310*795d594fSAndroid Build Coastguard Worker }
311*795d594fSAndroid Build Coastguard Worker 
CreateQuickImtConflictTrampoline() const312*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
313*795d594fSAndroid Build Coastguard Worker     const {
314*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
315*795d594fSAndroid Build Coastguard Worker }
316*795d594fSAndroid Build Coastguard Worker 
CreateQuickResolutionTrampoline() const317*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
318*795d594fSAndroid Build Coastguard Worker     const {
319*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
320*795d594fSAndroid Build Coastguard Worker }
321*795d594fSAndroid Build Coastguard Worker 
CreateQuickToInterpreterBridge() const322*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
323*795d594fSAndroid Build Coastguard Worker     const {
324*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
325*795d594fSAndroid Build Coastguard Worker }
326*795d594fSAndroid Build Coastguard Worker 
CreateNterpTrampoline() const327*795d594fSAndroid Build Coastguard Worker std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateNterpTrampoline()
328*795d594fSAndroid Build Coastguard Worker     const {
329*795d594fSAndroid Build Coastguard Worker   // We use QuickToInterpreterBridge to not waste one word in the Thread object.
330*795d594fSAndroid Build Coastguard Worker   // The Nterp trampoline gets replaced with the nterp entrypoint when loading
331*795d594fSAndroid Build Coastguard Worker   // an image.
332*795d594fSAndroid Build Coastguard Worker   CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
333*795d594fSAndroid Build Coastguard Worker }
334*795d594fSAndroid Build Coastguard Worker #undef CREATE_TRAMPOLINE
335*795d594fSAndroid Build Coastguard Worker 
CompileAll(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)336*795d594fSAndroid Build Coastguard Worker void CompilerDriver::CompileAll(jobject class_loader,
337*795d594fSAndroid Build Coastguard Worker                                 const std::vector<const DexFile*>& dex_files,
338*795d594fSAndroid Build Coastguard Worker                                 TimingLogger* timings) {
339*795d594fSAndroid Build Coastguard Worker   DCHECK(!Runtime::Current()->IsStarted());
340*795d594fSAndroid Build Coastguard Worker 
341*795d594fSAndroid Build Coastguard Worker   CheckThreadPools();
342*795d594fSAndroid Build Coastguard Worker 
343*795d594fSAndroid Build Coastguard Worker   // Compile:
344*795d594fSAndroid Build Coastguard Worker   // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
345*795d594fSAndroid Build Coastguard Worker   //    compilation.
346*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsAnyCompilationEnabled()) {
347*795d594fSAndroid Build Coastguard Worker     Compile(class_loader, dex_files, timings);
348*795d594fSAndroid Build Coastguard Worker   }
349*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().GetDumpStats()) {
350*795d594fSAndroid Build Coastguard Worker     stats_->Dump();
351*795d594fSAndroid Build Coastguard Worker   }
352*795d594fSAndroid Build Coastguard Worker }
353*795d594fSAndroid Build Coastguard Worker 
354*795d594fSAndroid Build Coastguard Worker // Does the runtime for the InstructionSet provide an implementation returned by
355*795d594fSAndroid Build Coastguard Worker // GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
InstructionSetHasGenericJniStub(InstructionSet isa)356*795d594fSAndroid Build Coastguard Worker static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
357*795d594fSAndroid Build Coastguard Worker   switch (isa) {
358*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kArm:
359*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kArm64:
360*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kThumb2:
361*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kX86:
362*795d594fSAndroid Build Coastguard Worker     case InstructionSet::kX86_64: return true;
363*795d594fSAndroid Build Coastguard Worker     default: return false;
364*795d594fSAndroid Build Coastguard Worker   }
365*795d594fSAndroid Build Coastguard Worker }
366*795d594fSAndroid Build Coastguard Worker 
367*795d594fSAndroid Build Coastguard Worker template <typename CompileFn>
CompileMethodHarness(Thread * self,CompilerDriver * driver,const dex::CodeItem * code_item,uint32_t access_flags,uint16_t class_def_idx,uint32_t method_idx,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache,CompileFn compile_fn)368*795d594fSAndroid Build Coastguard Worker static void CompileMethodHarness(
369*795d594fSAndroid Build Coastguard Worker     Thread* self,
370*795d594fSAndroid Build Coastguard Worker     CompilerDriver* driver,
371*795d594fSAndroid Build Coastguard Worker     const dex::CodeItem* code_item,
372*795d594fSAndroid Build Coastguard Worker     uint32_t access_flags,
373*795d594fSAndroid Build Coastguard Worker     uint16_t class_def_idx,
374*795d594fSAndroid Build Coastguard Worker     uint32_t method_idx,
375*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader,
376*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file,
377*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache,
378*795d594fSAndroid Build Coastguard Worker     CompileFn compile_fn) {
379*795d594fSAndroid Build Coastguard Worker   DCHECK(driver != nullptr);
380*795d594fSAndroid Build Coastguard Worker   CompiledMethod* compiled_method;
381*795d594fSAndroid Build Coastguard Worker   uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
382*795d594fSAndroid Build Coastguard Worker   MethodReference method_ref(&dex_file, method_idx);
383*795d594fSAndroid Build Coastguard Worker 
384*795d594fSAndroid Build Coastguard Worker   compiled_method = compile_fn(self,
385*795d594fSAndroid Build Coastguard Worker                                driver,
386*795d594fSAndroid Build Coastguard Worker                                code_item,
387*795d594fSAndroid Build Coastguard Worker                                access_flags,
388*795d594fSAndroid Build Coastguard Worker                                class_def_idx,
389*795d594fSAndroid Build Coastguard Worker                                method_idx,
390*795d594fSAndroid Build Coastguard Worker                                class_loader,
391*795d594fSAndroid Build Coastguard Worker                                dex_file,
392*795d594fSAndroid Build Coastguard Worker                                dex_cache);
393*795d594fSAndroid Build Coastguard Worker 
394*795d594fSAndroid Build Coastguard Worker   if (kTimeCompileMethod) {
395*795d594fSAndroid Build Coastguard Worker     uint64_t duration_ns = NanoTime() - start_ns;
396*795d594fSAndroid Build Coastguard Worker     if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
397*795d594fSAndroid Build Coastguard Worker       LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
398*795d594fSAndroid Build Coastguard Worker                    << " took " << PrettyDuration(duration_ns);
399*795d594fSAndroid Build Coastguard Worker     }
400*795d594fSAndroid Build Coastguard Worker   }
401*795d594fSAndroid Build Coastguard Worker 
402*795d594fSAndroid Build Coastguard Worker   if (compiled_method != nullptr) {
403*795d594fSAndroid Build Coastguard Worker     driver->AddCompiledMethod(method_ref, compiled_method);
404*795d594fSAndroid Build Coastguard Worker   }
405*795d594fSAndroid Build Coastguard Worker 
406*795d594fSAndroid Build Coastguard Worker   if (self->IsExceptionPending()) {
407*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
408*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
409*795d594fSAndroid Build Coastguard Worker         << self->GetException()->Dump();
410*795d594fSAndroid Build Coastguard Worker   }
411*795d594fSAndroid Build Coastguard Worker }
412*795d594fSAndroid Build Coastguard Worker 
413*795d594fSAndroid Build Coastguard Worker // Checks whether profile guided compilation is enabled and if the method should be compiled
414*795d594fSAndroid Build Coastguard Worker // according to the profile file.
ShouldCompileBasedOnProfile(const CompilerOptions & compiler_options,ProfileCompilationInfo::ProfileIndexType profile_index,MethodReference method_ref)415*795d594fSAndroid Build Coastguard Worker static bool ShouldCompileBasedOnProfile(const CompilerOptions& compiler_options,
416*795d594fSAndroid Build Coastguard Worker                                         ProfileCompilationInfo::ProfileIndexType profile_index,
417*795d594fSAndroid Build Coastguard Worker                                         MethodReference method_ref) {
418*795d594fSAndroid Build Coastguard Worker   if (profile_index == ProfileCompilationInfo::MaxProfileIndex()) {
419*795d594fSAndroid Build Coastguard Worker     // No profile for this dex file. Check if we're actually compiling based on a profile.
420*795d594fSAndroid Build Coastguard Worker     if (!CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter())) {
421*795d594fSAndroid Build Coastguard Worker       return true;
422*795d594fSAndroid Build Coastguard Worker     }
423*795d594fSAndroid Build Coastguard Worker     // Profile-based compilation without profile for this dex file. Do not compile the method.
424*795d594fSAndroid Build Coastguard Worker     DCHECK(compiler_options.GetProfileCompilationInfo() == nullptr ||
425*795d594fSAndroid Build Coastguard Worker            compiler_options.GetProfileCompilationInfo()->FindDexFile(*method_ref.dex_file) ==
426*795d594fSAndroid Build Coastguard Worker                ProfileCompilationInfo::MaxProfileIndex());
427*795d594fSAndroid Build Coastguard Worker     return false;
428*795d594fSAndroid Build Coastguard Worker   } else {
429*795d594fSAndroid Build Coastguard Worker     DCHECK(CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter()));
430*795d594fSAndroid Build Coastguard Worker     const ProfileCompilationInfo* profile_compilation_info =
431*795d594fSAndroid Build Coastguard Worker         compiler_options.GetProfileCompilationInfo();
432*795d594fSAndroid Build Coastguard Worker     DCHECK(profile_compilation_info != nullptr);
433*795d594fSAndroid Build Coastguard Worker 
434*795d594fSAndroid Build Coastguard Worker     bool result = profile_compilation_info->IsHotMethod(profile_index, method_ref.index);
435*795d594fSAndroid Build Coastguard Worker 
436*795d594fSAndroid Build Coastguard Worker     // On non-low RAM devices, compile startup methods to potentially speed up
437*795d594fSAndroid Build Coastguard Worker     // startup.
438*795d594fSAndroid Build Coastguard Worker     if (!result && !Runtime::Current()->GetHeap()->IsLowMemoryMode()) {
439*795d594fSAndroid Build Coastguard Worker       result = profile_compilation_info->IsStartupMethod(profile_index, method_ref.index);
440*795d594fSAndroid Build Coastguard Worker     }
441*795d594fSAndroid Build Coastguard Worker 
442*795d594fSAndroid Build Coastguard Worker     if (kDebugProfileGuidedCompilation) {
443*795d594fSAndroid Build Coastguard Worker       LOG(INFO) << "[ProfileGuidedCompilation] "
444*795d594fSAndroid Build Coastguard Worker           << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
445*795d594fSAndroid Build Coastguard Worker     }
446*795d594fSAndroid Build Coastguard Worker 
447*795d594fSAndroid Build Coastguard Worker 
448*795d594fSAndroid Build Coastguard Worker     return result;
449*795d594fSAndroid Build Coastguard Worker   }
450*795d594fSAndroid Build Coastguard Worker }
451*795d594fSAndroid Build Coastguard Worker 
CompileMethodQuick(Thread * self,CompilerDriver * driver,const dex::CodeItem * code_item,uint32_t access_flags,uint16_t class_def_idx,uint32_t method_idx,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,Handle<mirror::DexCache> dex_cache,ProfileCompilationInfo::ProfileIndexType profile_index)452*795d594fSAndroid Build Coastguard Worker static void CompileMethodQuick(
453*795d594fSAndroid Build Coastguard Worker     Thread* self,
454*795d594fSAndroid Build Coastguard Worker     CompilerDriver* driver,
455*795d594fSAndroid Build Coastguard Worker     const dex::CodeItem* code_item,
456*795d594fSAndroid Build Coastguard Worker     uint32_t access_flags,
457*795d594fSAndroid Build Coastguard Worker     uint16_t class_def_idx,
458*795d594fSAndroid Build Coastguard Worker     uint32_t method_idx,
459*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader,
460*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file,
461*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache,
462*795d594fSAndroid Build Coastguard Worker     ProfileCompilationInfo::ProfileIndexType profile_index) {
463*795d594fSAndroid Build Coastguard Worker   auto quick_fn = [profile_index]([[maybe_unused]] Thread* self,
464*795d594fSAndroid Build Coastguard Worker                                   CompilerDriver* driver,
465*795d594fSAndroid Build Coastguard Worker                                   const dex::CodeItem* code_item,
466*795d594fSAndroid Build Coastguard Worker                                   uint32_t access_flags,
467*795d594fSAndroid Build Coastguard Worker                                   uint16_t class_def_idx,
468*795d594fSAndroid Build Coastguard Worker                                   uint32_t method_idx,
469*795d594fSAndroid Build Coastguard Worker                                   Handle<mirror::ClassLoader> class_loader,
470*795d594fSAndroid Build Coastguard Worker                                   const DexFile& dex_file,
471*795d594fSAndroid Build Coastguard Worker                                   Handle<mirror::DexCache> dex_cache) {
472*795d594fSAndroid Build Coastguard Worker     DCHECK(driver != nullptr);
473*795d594fSAndroid Build Coastguard Worker     const VerificationResults* results = driver->GetVerificationResults();
474*795d594fSAndroid Build Coastguard Worker     DCHECK(results != nullptr);
475*795d594fSAndroid Build Coastguard Worker     MethodReference method_ref(&dex_file, method_idx);
476*795d594fSAndroid Build Coastguard Worker     CompiledMethod* compiled_method = nullptr;
477*795d594fSAndroid Build Coastguard Worker     if (results->IsUncompilableMethod(method_ref)) {
478*795d594fSAndroid Build Coastguard Worker       return compiled_method;
479*795d594fSAndroid Build Coastguard Worker     }
480*795d594fSAndroid Build Coastguard Worker 
481*795d594fSAndroid Build Coastguard Worker     if ((access_flags & kAccNative) != 0) {
482*795d594fSAndroid Build Coastguard Worker       // Are we extracting only and have support for generic JNI down calls?
483*795d594fSAndroid Build Coastguard Worker       const CompilerOptions& compiler_options = driver->GetCompilerOptions();
484*795d594fSAndroid Build Coastguard Worker       if (!compiler_options.IsJniCompilationEnabled() &&
485*795d594fSAndroid Build Coastguard Worker           InstructionSetHasGenericJniStub(compiler_options.GetInstructionSet())) {
486*795d594fSAndroid Build Coastguard Worker         // Leaving this empty will trigger the generic JNI version
487*795d594fSAndroid Build Coastguard Worker       } else {
488*795d594fSAndroid Build Coastguard Worker         // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
489*795d594fSAndroid Build Coastguard Worker         access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
490*795d594fSAndroid Build Coastguard Worker             dex_file, dex_file.GetClassDef(class_def_idx), method_idx);
491*795d594fSAndroid Build Coastguard Worker         const void* boot_jni_stub = nullptr;
492*795d594fSAndroid Build Coastguard Worker         if (!Runtime::Current()->GetHeap()->GetBootImageSpaces().empty()) {
493*795d594fSAndroid Build Coastguard Worker           // Skip the compilation for native method if found an usable boot JNI stub.
494*795d594fSAndroid Build Coastguard Worker           ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
495*795d594fSAndroid Build Coastguard Worker           std::string_view shorty = dex_file.GetMethodShortyView(dex_file.GetMethodId(method_idx));
496*795d594fSAndroid Build Coastguard Worker           boot_jni_stub = class_linker->FindBootJniStub(access_flags, shorty);
497*795d594fSAndroid Build Coastguard Worker         }
498*795d594fSAndroid Build Coastguard Worker         if (boot_jni_stub == nullptr) {
499*795d594fSAndroid Build Coastguard Worker           compiled_method =
500*795d594fSAndroid Build Coastguard Worker               driver->GetCompiler()->JniCompile(access_flags, method_idx, dex_file, dex_cache);
501*795d594fSAndroid Build Coastguard Worker           CHECK(compiled_method != nullptr);
502*795d594fSAndroid Build Coastguard Worker         }
503*795d594fSAndroid Build Coastguard Worker       }
504*795d594fSAndroid Build Coastguard Worker     } else if ((access_flags & kAccAbstract) != 0) {
505*795d594fSAndroid Build Coastguard Worker       // Abstract methods don't have code.
506*795d594fSAndroid Build Coastguard Worker     } else if (annotations::MethodIsNeverCompile(dex_file,
507*795d594fSAndroid Build Coastguard Worker                                                  dex_file.GetClassDef(class_def_idx),
508*795d594fSAndroid Build Coastguard Worker                                                  method_idx)) {
509*795d594fSAndroid Build Coastguard Worker       // Method is annotated with @NeverCompile and should not be compiled.
510*795d594fSAndroid Build Coastguard Worker     } else {
511*795d594fSAndroid Build Coastguard Worker       const CompilerOptions& compiler_options = driver->GetCompilerOptions();
512*795d594fSAndroid Build Coastguard Worker       // Don't compile class initializers unless kEverything.
513*795d594fSAndroid Build Coastguard Worker       bool compile = (compiler_options.GetCompilerFilter() == CompilerFilter::kEverything) ||
514*795d594fSAndroid Build Coastguard Worker          ((access_flags & kAccConstructor) == 0) || ((access_flags & kAccStatic) == 0);
515*795d594fSAndroid Build Coastguard Worker       // Check if we should compile based on the profile.
516*795d594fSAndroid Build Coastguard Worker       compile = compile && ShouldCompileBasedOnProfile(compiler_options, profile_index, method_ref);
517*795d594fSAndroid Build Coastguard Worker 
518*795d594fSAndroid Build Coastguard Worker       if (compile) {
519*795d594fSAndroid Build Coastguard Worker         // NOTE: if compiler declines to compile this method, it will return null.
520*795d594fSAndroid Build Coastguard Worker         compiled_method = driver->GetCompiler()->Compile(code_item,
521*795d594fSAndroid Build Coastguard Worker                                                          access_flags,
522*795d594fSAndroid Build Coastguard Worker                                                          class_def_idx,
523*795d594fSAndroid Build Coastguard Worker                                                          method_idx,
524*795d594fSAndroid Build Coastguard Worker                                                          class_loader,
525*795d594fSAndroid Build Coastguard Worker                                                          dex_file,
526*795d594fSAndroid Build Coastguard Worker                                                          dex_cache);
527*795d594fSAndroid Build Coastguard Worker         ProfileMethodsCheck check_type = compiler_options.CheckProfiledMethodsCompiled();
528*795d594fSAndroid Build Coastguard Worker         if (UNLIKELY(check_type != ProfileMethodsCheck::kNone)) {
529*795d594fSAndroid Build Coastguard Worker           DCHECK(ShouldCompileBasedOnProfile(compiler_options, profile_index, method_ref));
530*795d594fSAndroid Build Coastguard Worker           bool violation = (compiled_method == nullptr);
531*795d594fSAndroid Build Coastguard Worker           if (violation) {
532*795d594fSAndroid Build Coastguard Worker             std::ostringstream oss;
533*795d594fSAndroid Build Coastguard Worker             oss << "Failed to compile "
534*795d594fSAndroid Build Coastguard Worker                 << method_ref.dex_file->PrettyMethod(method_ref.index)
535*795d594fSAndroid Build Coastguard Worker                 << "[" << method_ref.dex_file->GetLocation() << "]"
536*795d594fSAndroid Build Coastguard Worker                 << " as expected by profile";
537*795d594fSAndroid Build Coastguard Worker             switch (check_type) {
538*795d594fSAndroid Build Coastguard Worker               case ProfileMethodsCheck::kNone:
539*795d594fSAndroid Build Coastguard Worker                 break;
540*795d594fSAndroid Build Coastguard Worker               case ProfileMethodsCheck::kLog:
541*795d594fSAndroid Build Coastguard Worker                 LOG(ERROR) << oss.str();
542*795d594fSAndroid Build Coastguard Worker                 break;
543*795d594fSAndroid Build Coastguard Worker               case ProfileMethodsCheck::kAbort:
544*795d594fSAndroid Build Coastguard Worker                 LOG(FATAL_WITHOUT_ABORT) << oss.str();
545*795d594fSAndroid Build Coastguard Worker                 _exit(1);
546*795d594fSAndroid Build Coastguard Worker             }
547*795d594fSAndroid Build Coastguard Worker           }
548*795d594fSAndroid Build Coastguard Worker         }
549*795d594fSAndroid Build Coastguard Worker       }
550*795d594fSAndroid Build Coastguard Worker     }
551*795d594fSAndroid Build Coastguard Worker     return compiled_method;
552*795d594fSAndroid Build Coastguard Worker   };
553*795d594fSAndroid Build Coastguard Worker   CompileMethodHarness(self,
554*795d594fSAndroid Build Coastguard Worker                        driver,
555*795d594fSAndroid Build Coastguard Worker                        code_item,
556*795d594fSAndroid Build Coastguard Worker                        access_flags,
557*795d594fSAndroid Build Coastguard Worker                        class_def_idx,
558*795d594fSAndroid Build Coastguard Worker                        method_idx,
559*795d594fSAndroid Build Coastguard Worker                        class_loader,
560*795d594fSAndroid Build Coastguard Worker                        dex_file,
561*795d594fSAndroid Build Coastguard Worker                        dex_cache,
562*795d594fSAndroid Build Coastguard Worker                        quick_fn);
563*795d594fSAndroid Build Coastguard Worker }
564*795d594fSAndroid Build Coastguard Worker 
Resolve(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)565*795d594fSAndroid Build Coastguard Worker void CompilerDriver::Resolve(jobject class_loader,
566*795d594fSAndroid Build Coastguard Worker                              const std::vector<const DexFile*>& dex_files,
567*795d594fSAndroid Build Coastguard Worker                              TimingLogger* timings) {
568*795d594fSAndroid Build Coastguard Worker   // Resolution allocates classes and needs to run single-threaded to be deterministic.
569*795d594fSAndroid Build Coastguard Worker   bool force_determinism = GetCompilerOptions().IsForceDeterminism();
570*795d594fSAndroid Build Coastguard Worker   ThreadPool* resolve_thread_pool = force_determinism
571*795d594fSAndroid Build Coastguard Worker                                      ? single_thread_pool_.get()
572*795d594fSAndroid Build Coastguard Worker                                      : parallel_thread_pool_.get();
573*795d594fSAndroid Build Coastguard Worker   size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
574*795d594fSAndroid Build Coastguard Worker 
575*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; i != dex_files.size(); ++i) {
576*795d594fSAndroid Build Coastguard Worker     const DexFile* dex_file = dex_files[i];
577*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file != nullptr);
578*795d594fSAndroid Build Coastguard Worker     ResolveDexFile(class_loader,
579*795d594fSAndroid Build Coastguard Worker                    *dex_file,
580*795d594fSAndroid Build Coastguard Worker                    resolve_thread_pool,
581*795d594fSAndroid Build Coastguard Worker                    resolve_thread_count,
582*795d594fSAndroid Build Coastguard Worker                    timings);
583*795d594fSAndroid Build Coastguard Worker   }
584*795d594fSAndroid Build Coastguard Worker }
585*795d594fSAndroid Build Coastguard Worker 
ResolveConstStrings(const std::vector<const DexFile * > & dex_files,bool only_startup_strings,TimingLogger * timings)586*795d594fSAndroid Build Coastguard Worker void CompilerDriver::ResolveConstStrings(const std::vector<const DexFile*>& dex_files,
587*795d594fSAndroid Build Coastguard Worker                                          bool only_startup_strings,
588*795d594fSAndroid Build Coastguard Worker                                          TimingLogger* timings) {
589*795d594fSAndroid Build Coastguard Worker   const ProfileCompilationInfo* profile_compilation_info =
590*795d594fSAndroid Build Coastguard Worker       GetCompilerOptions().GetProfileCompilationInfo();
591*795d594fSAndroid Build Coastguard Worker   if (only_startup_strings && profile_compilation_info == nullptr) {
592*795d594fSAndroid Build Coastguard Worker     // If there is no profile, don't resolve any strings. Resolving all of the strings in the image
593*795d594fSAndroid Build Coastguard Worker     // will cause a bloated app image and slow down startup.
594*795d594fSAndroid Build Coastguard Worker     return;
595*795d594fSAndroid Build Coastguard Worker   }
596*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
597*795d594fSAndroid Build Coastguard Worker   StackHandleScope<1> hs(soa.Self());
598*795d594fSAndroid Build Coastguard Worker   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
599*795d594fSAndroid Build Coastguard Worker   MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
600*795d594fSAndroid Build Coastguard Worker   size_t num_instructions = 0u;
601*795d594fSAndroid Build Coastguard Worker 
602*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
603*795d594fSAndroid Build Coastguard Worker     dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
604*795d594fSAndroid Build Coastguard Worker     TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
605*795d594fSAndroid Build Coastguard Worker 
606*795d594fSAndroid Build Coastguard Worker     ProfileCompilationInfo::ProfileIndexType profile_index =
607*795d594fSAndroid Build Coastguard Worker         ProfileCompilationInfo::MaxProfileIndex();
608*795d594fSAndroid Build Coastguard Worker     if (profile_compilation_info != nullptr) {
609*795d594fSAndroid Build Coastguard Worker       profile_index = profile_compilation_info->FindDexFile(*dex_file);
610*795d594fSAndroid Build Coastguard Worker       if (profile_index == ProfileCompilationInfo::MaxProfileIndex()) {
611*795d594fSAndroid Build Coastguard Worker         // We have a `ProfileCompilationInfo` but no data for this dex file.
612*795d594fSAndroid Build Coastguard Worker         // The code below would not find any method to process.
613*795d594fSAndroid Build Coastguard Worker         continue;
614*795d594fSAndroid Build Coastguard Worker       }
615*795d594fSAndroid Build Coastguard Worker     }
616*795d594fSAndroid Build Coastguard Worker 
617*795d594fSAndroid Build Coastguard Worker     // TODO: Implement a profile-based filter for the boot image. See b/76145463.
618*795d594fSAndroid Build Coastguard Worker     for (ClassAccessor accessor : dex_file->GetClasses()) {
619*795d594fSAndroid Build Coastguard Worker       // Skip methods that failed to verify since they may contain invalid Dex code.
620*795d594fSAndroid Build Coastguard Worker       if (GetClassStatus(ClassReference(dex_file, accessor.GetClassDefIndex())) <
621*795d594fSAndroid Build Coastguard Worker           ClassStatus::kRetryVerificationAtRuntime) {
622*795d594fSAndroid Build Coastguard Worker         continue;
623*795d594fSAndroid Build Coastguard Worker       }
624*795d594fSAndroid Build Coastguard Worker 
625*795d594fSAndroid Build Coastguard Worker       for (const ClassAccessor::Method& method : accessor.GetMethods()) {
626*795d594fSAndroid Build Coastguard Worker         if (profile_compilation_info != nullptr) {
627*795d594fSAndroid Build Coastguard Worker           DCHECK_NE(profile_index, ProfileCompilationInfo::MaxProfileIndex());
628*795d594fSAndroid Build Coastguard Worker           // There can be at most one class initializer in a class, so we shall not
629*795d594fSAndroid Build Coastguard Worker           // call `ProfileCompilationInfo::ContainsClass()` more than once per class.
630*795d594fSAndroid Build Coastguard Worker           constexpr uint32_t kMask = kAccConstructor | kAccStatic;
631*795d594fSAndroid Build Coastguard Worker           const bool is_startup_clinit =
632*795d594fSAndroid Build Coastguard Worker               (method.GetAccessFlags() & kMask) == kMask &&
633*795d594fSAndroid Build Coastguard Worker               profile_compilation_info->ContainsClass(profile_index, accessor.GetClassIdx());
634*795d594fSAndroid Build Coastguard Worker 
635*795d594fSAndroid Build Coastguard Worker           if (!is_startup_clinit) {
636*795d594fSAndroid Build Coastguard Worker             uint32_t method_index = method.GetIndex();
637*795d594fSAndroid Build Coastguard Worker             bool process_method = only_startup_strings
638*795d594fSAndroid Build Coastguard Worker                 ? profile_compilation_info->IsStartupMethod(profile_index, method_index)
639*795d594fSAndroid Build Coastguard Worker                 : profile_compilation_info->IsMethodInProfile(profile_index, method_index);
640*795d594fSAndroid Build Coastguard Worker             if (!process_method) {
641*795d594fSAndroid Build Coastguard Worker               continue;
642*795d594fSAndroid Build Coastguard Worker             }
643*795d594fSAndroid Build Coastguard Worker           }
644*795d594fSAndroid Build Coastguard Worker         }
645*795d594fSAndroid Build Coastguard Worker 
646*795d594fSAndroid Build Coastguard Worker         // Resolve const-strings in the code. Done to have deterministic allocation behavior. Right
647*795d594fSAndroid Build Coastguard Worker         // now this is single-threaded for simplicity.
648*795d594fSAndroid Build Coastguard Worker         // TODO: Collect the relevant string indices in parallel, then allocate them sequentially
649*795d594fSAndroid Build Coastguard Worker         // in a stable order.
650*795d594fSAndroid Build Coastguard Worker         for (const DexInstructionPcPair& inst : method.GetInstructions()) {
651*795d594fSAndroid Build Coastguard Worker           switch (inst->Opcode()) {
652*795d594fSAndroid Build Coastguard Worker             case Instruction::CONST_STRING:
653*795d594fSAndroid Build Coastguard Worker             case Instruction::CONST_STRING_JUMBO: {
654*795d594fSAndroid Build Coastguard Worker               dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING)
655*795d594fSAndroid Build Coastguard Worker                   ? inst->VRegB_21c()
656*795d594fSAndroid Build Coastguard Worker                   : inst->VRegB_31c());
657*795d594fSAndroid Build Coastguard Worker               ObjPtr<mirror::String> string = class_linker->ResolveString(string_index, dex_cache);
658*795d594fSAndroid Build Coastguard Worker               CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
659*795d594fSAndroid Build Coastguard Worker               ++num_instructions;
660*795d594fSAndroid Build Coastguard Worker               break;
661*795d594fSAndroid Build Coastguard Worker             }
662*795d594fSAndroid Build Coastguard Worker 
663*795d594fSAndroid Build Coastguard Worker             default:
664*795d594fSAndroid Build Coastguard Worker               break;
665*795d594fSAndroid Build Coastguard Worker           }
666*795d594fSAndroid Build Coastguard Worker         }
667*795d594fSAndroid Build Coastguard Worker       }
668*795d594fSAndroid Build Coastguard Worker     }
669*795d594fSAndroid Build Coastguard Worker   }
670*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "Resolved " << num_instructions << " const string instructions";
671*795d594fSAndroid Build Coastguard Worker }
672*795d594fSAndroid Build Coastguard Worker 
673*795d594fSAndroid Build Coastguard Worker // Initialize type check bit strings for check-cast and instance-of in the code. Done to have
674*795d594fSAndroid Build Coastguard Worker // deterministic allocation behavior. Right now this is single-threaded for simplicity.
675*795d594fSAndroid Build Coastguard Worker // TODO: Collect the relevant type indices in parallel, then process them sequentially in a
676*795d594fSAndroid Build Coastguard Worker //       stable order.
677*795d594fSAndroid Build Coastguard Worker 
InitializeTypeCheckBitstrings(CompilerDriver * driver,ClassLinker * class_linker,Handle<mirror::DexCache> dex_cache,const DexFile & dex_file,const ClassAccessor::Method & method)678*795d594fSAndroid Build Coastguard Worker static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
679*795d594fSAndroid Build Coastguard Worker                                           ClassLinker* class_linker,
680*795d594fSAndroid Build Coastguard Worker                                           Handle<mirror::DexCache> dex_cache,
681*795d594fSAndroid Build Coastguard Worker                                           const DexFile& dex_file,
682*795d594fSAndroid Build Coastguard Worker                                           const ClassAccessor::Method& method)
683*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
684*795d594fSAndroid Build Coastguard Worker   for (const DexInstructionPcPair& inst : method.GetInstructions()) {
685*795d594fSAndroid Build Coastguard Worker     switch (inst->Opcode()) {
686*795d594fSAndroid Build Coastguard Worker       case Instruction::CHECK_CAST:
687*795d594fSAndroid Build Coastguard Worker       case Instruction::INSTANCE_OF: {
688*795d594fSAndroid Build Coastguard Worker         dex::TypeIndex type_index(
689*795d594fSAndroid Build Coastguard Worker             (inst->Opcode() == Instruction::CHECK_CAST) ? inst->VRegB_21c() : inst->VRegC_22c());
690*795d594fSAndroid Build Coastguard Worker         const char* descriptor = dex_file.GetTypeDescriptor(type_index);
691*795d594fSAndroid Build Coastguard Worker         // We currently do not use the bitstring type check for array or final (including
692*795d594fSAndroid Build Coastguard Worker         // primitive) classes. We may reconsider this in future if it's deemed to be beneficial.
693*795d594fSAndroid Build Coastguard Worker         // And we cannot use it for classes outside the boot image as we do not know the runtime
694*795d594fSAndroid Build Coastguard Worker         // value of their bitstring when compiling (it may not even get assigned at runtime).
695*795d594fSAndroid Build Coastguard Worker         if (descriptor[0] == 'L' && driver->GetCompilerOptions().IsImageClass(descriptor)) {
696*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::Class> klass =
697*795d594fSAndroid Build Coastguard Worker               class_linker->LookupResolvedType(type_index,
698*795d594fSAndroid Build Coastguard Worker                                                dex_cache.Get(),
699*795d594fSAndroid Build Coastguard Worker                                                /* class_loader= */ nullptr);
700*795d594fSAndroid Build Coastguard Worker           CHECK(klass != nullptr) << descriptor << " should have been previously resolved.";
701*795d594fSAndroid Build Coastguard Worker           // Now assign the bitstring if the class is not final. Keep this in sync with sharpening.
702*795d594fSAndroid Build Coastguard Worker           if (!klass->IsFinal()) {
703*795d594fSAndroid Build Coastguard Worker             MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
704*795d594fSAndroid Build Coastguard Worker             SubtypeCheck<ObjPtr<mirror::Class>>::EnsureAssigned(klass);
705*795d594fSAndroid Build Coastguard Worker           }
706*795d594fSAndroid Build Coastguard Worker         }
707*795d594fSAndroid Build Coastguard Worker         break;
708*795d594fSAndroid Build Coastguard Worker       }
709*795d594fSAndroid Build Coastguard Worker 
710*795d594fSAndroid Build Coastguard Worker       default:
711*795d594fSAndroid Build Coastguard Worker         break;
712*795d594fSAndroid Build Coastguard Worker     }
713*795d594fSAndroid Build Coastguard Worker   }
714*795d594fSAndroid Build Coastguard Worker }
715*795d594fSAndroid Build Coastguard Worker 
InitializeTypeCheckBitstrings(CompilerDriver * driver,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)716*795d594fSAndroid Build Coastguard Worker static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
717*795d594fSAndroid Build Coastguard Worker                                           const std::vector<const DexFile*>& dex_files,
718*795d594fSAndroid Build Coastguard Worker                                           TimingLogger* timings) {
719*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
720*795d594fSAndroid Build Coastguard Worker   StackHandleScope<1> hs(soa.Self());
721*795d594fSAndroid Build Coastguard Worker   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
722*795d594fSAndroid Build Coastguard Worker   MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
723*795d594fSAndroid Build Coastguard Worker 
724*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
725*795d594fSAndroid Build Coastguard Worker     dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
726*795d594fSAndroid Build Coastguard Worker     TimingLogger::ScopedTiming t("Initialize type check bitstrings", timings);
727*795d594fSAndroid Build Coastguard Worker 
728*795d594fSAndroid Build Coastguard Worker     for (ClassAccessor accessor : dex_file->GetClasses()) {
729*795d594fSAndroid Build Coastguard Worker       // Direct and virtual methods.
730*795d594fSAndroid Build Coastguard Worker       for (const ClassAccessor::Method& method : accessor.GetMethods()) {
731*795d594fSAndroid Build Coastguard Worker         InitializeTypeCheckBitstrings(driver, class_linker, dex_cache, *dex_file, method);
732*795d594fSAndroid Build Coastguard Worker       }
733*795d594fSAndroid Build Coastguard Worker     }
734*795d594fSAndroid Build Coastguard Worker   }
735*795d594fSAndroid Build Coastguard Worker }
736*795d594fSAndroid Build Coastguard Worker 
CheckThreadPools()737*795d594fSAndroid Build Coastguard Worker inline void CompilerDriver::CheckThreadPools() {
738*795d594fSAndroid Build Coastguard Worker   DCHECK(parallel_thread_pool_ != nullptr);
739*795d594fSAndroid Build Coastguard Worker   DCHECK(single_thread_pool_ != nullptr);
740*795d594fSAndroid Build Coastguard Worker }
741*795d594fSAndroid Build Coastguard Worker 
EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,const std::vector<const DexFile * > & dex_files)742*795d594fSAndroid Build Coastguard Worker static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
743*795d594fSAndroid Build Coastguard Worker                                             const std::vector<const DexFile*>& dex_files) {
744*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
745*795d594fSAndroid Build Coastguard Worker   StackHandleScope<2> hs(soa.Self());
746*795d594fSAndroid Build Coastguard Worker   Handle<mirror::ClassLoader> class_loader(
747*795d594fSAndroid Build Coastguard Worker       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
748*795d594fSAndroid Build Coastguard Worker   MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
749*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
750*795d594fSAndroid Build Coastguard Worker 
751*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
752*795d594fSAndroid Build Coastguard Worker     for (ClassAccessor accessor : dex_file->GetClasses()) {
753*795d594fSAndroid Build Coastguard Worker       cls.Assign(
754*795d594fSAndroid Build Coastguard Worker           class_linker->FindClass(soa.Self(), *dex_file, accessor.GetClassIdx(), class_loader));
755*795d594fSAndroid Build Coastguard Worker       if (cls == nullptr) {
756*795d594fSAndroid Build Coastguard Worker         soa.Self()->ClearException();
757*795d594fSAndroid Build Coastguard Worker       } else if (&cls->GetDexFile() == dex_file) {
758*795d594fSAndroid Build Coastguard Worker         DCHECK(cls->IsErroneous() ||
759*795d594fSAndroid Build Coastguard Worker                cls->IsVerified() ||
760*795d594fSAndroid Build Coastguard Worker                cls->ShouldVerifyAtRuntime() ||
761*795d594fSAndroid Build Coastguard Worker                cls->IsVerifiedNeedsAccessChecks())
762*795d594fSAndroid Build Coastguard Worker             << cls->PrettyClass()
763*795d594fSAndroid Build Coastguard Worker             << " " << cls->GetStatus();
764*795d594fSAndroid Build Coastguard Worker       }
765*795d594fSAndroid Build Coastguard Worker     }
766*795d594fSAndroid Build Coastguard Worker   }
767*795d594fSAndroid Build Coastguard Worker }
768*795d594fSAndroid Build Coastguard Worker 
PrepareDexFilesForOatFile(TimingLogger * timings)769*795d594fSAndroid Build Coastguard Worker void CompilerDriver::PrepareDexFilesForOatFile([[maybe_unused]] TimingLogger* timings) {
770*795d594fSAndroid Build Coastguard Worker   compiled_classes_.AddDexFiles(GetCompilerOptions().GetDexFilesForOatFile());
771*795d594fSAndroid Build Coastguard Worker }
772*795d594fSAndroid Build Coastguard Worker 
773*795d594fSAndroid Build Coastguard Worker class CreateConflictTablesVisitor : public ClassVisitor {
774*795d594fSAndroid Build Coastguard Worker  public:
CreateConflictTablesVisitor(VariableSizedHandleScope & hs)775*795d594fSAndroid Build Coastguard Worker   explicit CreateConflictTablesVisitor(VariableSizedHandleScope& hs)
776*795d594fSAndroid Build Coastguard Worker       : hs_(hs) {}
777*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass)778*795d594fSAndroid Build Coastguard Worker   bool operator()(ObjPtr<mirror::Class> klass) override
779*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
780*795d594fSAndroid Build Coastguard Worker     if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
781*795d594fSAndroid Build Coastguard Worker       return true;
782*795d594fSAndroid Build Coastguard Worker     }
783*795d594fSAndroid Build Coastguard Worker     // Collect handles since there may be thread suspension in future EnsureInitialized.
784*795d594fSAndroid Build Coastguard Worker     to_visit_.push_back(hs_.NewHandle(klass));
785*795d594fSAndroid Build Coastguard Worker     return true;
786*795d594fSAndroid Build Coastguard Worker   }
787*795d594fSAndroid Build Coastguard Worker 
FillAllIMTAndConflictTables()788*795d594fSAndroid Build Coastguard Worker   void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
789*795d594fSAndroid Build Coastguard Worker     ScopedAssertNoThreadSuspension ants(__FUNCTION__);
790*795d594fSAndroid Build Coastguard Worker     for (Handle<mirror::Class> c : to_visit_) {
791*795d594fSAndroid Build Coastguard Worker       // Create the conflict tables.
792*795d594fSAndroid Build Coastguard Worker       FillIMTAndConflictTables(c.Get());
793*795d594fSAndroid Build Coastguard Worker     }
794*795d594fSAndroid Build Coastguard Worker   }
795*795d594fSAndroid Build Coastguard Worker 
796*795d594fSAndroid Build Coastguard Worker  private:
FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)797*795d594fSAndroid Build Coastguard Worker   void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
798*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
799*795d594fSAndroid Build Coastguard Worker     if (!klass->ShouldHaveImt()) {
800*795d594fSAndroid Build Coastguard Worker       return;
801*795d594fSAndroid Build Coastguard Worker     }
802*795d594fSAndroid Build Coastguard Worker     if (visited_classes_.find(klass.Ptr()) != visited_classes_.end()) {
803*795d594fSAndroid Build Coastguard Worker       return;
804*795d594fSAndroid Build Coastguard Worker     }
805*795d594fSAndroid Build Coastguard Worker     if (klass->HasSuperClass()) {
806*795d594fSAndroid Build Coastguard Worker       FillIMTAndConflictTables(klass->GetSuperClass());
807*795d594fSAndroid Build Coastguard Worker     }
808*795d594fSAndroid Build Coastguard Worker     if (!klass->IsTemp()) {
809*795d594fSAndroid Build Coastguard Worker       Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
810*795d594fSAndroid Build Coastguard Worker     }
811*795d594fSAndroid Build Coastguard Worker     visited_classes_.insert(klass.Ptr());
812*795d594fSAndroid Build Coastguard Worker   }
813*795d594fSAndroid Build Coastguard Worker 
814*795d594fSAndroid Build Coastguard Worker   VariableSizedHandleScope& hs_;
815*795d594fSAndroid Build Coastguard Worker   std::vector<Handle<mirror::Class>> to_visit_;
816*795d594fSAndroid Build Coastguard Worker   HashSet<mirror::Class*> visited_classes_;
817*795d594fSAndroid Build Coastguard Worker };
818*795d594fSAndroid Build Coastguard Worker 
PreCompile(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings,HashSet<std::string> * image_classes)819*795d594fSAndroid Build Coastguard Worker void CompilerDriver::PreCompile(jobject class_loader,
820*795d594fSAndroid Build Coastguard Worker                                 const std::vector<const DexFile*>& dex_files,
821*795d594fSAndroid Build Coastguard Worker                                 TimingLogger* timings,
822*795d594fSAndroid Build Coastguard Worker                                 /*inout*/ HashSet<std::string>* image_classes) {
823*795d594fSAndroid Build Coastguard Worker   CheckThreadPools();
824*795d594fSAndroid Build Coastguard Worker 
825*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
826*795d594fSAndroid Build Coastguard Worker 
827*795d594fSAndroid Build Coastguard Worker   // Precompile:
828*795d594fSAndroid Build Coastguard Worker   // 1) Load image classes.
829*795d594fSAndroid Build Coastguard Worker   // 2) Resolve all classes.
830*795d594fSAndroid Build Coastguard Worker   // 3) For deterministic boot image, resolve strings for const-string instructions.
831*795d594fSAndroid Build Coastguard Worker   // 4) Attempt to verify all classes.
832*795d594fSAndroid Build Coastguard Worker   // 5) Attempt to initialize image classes, and trivially initialized classes.
833*795d594fSAndroid Build Coastguard Worker   // 6) Update the set of image classes.
834*795d594fSAndroid Build Coastguard Worker   // 7) For deterministic boot image, initialize bitstrings for type checking.
835*795d594fSAndroid Build Coastguard Worker 
836*795d594fSAndroid Build Coastguard Worker   LoadImageClasses(timings, class_loader, image_classes);
837*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
838*795d594fSAndroid Build Coastguard Worker 
839*795d594fSAndroid Build Coastguard Worker   if (compiler_options_->AssumeClassesAreVerified()) {
840*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Verify none mode specified, skipping verification.";
841*795d594fSAndroid Build Coastguard Worker     SetVerified(class_loader, dex_files, timings);
842*795d594fSAndroid Build Coastguard Worker   } else {
843*795d594fSAndroid Build Coastguard Worker     DCHECK(compiler_options_->IsVerificationEnabled());
844*795d594fSAndroid Build Coastguard Worker 
845*795d594fSAndroid Build Coastguard Worker     if (compiler_options_->IsAnyCompilationEnabled()) {
846*795d594fSAndroid Build Coastguard Worker       // Avoid adding the dex files in the case where we aren't going to add compiled methods.
847*795d594fSAndroid Build Coastguard Worker       // This reduces RAM usage for this case.
848*795d594fSAndroid Build Coastguard Worker       for (const DexFile* dex_file : dex_files) {
849*795d594fSAndroid Build Coastguard Worker         // Can be already inserted. This happens for gtests.
850*795d594fSAndroid Build Coastguard Worker         if (!compiled_methods_.HaveDexFile(dex_file)) {
851*795d594fSAndroid Build Coastguard Worker           compiled_methods_.AddDexFile(dex_file);
852*795d594fSAndroid Build Coastguard Worker         }
853*795d594fSAndroid Build Coastguard Worker       }
854*795d594fSAndroid Build Coastguard Worker     }
855*795d594fSAndroid Build Coastguard Worker 
856*795d594fSAndroid Build Coastguard Worker     // Resolve eagerly for compilations always, and for verifications only if we are running with
857*795d594fSAndroid Build Coastguard Worker     // multiple threads.
858*795d594fSAndroid Build Coastguard Worker     const bool should_resolve_eagerly =
859*795d594fSAndroid Build Coastguard Worker         compiler_options_->IsAnyCompilationEnabled() ||
860*795d594fSAndroid Build Coastguard Worker         (!GetCompilerOptions().IsForceDeterminism() && parallel_thread_count_ > 1);
861*795d594fSAndroid Build Coastguard Worker     if (should_resolve_eagerly) {
862*795d594fSAndroid Build Coastguard Worker       Resolve(class_loader, dex_files, timings);
863*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
864*795d594fSAndroid Build Coastguard Worker     }
865*795d594fSAndroid Build Coastguard Worker 
866*795d594fSAndroid Build Coastguard Worker     Verify(class_loader, dex_files, timings);
867*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
868*795d594fSAndroid Build Coastguard Worker 
869*795d594fSAndroid Build Coastguard Worker     if (GetCompilerOptions().IsForceDeterminism() &&
870*795d594fSAndroid Build Coastguard Worker         (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension())) {
871*795d594fSAndroid Build Coastguard Worker       // Resolve strings from const-string. Do this now to have a deterministic image.
872*795d594fSAndroid Build Coastguard Worker       ResolveConstStrings(dex_files, /*only_startup_strings=*/ false, timings);
873*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
874*795d594fSAndroid Build Coastguard Worker     } else if (GetCompilerOptions().ResolveStartupConstStrings()) {
875*795d594fSAndroid Build Coastguard Worker       ResolveConstStrings(dex_files, /*only_startup_strings=*/ true, timings);
876*795d594fSAndroid Build Coastguard Worker     }
877*795d594fSAndroid Build Coastguard Worker 
878*795d594fSAndroid Build Coastguard Worker     if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
879*795d594fSAndroid Build Coastguard Worker       // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
880*795d594fSAndroid Build Coastguard Worker       // instances of this thread's stack.
881*795d594fSAndroid Build Coastguard Worker       LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
882*795d594fSAndroid Build Coastguard Worker                                << "in such situations. Please check the log.";
883*795d594fSAndroid Build Coastguard Worker       _exit(1);
884*795d594fSAndroid Build Coastguard Worker     } else if (number_of_soft_verifier_failures_ > 0 &&
885*795d594fSAndroid Build Coastguard Worker                GetCompilerOptions().AbortOnSoftVerifierFailure()) {
886*795d594fSAndroid Build Coastguard Worker       LOG(FATAL_WITHOUT_ABORT) << "Had " << number_of_soft_verifier_failures_ << " soft failure(s) "
887*795d594fSAndroid Build Coastguard Worker                                << "verifying all classes, and was asked to abort in such situations. "
888*795d594fSAndroid Build Coastguard Worker                                << "Please check the log.";
889*795d594fSAndroid Build Coastguard Worker       _exit(1);
890*795d594fSAndroid Build Coastguard Worker     }
891*795d594fSAndroid Build Coastguard Worker 
892*795d594fSAndroid Build Coastguard Worker     if (GetCompilerOptions().IsAppImage() && had_hard_verifier_failure_) {
893*795d594fSAndroid Build Coastguard Worker       // Prune erroneous classes and classes that depend on them.
894*795d594fSAndroid Build Coastguard Worker       UpdateImageClasses(timings, image_classes);
895*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "verify/UpdateImageClasses: " << GetMemoryUsageString(false);
896*795d594fSAndroid Build Coastguard Worker     }
897*795d594fSAndroid Build Coastguard Worker   }
898*795d594fSAndroid Build Coastguard Worker 
899*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsGeneratingImage()) {
900*795d594fSAndroid Build Coastguard Worker     // We can only initialize classes when their verification bit is set.
901*795d594fSAndroid Build Coastguard Worker     if (compiler_options_->AssumeClassesAreVerified() ||
902*795d594fSAndroid Build Coastguard Worker         compiler_options_->IsVerificationEnabled()) {
903*795d594fSAndroid Build Coastguard Worker       if (kIsDebugBuild) {
904*795d594fSAndroid Build Coastguard Worker         EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
905*795d594fSAndroid Build Coastguard Worker       }
906*795d594fSAndroid Build Coastguard Worker       InitializeClasses(class_loader, dex_files, timings);
907*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
908*795d594fSAndroid Build Coastguard Worker     }
909*795d594fSAndroid Build Coastguard Worker     {
910*795d594fSAndroid Build Coastguard Worker       // Create conflict tables, as the runtime expects boot image classes to
911*795d594fSAndroid Build Coastguard Worker       // always have their conflict tables filled.
912*795d594fSAndroid Build Coastguard Worker       ScopedObjectAccess soa(Thread::Current());
913*795d594fSAndroid Build Coastguard Worker       VariableSizedHandleScope hs(soa.Self());
914*795d594fSAndroid Build Coastguard Worker       CreateConflictTablesVisitor visitor(hs);
915*795d594fSAndroid Build Coastguard Worker       Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
916*795d594fSAndroid Build Coastguard Worker       visitor.FillAllIMTAndConflictTables();
917*795d594fSAndroid Build Coastguard Worker     }
918*795d594fSAndroid Build Coastguard Worker 
919*795d594fSAndroid Build Coastguard Worker     if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
920*795d594fSAndroid Build Coastguard Worker       UpdateImageClasses(timings, image_classes);
921*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
922*795d594fSAndroid Build Coastguard Worker     }
923*795d594fSAndroid Build Coastguard Worker 
924*795d594fSAndroid Build Coastguard Worker     if (kBitstringSubtypeCheckEnabled &&
925*795d594fSAndroid Build Coastguard Worker         GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
926*795d594fSAndroid Build Coastguard Worker       // Initialize type check bit string used by check-cast and instanceof.
927*795d594fSAndroid Build Coastguard Worker       // Do this now to have a deterministic image.
928*795d594fSAndroid Build Coastguard Worker       // Note: This is done after UpdateImageClasses() at it relies on the image
929*795d594fSAndroid Build Coastguard Worker       // classes to be final.
930*795d594fSAndroid Build Coastguard Worker       InitializeTypeCheckBitstrings(this, dex_files, timings);
931*795d594fSAndroid Build Coastguard Worker     }
932*795d594fSAndroid Build Coastguard Worker   }
933*795d594fSAndroid Build Coastguard Worker }
934*795d594fSAndroid Build Coastguard Worker 
935*795d594fSAndroid Build Coastguard Worker class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
936*795d594fSAndroid Build Coastguard Worker  public:
ResolveCatchBlockExceptionsClassVisitor(Thread * self)937*795d594fSAndroid Build Coastguard Worker   explicit ResolveCatchBlockExceptionsClassVisitor(Thread* self)
938*795d594fSAndroid Build Coastguard Worker       : hs_(self),
939*795d594fSAndroid Build Coastguard Worker         dex_file_records_(),
940*795d594fSAndroid Build Coastguard Worker         unprocessed_classes_(),
941*795d594fSAndroid Build Coastguard Worker         exception_types_to_resolve_(),
942*795d594fSAndroid Build Coastguard Worker         boot_images_start_(Runtime::Current()->GetHeap()->GetBootImagesStartAddress()),
943*795d594fSAndroid Build Coastguard Worker         boot_images_size_(Runtime::Current()->GetHeap()->GetBootImagesSize()) {}
944*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> c)945*795d594fSAndroid Build Coastguard Worker   bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
946*795d594fSAndroid Build Coastguard Worker     // Filter out classes from boot images we're compiling against.
947*795d594fSAndroid Build Coastguard Worker     // These have been processed when we compiled those boot images.
948*795d594fSAndroid Build Coastguard Worker     if (reinterpret_cast32<uint32_t>(c.Ptr()) - boot_images_start_ < boot_images_size_) {
949*795d594fSAndroid Build Coastguard Worker       DCHECK(Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(c));
950*795d594fSAndroid Build Coastguard Worker       return true;
951*795d594fSAndroid Build Coastguard Worker     }
952*795d594fSAndroid Build Coastguard Worker     // Filter out classes without methods.
953*795d594fSAndroid Build Coastguard Worker     // These include primitive types and array types which have no dex file.
954*795d594fSAndroid Build Coastguard Worker     if (c->GetMethodsPtr() == nullptr) {
955*795d594fSAndroid Build Coastguard Worker       return true;
956*795d594fSAndroid Build Coastguard Worker     }
957*795d594fSAndroid Build Coastguard Worker     auto it = dex_file_records_.find(&c->GetDexFile());
958*795d594fSAndroid Build Coastguard Worker     if (it != dex_file_records_.end()) {
959*795d594fSAndroid Build Coastguard Worker       DexFileRecord& record = it->second;
960*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(c->GetDexCache(), record.GetDexCache().Get());
961*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(c->GetClassLoader(), record.GetClassLoader().Get());
962*795d594fSAndroid Build Coastguard Worker       if (record.IsProcessedClass(c)) {
963*795d594fSAndroid Build Coastguard Worker         return true;
964*795d594fSAndroid Build Coastguard Worker       }
965*795d594fSAndroid Build Coastguard Worker     }
966*795d594fSAndroid Build Coastguard Worker     unprocessed_classes_.push_back(c);
967*795d594fSAndroid Build Coastguard Worker     return true;
968*795d594fSAndroid Build Coastguard Worker   }
969*795d594fSAndroid Build Coastguard Worker 
FindAndResolveExceptionTypes(Thread * self,ClassLinker * class_linker)970*795d594fSAndroid Build Coastguard Worker   void FindAndResolveExceptionTypes(Thread* self, ClassLinker* class_linker)
971*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
972*795d594fSAndroid Build Coastguard Worker     // If we try to resolve any exception types, we need to repeat the process.
973*795d594fSAndroid Build Coastguard Worker     // Even if we failed to resolve an exception type, we could have resolved its supertype
974*795d594fSAndroid Build Coastguard Worker     // or some implemented interfaces as a side-effect (the exception type could implement
975*795d594fSAndroid Build Coastguard Worker     // another unresolved interface) and we need to visit methods of such new resolved
976*795d594fSAndroid Build Coastguard Worker     // classes as they shall be recorded as image classes.
977*795d594fSAndroid Build Coastguard Worker     while (FindExceptionTypesToResolve(class_linker)) {
978*795d594fSAndroid Build Coastguard Worker       ResolveExceptionTypes(self, class_linker);
979*795d594fSAndroid Build Coastguard Worker     }
980*795d594fSAndroid Build Coastguard Worker   }
981*795d594fSAndroid Build Coastguard Worker 
982*795d594fSAndroid Build Coastguard Worker  private:
983*795d594fSAndroid Build Coastguard Worker   class DexFileRecord {
984*795d594fSAndroid Build Coastguard Worker    public:
DexFileRecord(Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)985*795d594fSAndroid Build Coastguard Worker     DexFileRecord(Handle<mirror::DexCache> dex_cache, Handle<mirror::ClassLoader> class_loader)
986*795d594fSAndroid Build Coastguard Worker         REQUIRES_SHARED(Locks::mutator_lock_)
987*795d594fSAndroid Build Coastguard Worker         : dex_cache_(dex_cache),
988*795d594fSAndroid Build Coastguard Worker           class_loader_(class_loader),
989*795d594fSAndroid Build Coastguard Worker           processed_classes_(/*start_bits=*/ dex_cache->GetDexFile()->NumClassDefs(),
990*795d594fSAndroid Build Coastguard Worker                              /*expandable=*/ false,
991*795d594fSAndroid Build Coastguard Worker                              Allocator::GetCallocAllocator()),
992*795d594fSAndroid Build Coastguard Worker           processed_exception_types_(/*start_bits=*/ dex_cache->GetDexFile()->NumTypeIds(),
993*795d594fSAndroid Build Coastguard Worker                                      /*expandable=*/ false,
994*795d594fSAndroid Build Coastguard Worker                                      Allocator::GetCallocAllocator()) {}
995*795d594fSAndroid Build Coastguard Worker 
GetDexCache()996*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> GetDexCache() {
997*795d594fSAndroid Build Coastguard Worker       return dex_cache_;
998*795d594fSAndroid Build Coastguard Worker     }
999*795d594fSAndroid Build Coastguard Worker 
GetClassLoader()1000*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> GetClassLoader() {
1001*795d594fSAndroid Build Coastguard Worker       return class_loader_;
1002*795d594fSAndroid Build Coastguard Worker     }
1003*795d594fSAndroid Build Coastguard Worker 
IsProcessedClass(ObjPtr<mirror::Class> c)1004*795d594fSAndroid Build Coastguard Worker     bool IsProcessedClass(ObjPtr<mirror::Class> c) REQUIRES_SHARED(Locks::mutator_lock_) {
1005*795d594fSAndroid Build Coastguard Worker       DCHECK_LT(c->GetDexClassDefIndex(), dex_cache_->GetDexFile()->NumClassDefs());
1006*795d594fSAndroid Build Coastguard Worker       return processed_classes_.IsBitSet(c->GetDexClassDefIndex());
1007*795d594fSAndroid Build Coastguard Worker     }
1008*795d594fSAndroid Build Coastguard Worker 
MarkProcessedClass(ObjPtr<mirror::Class> c)1009*795d594fSAndroid Build Coastguard Worker     void MarkProcessedClass(ObjPtr<mirror::Class> c) REQUIRES_SHARED(Locks::mutator_lock_) {
1010*795d594fSAndroid Build Coastguard Worker       DCHECK_LT(c->GetDexClassDefIndex(), dex_cache_->GetDexFile()->NumClassDefs());
1011*795d594fSAndroid Build Coastguard Worker       processed_classes_.SetBit(c->GetDexClassDefIndex());
1012*795d594fSAndroid Build Coastguard Worker     }
1013*795d594fSAndroid Build Coastguard Worker 
IsProcessedExceptionType(dex::TypeIndex type_idx)1014*795d594fSAndroid Build Coastguard Worker     bool IsProcessedExceptionType(dex::TypeIndex type_idx) REQUIRES_SHARED(Locks::mutator_lock_) {
1015*795d594fSAndroid Build Coastguard Worker       DCHECK_LT(type_idx.index_, dex_cache_->GetDexFile()->NumTypeIds());
1016*795d594fSAndroid Build Coastguard Worker       return processed_exception_types_.IsBitSet(type_idx.index_);
1017*795d594fSAndroid Build Coastguard Worker     }
1018*795d594fSAndroid Build Coastguard Worker 
MarkProcessedExceptionType(dex::TypeIndex type_idx)1019*795d594fSAndroid Build Coastguard Worker     void MarkProcessedExceptionType(dex::TypeIndex type_idx) REQUIRES_SHARED(Locks::mutator_lock_) {
1020*795d594fSAndroid Build Coastguard Worker       DCHECK_LT(type_idx.index_, dex_cache_->GetDexFile()->NumTypeIds());
1021*795d594fSAndroid Build Coastguard Worker       processed_exception_types_.SetBit(type_idx.index_);
1022*795d594fSAndroid Build Coastguard Worker     }
1023*795d594fSAndroid Build Coastguard Worker 
1024*795d594fSAndroid Build Coastguard Worker    private:
1025*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache_;
1026*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader_;
1027*795d594fSAndroid Build Coastguard Worker     BitVector processed_classes_;
1028*795d594fSAndroid Build Coastguard Worker     BitVector processed_exception_types_;
1029*795d594fSAndroid Build Coastguard Worker   };
1030*795d594fSAndroid Build Coastguard Worker 
1031*795d594fSAndroid Build Coastguard Worker   struct ExceptionTypeReference {
1032*795d594fSAndroid Build Coastguard Worker     dex::TypeIndex exception_type_idx;
1033*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache;
1034*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader;
1035*795d594fSAndroid Build Coastguard Worker   };
1036*795d594fSAndroid Build Coastguard Worker 
1037*795d594fSAndroid Build Coastguard Worker   bool FindExceptionTypesToResolve(ClassLinker* class_linker)
1038*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1039*795d594fSAndroid Build Coastguard Worker 
ResolveExceptionTypes(Thread * self,ClassLinker * class_linker)1040*795d594fSAndroid Build Coastguard Worker   void ResolveExceptionTypes(Thread* self, ClassLinker* class_linker)
1041*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1042*795d594fSAndroid Build Coastguard Worker     DCHECK(!exception_types_to_resolve_.empty());
1043*795d594fSAndroid Build Coastguard Worker     for (auto [exception_type_idx, dex_cache, class_loader] : exception_types_to_resolve_) {
1044*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> exception_class =
1045*795d594fSAndroid Build Coastguard Worker           class_linker->ResolveType(exception_type_idx, dex_cache, class_loader);
1046*795d594fSAndroid Build Coastguard Worker       if (exception_class == nullptr) {
1047*795d594fSAndroid Build Coastguard Worker         VLOG(compiler) << "Failed to resolve exception class "
1048*795d594fSAndroid Build Coastguard Worker             << dex_cache->GetDexFile()->GetTypeDescriptorView(exception_type_idx);
1049*795d594fSAndroid Build Coastguard Worker         self->ClearException();
1050*795d594fSAndroid Build Coastguard Worker       } else {
1051*795d594fSAndroid Build Coastguard Worker         DCHECK(GetClassRoot<mirror::Throwable>(class_linker)->IsAssignableFrom(exception_class));
1052*795d594fSAndroid Build Coastguard Worker       }
1053*795d594fSAndroid Build Coastguard Worker     }
1054*795d594fSAndroid Build Coastguard Worker     exception_types_to_resolve_.clear();
1055*795d594fSAndroid Build Coastguard Worker   }
1056*795d594fSAndroid Build Coastguard Worker 
1057*795d594fSAndroid Build Coastguard Worker   VariableSizedHandleScope hs_;
1058*795d594fSAndroid Build Coastguard Worker   SafeMap<const DexFile*, DexFileRecord> dex_file_records_;
1059*795d594fSAndroid Build Coastguard Worker   std::vector<ObjPtr<mirror::Class>> unprocessed_classes_;
1060*795d594fSAndroid Build Coastguard Worker   std::vector<ExceptionTypeReference> exception_types_to_resolve_;
1061*795d594fSAndroid Build Coastguard Worker   const uint32_t boot_images_start_;
1062*795d594fSAndroid Build Coastguard Worker   const uint32_t boot_images_size_;
1063*795d594fSAndroid Build Coastguard Worker };
1064*795d594fSAndroid Build Coastguard Worker 
FindExceptionTypesToResolve(ClassLinker * class_linker)1065*795d594fSAndroid Build Coastguard Worker bool ResolveCatchBlockExceptionsClassVisitor::FindExceptionTypesToResolve(
1066*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker) {
1067*795d594fSAndroid Build Coastguard Worker   // Thread suspension is not allowed while the `ResolveCatchBlockExceptionsClassVisitor`
1068*795d594fSAndroid Build Coastguard Worker   // is using a `std::vector<ObjPtr<mirror::Class>>`.
1069*795d594fSAndroid Build Coastguard Worker   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1070*795d594fSAndroid Build Coastguard Worker   DCHECK(unprocessed_classes_.empty());
1071*795d594fSAndroid Build Coastguard Worker   class_linker->VisitClasses(this);
1072*795d594fSAndroid Build Coastguard Worker   if (unprocessed_classes_.empty()) {
1073*795d594fSAndroid Build Coastguard Worker     return false;
1074*795d594fSAndroid Build Coastguard Worker   }
1075*795d594fSAndroid Build Coastguard Worker 
1076*795d594fSAndroid Build Coastguard Worker   DCHECK(exception_types_to_resolve_.empty());
1077*795d594fSAndroid Build Coastguard Worker   const PointerSize pointer_size = class_linker->GetImagePointerSize();
1078*795d594fSAndroid Build Coastguard Worker   for (ObjPtr<mirror::Class> klass : unprocessed_classes_) {
1079*795d594fSAndroid Build Coastguard Worker     const DexFile* dex_file = &klass->GetDexFile();
1080*795d594fSAndroid Build Coastguard Worker     DexFileRecord& record = dex_file_records_.GetOrCreate(
1081*795d594fSAndroid Build Coastguard Worker         dex_file,
1082*795d594fSAndroid Build Coastguard Worker         // NO_THREAD_SAFETY_ANALYSIS: Called from unannotated `SafeMap<>::GetOrCreate()`.
1083*795d594fSAndroid Build Coastguard Worker         [&]() NO_THREAD_SAFETY_ANALYSIS {
1084*795d594fSAndroid Build Coastguard Worker           return DexFileRecord(hs_.NewHandle(klass->GetDexCache()),
1085*795d594fSAndroid Build Coastguard Worker                                hs_.NewHandle(klass->GetClassLoader()));
1086*795d594fSAndroid Build Coastguard Worker         });
1087*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(klass->GetDexCache(), record.GetDexCache().Get());
1088*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(klass->GetClassLoader(), record.GetClassLoader().Get());
1089*795d594fSAndroid Build Coastguard Worker     DCHECK(!record.IsProcessedClass(klass));
1090*795d594fSAndroid Build Coastguard Worker     record.MarkProcessedClass(klass);
1091*795d594fSAndroid Build Coastguard Worker     for (ArtMethod& method : klass->GetDeclaredMethods(pointer_size)) {
1092*795d594fSAndroid Build Coastguard Worker       if (method.GetCodeItem() == nullptr) {
1093*795d594fSAndroid Build Coastguard Worker         continue;  // native or abstract method
1094*795d594fSAndroid Build Coastguard Worker       }
1095*795d594fSAndroid Build Coastguard Worker       CodeItemDataAccessor accessor(method.DexInstructionData());
1096*795d594fSAndroid Build Coastguard Worker       if (accessor.TriesSize() == 0) {
1097*795d594fSAndroid Build Coastguard Worker         continue;  // nothing to process
1098*795d594fSAndroid Build Coastguard Worker       }
1099*795d594fSAndroid Build Coastguard Worker       const uint8_t* handlers_ptr = accessor.GetCatchHandlerData();
1100*795d594fSAndroid Build Coastguard Worker       size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&handlers_ptr);
1101*795d594fSAndroid Build Coastguard Worker       for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1102*795d594fSAndroid Build Coastguard Worker         CatchHandlerIterator iterator(handlers_ptr);
1103*795d594fSAndroid Build Coastguard Worker         for (; iterator.HasNext(); iterator.Next()) {
1104*795d594fSAndroid Build Coastguard Worker           dex::TypeIndex exception_type_idx = iterator.GetHandlerTypeIndex();
1105*795d594fSAndroid Build Coastguard Worker           if (exception_type_idx.IsValid() &&
1106*795d594fSAndroid Build Coastguard Worker               !record.IsProcessedExceptionType(exception_type_idx)) {
1107*795d594fSAndroid Build Coastguard Worker             record.MarkProcessedExceptionType(exception_type_idx);
1108*795d594fSAndroid Build Coastguard Worker             // Add to set of types to resolve if not resolved yet.
1109*795d594fSAndroid Build Coastguard Worker             ObjPtr<mirror::Class> type = class_linker->LookupResolvedType(
1110*795d594fSAndroid Build Coastguard Worker                 exception_type_idx, record.GetDexCache().Get(), record.GetClassLoader().Get());
1111*795d594fSAndroid Build Coastguard Worker             if (type == nullptr) {
1112*795d594fSAndroid Build Coastguard Worker               exception_types_to_resolve_.push_back(
1113*795d594fSAndroid Build Coastguard Worker                   {exception_type_idx, record.GetDexCache(), record.GetClassLoader()});
1114*795d594fSAndroid Build Coastguard Worker             }
1115*795d594fSAndroid Build Coastguard Worker           }
1116*795d594fSAndroid Build Coastguard Worker         }
1117*795d594fSAndroid Build Coastguard Worker         handlers_ptr = iterator.EndDataPointer();
1118*795d594fSAndroid Build Coastguard Worker       }
1119*795d594fSAndroid Build Coastguard Worker     }
1120*795d594fSAndroid Build Coastguard Worker   }
1121*795d594fSAndroid Build Coastguard Worker   unprocessed_classes_.clear();
1122*795d594fSAndroid Build Coastguard Worker   return !exception_types_to_resolve_.empty();
1123*795d594fSAndroid Build Coastguard Worker }
1124*795d594fSAndroid Build Coastguard Worker 
CanIncludeInCurrentImage(ObjPtr<mirror::Class> klass)1125*795d594fSAndroid Build Coastguard Worker static inline bool CanIncludeInCurrentImage(ObjPtr<mirror::Class> klass)
1126*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1127*795d594fSAndroid Build Coastguard Worker   DCHECK(klass != nullptr);
1128*795d594fSAndroid Build Coastguard Worker   gc::Heap* heap = Runtime::Current()->GetHeap();
1129*795d594fSAndroid Build Coastguard Worker   if (heap->GetBootImageSpaces().empty()) {
1130*795d594fSAndroid Build Coastguard Worker     return true;  // We can include any class when compiling the primary boot image.
1131*795d594fSAndroid Build Coastguard Worker   }
1132*795d594fSAndroid Build Coastguard Worker   if (heap->ObjectIsInBootImageSpace(klass)) {
1133*795d594fSAndroid Build Coastguard Worker     return false;  // Already included in the boot image we're compiling against.
1134*795d594fSAndroid Build Coastguard Worker   }
1135*795d594fSAndroid Build Coastguard Worker   return AotClassLinker::CanReferenceInBootImageExtensionOrAppImage(klass, heap);
1136*795d594fSAndroid Build Coastguard Worker }
1137*795d594fSAndroid Build Coastguard Worker 
1138*795d594fSAndroid Build Coastguard Worker class RecordImageClassesVisitor : public ClassVisitor {
1139*795d594fSAndroid Build Coastguard Worker  public:
RecordImageClassesVisitor(HashSet<std::string> * image_classes)1140*795d594fSAndroid Build Coastguard Worker   explicit RecordImageClassesVisitor(HashSet<std::string>* image_classes)
1141*795d594fSAndroid Build Coastguard Worker       : image_classes_(image_classes) {}
1142*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass)1143*795d594fSAndroid Build Coastguard Worker   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1144*795d594fSAndroid Build Coastguard Worker     bool resolved = klass->IsResolved();
1145*795d594fSAndroid Build Coastguard Worker     DCHECK(resolved || klass->IsErroneousUnresolved());
1146*795d594fSAndroid Build Coastguard Worker     bool can_include_in_image = LIKELY(resolved) && CanIncludeInCurrentImage(klass);
1147*795d594fSAndroid Build Coastguard Worker     std::string temp;
1148*795d594fSAndroid Build Coastguard Worker     std::string_view descriptor(klass->GetDescriptor(&temp));
1149*795d594fSAndroid Build Coastguard Worker     if (can_include_in_image) {
1150*795d594fSAndroid Build Coastguard Worker       image_classes_->insert(std::string(descriptor));  // Does nothing if already present.
1151*795d594fSAndroid Build Coastguard Worker     } else {
1152*795d594fSAndroid Build Coastguard Worker       auto it = image_classes_->find(descriptor);
1153*795d594fSAndroid Build Coastguard Worker       if (it != image_classes_->end()) {
1154*795d594fSAndroid Build Coastguard Worker         VLOG(compiler) << "Removing " << (resolved ? "unsuitable" : "unresolved")
1155*795d594fSAndroid Build Coastguard Worker             << " class from image classes: " << descriptor;
1156*795d594fSAndroid Build Coastguard Worker         image_classes_->erase(it);
1157*795d594fSAndroid Build Coastguard Worker       }
1158*795d594fSAndroid Build Coastguard Worker     }
1159*795d594fSAndroid Build Coastguard Worker     return true;
1160*795d594fSAndroid Build Coastguard Worker   }
1161*795d594fSAndroid Build Coastguard Worker 
1162*795d594fSAndroid Build Coastguard Worker  private:
1163*795d594fSAndroid Build Coastguard Worker   HashSet<std::string>* const image_classes_;
1164*795d594fSAndroid Build Coastguard Worker };
1165*795d594fSAndroid Build Coastguard Worker 
1166*795d594fSAndroid Build Coastguard Worker // Verify that classes which contain intrinsics methods are in the list of image classes.
VerifyClassesContainingIntrinsicsAreImageClasses(HashSet<std::string> * image_classes)1167*795d594fSAndroid Build Coastguard Worker static void VerifyClassesContainingIntrinsicsAreImageClasses(HashSet<std::string>* image_classes) {
1168*795d594fSAndroid Build Coastguard Worker #define CHECK_INTRINSIC_OWNER_CLASS(_, __, ___, ____, _____, ClassName, ______, _______) \
1169*795d594fSAndroid Build Coastguard Worker   CHECK(image_classes->find(std::string_view(ClassName)) != image_classes->end());
1170*795d594fSAndroid Build Coastguard Worker 
1171*795d594fSAndroid Build Coastguard Worker   ART_INTRINSICS_LIST(CHECK_INTRINSIC_OWNER_CLASS)
1172*795d594fSAndroid Build Coastguard Worker #undef CHECK_INTRINSIC_OWNER_CLASS
1173*795d594fSAndroid Build Coastguard Worker }
1174*795d594fSAndroid Build Coastguard Worker 
1175*795d594fSAndroid Build Coastguard Worker // We need to put classes required by app class loaders to the boot image,
1176*795d594fSAndroid Build Coastguard Worker // otherwise we would not be able to store app class loaders in app images.
AddClassLoaderClasses(HashSet<std::string> * image_classes)1177*795d594fSAndroid Build Coastguard Worker static void AddClassLoaderClasses(/* out */ HashSet<std::string>* image_classes) {
1178*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
1179*795d594fSAndroid Build Coastguard Worker   // Well known classes have been loaded and shall be added to image classes
1180*795d594fSAndroid Build Coastguard Worker   // by the `RecordImageClassesVisitor`. However, there are fields with array
1181*795d594fSAndroid Build Coastguard Worker   // types which we need to add to the image classes explicitly.
1182*795d594fSAndroid Build Coastguard Worker   ArtField* class_loader_array_fields[] = {
1183*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders,
1184*795d594fSAndroid Build Coastguard Worker       // BaseDexClassLoader.sharedLibraryLoadersAfter has the same array type as above.
1185*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexPathList_dexElements,
1186*795d594fSAndroid Build Coastguard Worker   };
1187*795d594fSAndroid Build Coastguard Worker   for (ArtField* field : class_loader_array_fields) {
1188*795d594fSAndroid Build Coastguard Worker     const char* field_type_descriptor = field->GetTypeDescriptor();
1189*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(field_type_descriptor[0], '[');
1190*795d594fSAndroid Build Coastguard Worker     image_classes->insert(field_type_descriptor);
1191*795d594fSAndroid Build Coastguard Worker   }
1192*795d594fSAndroid Build Coastguard Worker }
1193*795d594fSAndroid Build Coastguard Worker 
VerifyClassLoaderClassesAreImageClasses(HashSet<std::string> * image_classes)1194*795d594fSAndroid Build Coastguard Worker static void VerifyClassLoaderClassesAreImageClasses(/* out */ HashSet<std::string>* image_classes) {
1195*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
1196*795d594fSAndroid Build Coastguard Worker   ScopedAssertNoThreadSuspension sants(__FUNCTION__);
1197*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> class_loader_classes[] = {
1198*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_BaseDexClassLoader.Get(),
1199*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DelegateLastClassLoader.Get(),
1200*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexClassLoader.Get(),
1201*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexFile.Get(),
1202*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexPathList.Get(),
1203*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexPathList__Element.Get(),
1204*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_InMemoryDexClassLoader.Get(),
1205*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_PathClassLoader.Get(),
1206*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::java_lang_BootClassLoader.Get(),
1207*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::java_lang_ClassLoader.Get(),
1208*795d594fSAndroid Build Coastguard Worker   };
1209*795d594fSAndroid Build Coastguard Worker   for (ObjPtr<mirror::Class> klass : class_loader_classes) {
1210*795d594fSAndroid Build Coastguard Worker     std::string temp;
1211*795d594fSAndroid Build Coastguard Worker     std::string_view descriptor = klass->GetDescriptor(&temp);
1212*795d594fSAndroid Build Coastguard Worker     CHECK(image_classes->find(descriptor) != image_classes->end());
1213*795d594fSAndroid Build Coastguard Worker   }
1214*795d594fSAndroid Build Coastguard Worker   ArtField* class_loader_fields[] = {
1215*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList,
1216*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders,
1217*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter,
1218*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexFile_cookie,
1219*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexFile_fileName,
1220*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexPathList_dexElements,
1221*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::dalvik_system_DexPathList__Element_dexFile,
1222*795d594fSAndroid Build Coastguard Worker       WellKnownClasses::java_lang_ClassLoader_parent,
1223*795d594fSAndroid Build Coastguard Worker   };
1224*795d594fSAndroid Build Coastguard Worker   for (ArtField* field : class_loader_fields) {
1225*795d594fSAndroid Build Coastguard Worker     std::string_view field_type_descriptor = field->GetTypeDescriptor();
1226*795d594fSAndroid Build Coastguard Worker     CHECK(image_classes->find(field_type_descriptor) != image_classes->end());
1227*795d594fSAndroid Build Coastguard Worker   }
1228*795d594fSAndroid Build Coastguard Worker }
1229*795d594fSAndroid Build Coastguard Worker 
1230*795d594fSAndroid Build Coastguard Worker // Make a list of descriptors for classes to include in the image
LoadImageClasses(TimingLogger * timings,jobject class_loader,HashSet<std::string> * image_classes)1231*795d594fSAndroid Build Coastguard Worker void CompilerDriver::LoadImageClasses(TimingLogger* timings,
1232*795d594fSAndroid Build Coastguard Worker                                       jobject class_loader,
1233*795d594fSAndroid Build Coastguard Worker                                       /*inout*/ HashSet<std::string>* image_classes) {
1234*795d594fSAndroid Build Coastguard Worker   CHECK(timings != nullptr);
1235*795d594fSAndroid Build Coastguard Worker   if (!GetCompilerOptions().IsGeneratingImage()) {
1236*795d594fSAndroid Build Coastguard Worker     return;
1237*795d594fSAndroid Build Coastguard Worker   }
1238*795d594fSAndroid Build Coastguard Worker 
1239*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("LoadImageClasses", timings);
1240*795d594fSAndroid Build Coastguard Worker 
1241*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsBootImage()) {
1242*795d594fSAndroid Build Coastguard Worker     // Image classes of intrinsics are loaded and shall be added
1243*795d594fSAndroid Build Coastguard Worker     // to image classes by the `RecordImageClassesVisitor`.
1244*795d594fSAndroid Build Coastguard Worker     // Add classes needed for storing class loaders in app images.
1245*795d594fSAndroid Build Coastguard Worker     AddClassLoaderClasses(image_classes);
1246*795d594fSAndroid Build Coastguard Worker   }
1247*795d594fSAndroid Build Coastguard Worker 
1248*795d594fSAndroid Build Coastguard Worker   // Make a first pass to load all classes explicitly listed in the profile.
1249*795d594fSAndroid Build Coastguard Worker   Thread* self = Thread::Current();
1250*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(self);
1251*795d594fSAndroid Build Coastguard Worker   StackHandleScope<2u> hs(self);
1252*795d594fSAndroid Build Coastguard Worker   Handle<mirror::ClassLoader> loader = hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1253*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1254*795d594fSAndroid Build Coastguard Worker   CHECK(image_classes != nullptr);
1255*795d594fSAndroid Build Coastguard Worker   for (auto it = image_classes->begin(), end = image_classes->end(); it != end;) {
1256*795d594fSAndroid Build Coastguard Worker     const std::string& descriptor(*it);
1257*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass =
1258*795d594fSAndroid Build Coastguard Worker         class_linker->FindClass(self, descriptor.c_str(), descriptor.length(), loader);
1259*795d594fSAndroid Build Coastguard Worker     if (klass == nullptr) {
1260*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Failed to find class " << descriptor;
1261*795d594fSAndroid Build Coastguard Worker       it = image_classes->erase(it);  // May cause some descriptors to be revisited.
1262*795d594fSAndroid Build Coastguard Worker       self->ClearException();
1263*795d594fSAndroid Build Coastguard Worker     } else {
1264*795d594fSAndroid Build Coastguard Worker       ++it;
1265*795d594fSAndroid Build Coastguard Worker     }
1266*795d594fSAndroid Build Coastguard Worker   }
1267*795d594fSAndroid Build Coastguard Worker 
1268*795d594fSAndroid Build Coastguard Worker   // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1269*795d594fSAndroid Build Coastguard Worker   // exceptions are resolved by the verifier when there is a catch block in an interested method.
1270*795d594fSAndroid Build Coastguard Worker   // Do this here so that exception classes appear to have been specified image classes.
1271*795d594fSAndroid Build Coastguard Worker   ResolveCatchBlockExceptionsClassVisitor resolve_exception_classes_visitor(self);
1272*795d594fSAndroid Build Coastguard Worker   resolve_exception_classes_visitor.FindAndResolveExceptionTypes(self, class_linker);
1273*795d594fSAndroid Build Coastguard Worker 
1274*795d594fSAndroid Build Coastguard Worker   // We walk the roots looking for classes so that we'll pick up the
1275*795d594fSAndroid Build Coastguard Worker   // above classes plus any classes they depend on such super
1276*795d594fSAndroid Build Coastguard Worker   // classes, interfaces, and the required ClassLinker roots.
1277*795d594fSAndroid Build Coastguard Worker   RecordImageClassesVisitor visitor(image_classes);
1278*795d594fSAndroid Build Coastguard Worker   class_linker->VisitClasses(&visitor);
1279*795d594fSAndroid Build Coastguard Worker 
1280*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild && GetCompilerOptions().IsBootImage()) {
1281*795d594fSAndroid Build Coastguard Worker     VerifyClassesContainingIntrinsicsAreImageClasses(image_classes);
1282*795d594fSAndroid Build Coastguard Worker     VerifyClassLoaderClassesAreImageClasses(image_classes);
1283*795d594fSAndroid Build Coastguard Worker   }
1284*795d594fSAndroid Build Coastguard Worker 
1285*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsBootImage()) {
1286*795d594fSAndroid Build Coastguard Worker     CHECK(!image_classes->empty());
1287*795d594fSAndroid Build Coastguard Worker   }
1288*795d594fSAndroid Build Coastguard Worker }
1289*795d594fSAndroid Build Coastguard Worker 
MaybeAddToImageClasses(Thread * self,ObjPtr<mirror::Class> klass,HashSet<std::string> * image_classes)1290*795d594fSAndroid Build Coastguard Worker static void MaybeAddToImageClasses(Thread* self,
1291*795d594fSAndroid Build Coastguard Worker                                    ObjPtr<mirror::Class> klass,
1292*795d594fSAndroid Build Coastguard Worker                                    HashSet<std::string>* image_classes)
1293*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1294*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(self, Thread::Current());
1295*795d594fSAndroid Build Coastguard Worker   DCHECK(klass->IsResolved());
1296*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1297*795d594fSAndroid Build Coastguard Worker   gc::Heap* heap = runtime->GetHeap();
1298*795d594fSAndroid Build Coastguard Worker   if (heap->ObjectIsInBootImageSpace(klass)) {
1299*795d594fSAndroid Build Coastguard Worker     // We're compiling a boot image extension and the class is already
1300*795d594fSAndroid Build Coastguard Worker     // in the boot image we're compiling against.
1301*795d594fSAndroid Build Coastguard Worker     return;
1302*795d594fSAndroid Build Coastguard Worker   }
1303*795d594fSAndroid Build Coastguard Worker   const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
1304*795d594fSAndroid Build Coastguard Worker   std::string temp;
1305*795d594fSAndroid Build Coastguard Worker   while (!klass->IsObjectClass()) {
1306*795d594fSAndroid Build Coastguard Worker     const char* descriptor = klass->GetDescriptor(&temp);
1307*795d594fSAndroid Build Coastguard Worker     if (image_classes->find(std::string_view(descriptor)) != image_classes->end()) {
1308*795d594fSAndroid Build Coastguard Worker       break;  // Previously inserted.
1309*795d594fSAndroid Build Coastguard Worker     }
1310*795d594fSAndroid Build Coastguard Worker     image_classes->insert(descriptor);
1311*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Adding " << descriptor << " to image classes";
1312*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1313*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> interface = klass->GetDirectInterface(i);
1314*795d594fSAndroid Build Coastguard Worker       DCHECK(interface != nullptr);
1315*795d594fSAndroid Build Coastguard Worker       MaybeAddToImageClasses(self, interface, image_classes);
1316*795d594fSAndroid Build Coastguard Worker     }
1317*795d594fSAndroid Build Coastguard Worker     for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1318*795d594fSAndroid Build Coastguard Worker       MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
1319*795d594fSAndroid Build Coastguard Worker     }
1320*795d594fSAndroid Build Coastguard Worker     if (klass->IsArrayClass()) {
1321*795d594fSAndroid Build Coastguard Worker       MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
1322*795d594fSAndroid Build Coastguard Worker     }
1323*795d594fSAndroid Build Coastguard Worker     klass = klass->GetSuperClass();
1324*795d594fSAndroid Build Coastguard Worker   }
1325*795d594fSAndroid Build Coastguard Worker }
1326*795d594fSAndroid Build Coastguard Worker 
1327*795d594fSAndroid Build Coastguard Worker // Keeps all the data for the update together. Also doubles as the reference visitor.
1328*795d594fSAndroid Build Coastguard Worker // Note: we can use object pointers because we suspend all threads.
1329*795d594fSAndroid Build Coastguard Worker class ClinitImageUpdate {
1330*795d594fSAndroid Build Coastguard Worker  public:
ClinitImageUpdate(HashSet<std::string> * image_class_descriptors,Thread * self)1331*795d594fSAndroid Build Coastguard Worker   ClinitImageUpdate(HashSet<std::string>* image_class_descriptors,
1332*795d594fSAndroid Build Coastguard Worker                     Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
1333*795d594fSAndroid Build Coastguard Worker       : hs_(self),
1334*795d594fSAndroid Build Coastguard Worker         image_class_descriptors_(image_class_descriptors),
1335*795d594fSAndroid Build Coastguard Worker         self_(self) {
1336*795d594fSAndroid Build Coastguard Worker     CHECK(image_class_descriptors != nullptr);
1337*795d594fSAndroid Build Coastguard Worker 
1338*795d594fSAndroid Build Coastguard Worker     // Make sure nobody interferes with us.
1339*795d594fSAndroid Build Coastguard Worker     old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1340*795d594fSAndroid Build Coastguard Worker   }
1341*795d594fSAndroid Build Coastguard Worker 
~ClinitImageUpdate()1342*795d594fSAndroid Build Coastguard Worker   ~ClinitImageUpdate() {
1343*795d594fSAndroid Build Coastguard Worker     // Allow others to suspend again.
1344*795d594fSAndroid Build Coastguard Worker     self_->EndAssertNoThreadSuspension(old_cause_);
1345*795d594fSAndroid Build Coastguard Worker   }
1346*795d594fSAndroid Build Coastguard Worker 
1347*795d594fSAndroid Build Coastguard Worker   // Visitor for VisitReferences.
operator ()(ObjPtr<mirror::Object> object,MemberOffset field_offset,bool is_static) const1348*795d594fSAndroid Build Coastguard Worker   void operator()(ObjPtr<mirror::Object> object,
1349*795d594fSAndroid Build Coastguard Worker                   MemberOffset field_offset,
1350*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] bool is_static) const REQUIRES_SHARED(Locks::mutator_lock_) {
1351*795d594fSAndroid Build Coastguard Worker     mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1352*795d594fSAndroid Build Coastguard Worker     if (ref != nullptr) {
1353*795d594fSAndroid Build Coastguard Worker       VisitClinitClassesObject(ref);
1354*795d594fSAndroid Build Coastguard Worker     }
1355*795d594fSAndroid Build Coastguard Worker   }
1356*795d594fSAndroid Build Coastguard Worker 
1357*795d594fSAndroid Build Coastguard Worker   // java.lang.ref.Reference visitor for VisitReferences.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1358*795d594fSAndroid Build Coastguard Worker   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
1359*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] ObjPtr<mirror::Reference> ref) const {}
1360*795d594fSAndroid Build Coastguard Worker 
1361*795d594fSAndroid Build Coastguard Worker   // Ignore class native roots.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1362*795d594fSAndroid Build Coastguard Worker   void VisitRootIfNonNull(
1363*795d594fSAndroid Build Coastguard Worker       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1364*795d594fSAndroid Build Coastguard Worker   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
1365*795d594fSAndroid Build Coastguard Worker 
Walk()1366*795d594fSAndroid Build Coastguard Worker   void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
1367*795d594fSAndroid Build Coastguard Worker     // Find all the already-marked classes.
1368*795d594fSAndroid Build Coastguard Worker     WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
1369*795d594fSAndroid Build Coastguard Worker     FindImageClassesVisitor visitor(this);
1370*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
1371*795d594fSAndroid Build Coastguard Worker 
1372*795d594fSAndroid Build Coastguard Worker     // Use the initial classes as roots for a search.
1373*795d594fSAndroid Build Coastguard Worker     for (Handle<mirror::Class> klass_root : image_classes_) {
1374*795d594fSAndroid Build Coastguard Worker       VisitClinitClassesObject(klass_root.Get());
1375*795d594fSAndroid Build Coastguard Worker     }
1376*795d594fSAndroid Build Coastguard Worker     ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1377*795d594fSAndroid Build Coastguard Worker     for (Handle<mirror::Class> h_klass : to_insert_) {
1378*795d594fSAndroid Build Coastguard Worker       MaybeAddToImageClasses(self_, h_klass.Get(), image_class_descriptors_);
1379*795d594fSAndroid Build Coastguard Worker     }
1380*795d594fSAndroid Build Coastguard Worker   }
1381*795d594fSAndroid Build Coastguard Worker 
1382*795d594fSAndroid Build Coastguard Worker  private:
1383*795d594fSAndroid Build Coastguard Worker   class FindImageClassesVisitor : public ClassVisitor {
1384*795d594fSAndroid Build Coastguard Worker    public:
FindImageClassesVisitor(ClinitImageUpdate * data)1385*795d594fSAndroid Build Coastguard Worker     explicit FindImageClassesVisitor(ClinitImageUpdate* data)
1386*795d594fSAndroid Build Coastguard Worker         : data_(data) {}
1387*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass)1388*795d594fSAndroid Build Coastguard Worker     bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1389*795d594fSAndroid Build Coastguard Worker       bool resolved = klass->IsResolved();
1390*795d594fSAndroid Build Coastguard Worker       DCHECK(resolved || klass->IsErroneousUnresolved());
1391*795d594fSAndroid Build Coastguard Worker       bool can_include_in_image =
1392*795d594fSAndroid Build Coastguard Worker           LIKELY(resolved) && LIKELY(!klass->IsErroneous()) && CanIncludeInCurrentImage(klass);
1393*795d594fSAndroid Build Coastguard Worker       std::string temp;
1394*795d594fSAndroid Build Coastguard Worker       std::string_view descriptor(klass->GetDescriptor(&temp));
1395*795d594fSAndroid Build Coastguard Worker       auto it = data_->image_class_descriptors_->find(descriptor);
1396*795d594fSAndroid Build Coastguard Worker       if (it != data_->image_class_descriptors_->end()) {
1397*795d594fSAndroid Build Coastguard Worker         if (can_include_in_image) {
1398*795d594fSAndroid Build Coastguard Worker           data_->image_classes_.push_back(data_->hs_.NewHandle(klass));
1399*795d594fSAndroid Build Coastguard Worker         } else {
1400*795d594fSAndroid Build Coastguard Worker           VLOG(compiler) << "Removing " << (resolved ? "unsuitable" : "unresolved")
1401*795d594fSAndroid Build Coastguard Worker               << " class from image classes: " << descriptor;
1402*795d594fSAndroid Build Coastguard Worker           data_->image_class_descriptors_->erase(it);
1403*795d594fSAndroid Build Coastguard Worker         }
1404*795d594fSAndroid Build Coastguard Worker       } else if (can_include_in_image) {
1405*795d594fSAndroid Build Coastguard Worker         // Check whether the class is initialized and has a clinit or static fields.
1406*795d594fSAndroid Build Coastguard Worker         // Such classes must be kept too.
1407*795d594fSAndroid Build Coastguard Worker         if (klass->IsInitialized()) {
1408*795d594fSAndroid Build Coastguard Worker           PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1409*795d594fSAndroid Build Coastguard Worker           if (klass->FindClassInitializer(pointer_size) != nullptr ||
1410*795d594fSAndroid Build Coastguard Worker               klass->NumStaticFields() != 0) {
1411*795d594fSAndroid Build Coastguard Worker             DCHECK(!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass->GetDexCache()))
1412*795d594fSAndroid Build Coastguard Worker                 << klass->PrettyDescriptor();
1413*795d594fSAndroid Build Coastguard Worker             data_->image_classes_.push_back(data_->hs_.NewHandle(klass));
1414*795d594fSAndroid Build Coastguard Worker           }
1415*795d594fSAndroid Build Coastguard Worker         }
1416*795d594fSAndroid Build Coastguard Worker       }
1417*795d594fSAndroid Build Coastguard Worker       return true;
1418*795d594fSAndroid Build Coastguard Worker     }
1419*795d594fSAndroid Build Coastguard Worker 
1420*795d594fSAndroid Build Coastguard Worker    private:
1421*795d594fSAndroid Build Coastguard Worker     ClinitImageUpdate* const data_;
1422*795d594fSAndroid Build Coastguard Worker   };
1423*795d594fSAndroid Build Coastguard Worker 
VisitClinitClassesObject(mirror::Object * object) const1424*795d594fSAndroid Build Coastguard Worker   void VisitClinitClassesObject(mirror::Object* object) const
1425*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1426*795d594fSAndroid Build Coastguard Worker     DCHECK(object != nullptr);
1427*795d594fSAndroid Build Coastguard Worker     if (marked_objects_.find(object) != marked_objects_.end()) {
1428*795d594fSAndroid Build Coastguard Worker       // Already processed.
1429*795d594fSAndroid Build Coastguard Worker       return;
1430*795d594fSAndroid Build Coastguard Worker     }
1431*795d594fSAndroid Build Coastguard Worker 
1432*795d594fSAndroid Build Coastguard Worker     // Mark it.
1433*795d594fSAndroid Build Coastguard Worker     marked_objects_.insert(object);
1434*795d594fSAndroid Build Coastguard Worker 
1435*795d594fSAndroid Build Coastguard Worker     if (object->IsClass()) {
1436*795d594fSAndroid Build Coastguard Worker       // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1437*795d594fSAndroid Build Coastguard Worker       // suspensionb is not safe to do in VisitObjects or VisitReferences.
1438*795d594fSAndroid Build Coastguard Worker       to_insert_.push_back(hs_.NewHandle(object->AsClass()));
1439*795d594fSAndroid Build Coastguard Worker     } else {
1440*795d594fSAndroid Build Coastguard Worker       // Else visit the object's class.
1441*795d594fSAndroid Build Coastguard Worker       VisitClinitClassesObject(object->GetClass());
1442*795d594fSAndroid Build Coastguard Worker     }
1443*795d594fSAndroid Build Coastguard Worker 
1444*795d594fSAndroid Build Coastguard Worker     // If it is not a DexCache, visit all references.
1445*795d594fSAndroid Build Coastguard Worker     if (!object->IsDexCache()) {
1446*795d594fSAndroid Build Coastguard Worker       object->VisitReferences(*this, *this);
1447*795d594fSAndroid Build Coastguard Worker     }
1448*795d594fSAndroid Build Coastguard Worker   }
1449*795d594fSAndroid Build Coastguard Worker 
1450*795d594fSAndroid Build Coastguard Worker   mutable VariableSizedHandleScope hs_;
1451*795d594fSAndroid Build Coastguard Worker   mutable std::vector<Handle<mirror::Class>> to_insert_;
1452*795d594fSAndroid Build Coastguard Worker   mutable HashSet<mirror::Object*> marked_objects_;
1453*795d594fSAndroid Build Coastguard Worker   HashSet<std::string>* const image_class_descriptors_;
1454*795d594fSAndroid Build Coastguard Worker   std::vector<Handle<mirror::Class>> image_classes_;
1455*795d594fSAndroid Build Coastguard Worker   Thread* const self_;
1456*795d594fSAndroid Build Coastguard Worker   const char* old_cause_;
1457*795d594fSAndroid Build Coastguard Worker 
1458*795d594fSAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1459*795d594fSAndroid Build Coastguard Worker };
1460*795d594fSAndroid Build Coastguard Worker 
UpdateImageClasses(TimingLogger * timings,HashSet<std::string> * image_classes)1461*795d594fSAndroid Build Coastguard Worker void CompilerDriver::UpdateImageClasses(TimingLogger* timings,
1462*795d594fSAndroid Build Coastguard Worker                                         /*inout*/ HashSet<std::string>* image_classes) {
1463*795d594fSAndroid Build Coastguard Worker   DCHECK(GetCompilerOptions().IsGeneratingImage());
1464*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
1465*795d594fSAndroid Build Coastguard Worker 
1466*795d594fSAndroid Build Coastguard Worker   // Suspend all threads.
1467*795d594fSAndroid Build Coastguard Worker   ScopedSuspendAll ssa(__FUNCTION__);
1468*795d594fSAndroid Build Coastguard Worker 
1469*795d594fSAndroid Build Coastguard Worker   ClinitImageUpdate update(image_classes, Thread::Current());
1470*795d594fSAndroid Build Coastguard Worker 
1471*795d594fSAndroid Build Coastguard Worker   // Do the marking.
1472*795d594fSAndroid Build Coastguard Worker   update.Walk();
1473*795d594fSAndroid Build Coastguard Worker }
1474*795d594fSAndroid Build Coastguard Worker 
ProcessedInstanceField(bool resolved)1475*795d594fSAndroid Build Coastguard Worker void CompilerDriver::ProcessedInstanceField(bool resolved) {
1476*795d594fSAndroid Build Coastguard Worker   if (!resolved) {
1477*795d594fSAndroid Build Coastguard Worker     stats_->UnresolvedInstanceField();
1478*795d594fSAndroid Build Coastguard Worker   } else {
1479*795d594fSAndroid Build Coastguard Worker     stats_->ResolvedInstanceField();
1480*795d594fSAndroid Build Coastguard Worker   }
1481*795d594fSAndroid Build Coastguard Worker }
1482*795d594fSAndroid Build Coastguard Worker 
ProcessedStaticField(bool resolved,bool local)1483*795d594fSAndroid Build Coastguard Worker void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1484*795d594fSAndroid Build Coastguard Worker   if (!resolved) {
1485*795d594fSAndroid Build Coastguard Worker     stats_->UnresolvedStaticField();
1486*795d594fSAndroid Build Coastguard Worker   } else if (local) {
1487*795d594fSAndroid Build Coastguard Worker     stats_->ResolvedLocalStaticField();
1488*795d594fSAndroid Build Coastguard Worker   } else {
1489*795d594fSAndroid Build Coastguard Worker     stats_->ResolvedStaticField();
1490*795d594fSAndroid Build Coastguard Worker   }
1491*795d594fSAndroid Build Coastguard Worker }
1492*795d594fSAndroid Build Coastguard Worker 
ComputeInstanceFieldInfo(uint32_t field_idx,const DexCompilationUnit * mUnit,bool is_put,const ScopedObjectAccess & soa)1493*795d594fSAndroid Build Coastguard Worker ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1494*795d594fSAndroid Build Coastguard Worker                                                    const DexCompilationUnit* mUnit,
1495*795d594fSAndroid Build Coastguard Worker                                                    bool is_put,
1496*795d594fSAndroid Build Coastguard Worker                                                    const ScopedObjectAccess& soa) {
1497*795d594fSAndroid Build Coastguard Worker   // Try to resolve the field and compiling method's class.
1498*795d594fSAndroid Build Coastguard Worker   ArtField* resolved_field;
1499*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> referrer_class;
1500*795d594fSAndroid Build Coastguard Worker   Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
1501*795d594fSAndroid Build Coastguard Worker   {
1502*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader = mUnit->GetClassLoader();
1503*795d594fSAndroid Build Coastguard Worker     resolved_field = ResolveField(soa, dex_cache, class_loader, field_idx, /* is_static= */ false);
1504*795d594fSAndroid Build Coastguard Worker     referrer_class = resolved_field != nullptr
1505*795d594fSAndroid Build Coastguard Worker         ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
1506*795d594fSAndroid Build Coastguard Worker   }
1507*795d594fSAndroid Build Coastguard Worker   bool can_link = false;
1508*795d594fSAndroid Build Coastguard Worker   if (resolved_field != nullptr && referrer_class != nullptr) {
1509*795d594fSAndroid Build Coastguard Worker     std::pair<bool, bool> fast_path = IsFastInstanceField(
1510*795d594fSAndroid Build Coastguard Worker         dex_cache.Get(), referrer_class, resolved_field, field_idx);
1511*795d594fSAndroid Build Coastguard Worker     can_link = is_put ? fast_path.second : fast_path.first;
1512*795d594fSAndroid Build Coastguard Worker   }
1513*795d594fSAndroid Build Coastguard Worker   ProcessedInstanceField(can_link);
1514*795d594fSAndroid Build Coastguard Worker   return can_link ? resolved_field : nullptr;
1515*795d594fSAndroid Build Coastguard Worker }
1516*795d594fSAndroid Build Coastguard Worker 
ComputeInstanceFieldInfo(uint32_t field_idx,const DexCompilationUnit * mUnit,bool is_put,MemberOffset * field_offset,bool * is_volatile)1517*795d594fSAndroid Build Coastguard Worker bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1518*795d594fSAndroid Build Coastguard Worker                                               bool is_put, MemberOffset* field_offset,
1519*795d594fSAndroid Build Coastguard Worker                                               bool* is_volatile) {
1520*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
1521*795d594fSAndroid Build Coastguard Worker   ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
1522*795d594fSAndroid Build Coastguard Worker 
1523*795d594fSAndroid Build Coastguard Worker   if (resolved_field == nullptr) {
1524*795d594fSAndroid Build Coastguard Worker     // Conservative defaults.
1525*795d594fSAndroid Build Coastguard Worker     *is_volatile = true;
1526*795d594fSAndroid Build Coastguard Worker     *field_offset = MemberOffset(static_cast<size_t>(-1));
1527*795d594fSAndroid Build Coastguard Worker     return false;
1528*795d594fSAndroid Build Coastguard Worker   } else {
1529*795d594fSAndroid Build Coastguard Worker     *is_volatile = resolved_field->IsVolatile();
1530*795d594fSAndroid Build Coastguard Worker     *field_offset = resolved_field->GetOffset();
1531*795d594fSAndroid Build Coastguard Worker     return true;
1532*795d594fSAndroid Build Coastguard Worker   }
1533*795d594fSAndroid Build Coastguard Worker }
1534*795d594fSAndroid Build Coastguard Worker 
1535*795d594fSAndroid Build Coastguard Worker class CompilationVisitor {
1536*795d594fSAndroid Build Coastguard Worker  public:
~CompilationVisitor()1537*795d594fSAndroid Build Coastguard Worker   virtual ~CompilationVisitor() {}
1538*795d594fSAndroid Build Coastguard Worker   virtual void Visit(size_t index) = 0;
1539*795d594fSAndroid Build Coastguard Worker };
1540*795d594fSAndroid Build Coastguard Worker 
1541*795d594fSAndroid Build Coastguard Worker class ParallelCompilationManager {
1542*795d594fSAndroid Build Coastguard Worker  public:
ParallelCompilationManager(ClassLinker * class_linker,jobject class_loader,CompilerDriver * compiler,const DexFile * dex_file,ThreadPool * thread_pool)1543*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager(ClassLinker* class_linker,
1544*795d594fSAndroid Build Coastguard Worker                              jobject class_loader,
1545*795d594fSAndroid Build Coastguard Worker                              CompilerDriver* compiler,
1546*795d594fSAndroid Build Coastguard Worker                              const DexFile* dex_file,
1547*795d594fSAndroid Build Coastguard Worker                              ThreadPool* thread_pool)
1548*795d594fSAndroid Build Coastguard Worker     : index_(0),
1549*795d594fSAndroid Build Coastguard Worker       class_linker_(class_linker),
1550*795d594fSAndroid Build Coastguard Worker       class_loader_(class_loader),
1551*795d594fSAndroid Build Coastguard Worker       compiler_(compiler),
1552*795d594fSAndroid Build Coastguard Worker       dex_file_(dex_file),
1553*795d594fSAndroid Build Coastguard Worker       thread_pool_(thread_pool) {}
1554*795d594fSAndroid Build Coastguard Worker 
GetClassLinker() const1555*795d594fSAndroid Build Coastguard Worker   ClassLinker* GetClassLinker() const {
1556*795d594fSAndroid Build Coastguard Worker     CHECK(class_linker_ != nullptr);
1557*795d594fSAndroid Build Coastguard Worker     return class_linker_;
1558*795d594fSAndroid Build Coastguard Worker   }
1559*795d594fSAndroid Build Coastguard Worker 
GetClassLoader() const1560*795d594fSAndroid Build Coastguard Worker   jobject GetClassLoader() const {
1561*795d594fSAndroid Build Coastguard Worker     return class_loader_;
1562*795d594fSAndroid Build Coastguard Worker   }
1563*795d594fSAndroid Build Coastguard Worker 
GetCompiler() const1564*795d594fSAndroid Build Coastguard Worker   CompilerDriver* GetCompiler() const {
1565*795d594fSAndroid Build Coastguard Worker     CHECK(compiler_ != nullptr);
1566*795d594fSAndroid Build Coastguard Worker     return compiler_;
1567*795d594fSAndroid Build Coastguard Worker   }
1568*795d594fSAndroid Build Coastguard Worker 
GetDexFile() const1569*795d594fSAndroid Build Coastguard Worker   const DexFile* GetDexFile() const {
1570*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file_ != nullptr);
1571*795d594fSAndroid Build Coastguard Worker     return dex_file_;
1572*795d594fSAndroid Build Coastguard Worker   }
1573*795d594fSAndroid Build Coastguard Worker 
ForAll(size_t begin,size_t end,CompilationVisitor * visitor,size_t work_units)1574*795d594fSAndroid Build Coastguard Worker   void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1575*795d594fSAndroid Build Coastguard Worker       REQUIRES(!*Locks::mutator_lock_) {
1576*795d594fSAndroid Build Coastguard Worker     ForAllLambda(begin, end, [visitor](size_t index) { visitor->Visit(index); }, work_units);
1577*795d594fSAndroid Build Coastguard Worker   }
1578*795d594fSAndroid Build Coastguard Worker 
1579*795d594fSAndroid Build Coastguard Worker   template <typename Fn>
ForAllLambda(size_t begin,size_t end,Fn fn,size_t work_units)1580*795d594fSAndroid Build Coastguard Worker   void ForAllLambda(size_t begin, size_t end, Fn fn, size_t work_units)
1581*795d594fSAndroid Build Coastguard Worker       REQUIRES(!*Locks::mutator_lock_) {
1582*795d594fSAndroid Build Coastguard Worker     Thread* self = Thread::Current();
1583*795d594fSAndroid Build Coastguard Worker     self->AssertNoPendingException();
1584*795d594fSAndroid Build Coastguard Worker     CHECK_GT(work_units, 0U);
1585*795d594fSAndroid Build Coastguard Worker 
1586*795d594fSAndroid Build Coastguard Worker     index_.store(begin, std::memory_order_relaxed);
1587*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < work_units; ++i) {
1588*795d594fSAndroid Build Coastguard Worker       thread_pool_->AddTask(self, new ForAllClosureLambda<Fn>(this, end, fn));
1589*795d594fSAndroid Build Coastguard Worker     }
1590*795d594fSAndroid Build Coastguard Worker     thread_pool_->StartWorkers(self);
1591*795d594fSAndroid Build Coastguard Worker 
1592*795d594fSAndroid Build Coastguard Worker     // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1593*795d594fSAndroid Build Coastguard Worker     // thread destructor's called below perform join).
1594*795d594fSAndroid Build Coastguard Worker     CHECK_NE(self->GetState(), ThreadState::kRunnable);
1595*795d594fSAndroid Build Coastguard Worker 
1596*795d594fSAndroid Build Coastguard Worker     // Wait for all the worker threads to finish.
1597*795d594fSAndroid Build Coastguard Worker     thread_pool_->Wait(self, true, false);
1598*795d594fSAndroid Build Coastguard Worker 
1599*795d594fSAndroid Build Coastguard Worker     // And stop the workers accepting jobs.
1600*795d594fSAndroid Build Coastguard Worker     thread_pool_->StopWorkers(self);
1601*795d594fSAndroid Build Coastguard Worker   }
1602*795d594fSAndroid Build Coastguard Worker 
NextIndex()1603*795d594fSAndroid Build Coastguard Worker   size_t NextIndex() {
1604*795d594fSAndroid Build Coastguard Worker     return index_.fetch_add(1, std::memory_order_seq_cst);
1605*795d594fSAndroid Build Coastguard Worker   }
1606*795d594fSAndroid Build Coastguard Worker 
1607*795d594fSAndroid Build Coastguard Worker  private:
1608*795d594fSAndroid Build Coastguard Worker   template <typename Fn>
1609*795d594fSAndroid Build Coastguard Worker   class ForAllClosureLambda : public Task {
1610*795d594fSAndroid Build Coastguard Worker    public:
ForAllClosureLambda(ParallelCompilationManager * manager,size_t end,Fn fn)1611*795d594fSAndroid Build Coastguard Worker     ForAllClosureLambda(ParallelCompilationManager* manager, size_t end, Fn fn)
1612*795d594fSAndroid Build Coastguard Worker         : manager_(manager),
1613*795d594fSAndroid Build Coastguard Worker           end_(end),
1614*795d594fSAndroid Build Coastguard Worker           fn_(fn) {}
1615*795d594fSAndroid Build Coastguard Worker 
Run(Thread * self)1616*795d594fSAndroid Build Coastguard Worker     void Run(Thread* self) override {
1617*795d594fSAndroid Build Coastguard Worker       while (true) {
1618*795d594fSAndroid Build Coastguard Worker         const size_t index = manager_->NextIndex();
1619*795d594fSAndroid Build Coastguard Worker         if (UNLIKELY(index >= end_)) {
1620*795d594fSAndroid Build Coastguard Worker           break;
1621*795d594fSAndroid Build Coastguard Worker         }
1622*795d594fSAndroid Build Coastguard Worker         fn_(index);
1623*795d594fSAndroid Build Coastguard Worker         self->AssertNoPendingException();
1624*795d594fSAndroid Build Coastguard Worker       }
1625*795d594fSAndroid Build Coastguard Worker     }
1626*795d594fSAndroid Build Coastguard Worker 
Finalize()1627*795d594fSAndroid Build Coastguard Worker     void Finalize() override {
1628*795d594fSAndroid Build Coastguard Worker       delete this;
1629*795d594fSAndroid Build Coastguard Worker     }
1630*795d594fSAndroid Build Coastguard Worker 
1631*795d594fSAndroid Build Coastguard Worker    private:
1632*795d594fSAndroid Build Coastguard Worker     ParallelCompilationManager* const manager_;
1633*795d594fSAndroid Build Coastguard Worker     const size_t end_;
1634*795d594fSAndroid Build Coastguard Worker     Fn fn_;
1635*795d594fSAndroid Build Coastguard Worker   };
1636*795d594fSAndroid Build Coastguard Worker 
1637*795d594fSAndroid Build Coastguard Worker   AtomicInteger index_;
1638*795d594fSAndroid Build Coastguard Worker   ClassLinker* const class_linker_;
1639*795d594fSAndroid Build Coastguard Worker   const jobject class_loader_;
1640*795d594fSAndroid Build Coastguard Worker   CompilerDriver* const compiler_;
1641*795d594fSAndroid Build Coastguard Worker   const DexFile* const dex_file_;
1642*795d594fSAndroid Build Coastguard Worker   ThreadPool* const thread_pool_;
1643*795d594fSAndroid Build Coastguard Worker 
1644*795d594fSAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
1645*795d594fSAndroid Build Coastguard Worker };
1646*795d594fSAndroid Build Coastguard Worker 
1647*795d594fSAndroid Build Coastguard Worker // A fast version of SkipClass above if the class pointer is available
1648*795d594fSAndroid Build Coastguard Worker // that avoids the expensive FindInClassPath search.
SkipClass(jobject class_loader,const DexFile & dex_file,ObjPtr<mirror::Class> klass)1649*795d594fSAndroid Build Coastguard Worker static bool SkipClass(jobject class_loader, const DexFile& dex_file, ObjPtr<mirror::Class> klass)
1650*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1651*795d594fSAndroid Build Coastguard Worker   DCHECK(klass != nullptr);
1652*795d594fSAndroid Build Coastguard Worker   const DexFile& original_dex_file = klass->GetDexFile();
1653*795d594fSAndroid Build Coastguard Worker   if (&dex_file != &original_dex_file) {
1654*795d594fSAndroid Build Coastguard Worker     if (class_loader == nullptr) {
1655*795d594fSAndroid Build Coastguard Worker       LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
1656*795d594fSAndroid Build Coastguard Worker                    << dex_file.GetLocation() << " previously found in "
1657*795d594fSAndroid Build Coastguard Worker                    << original_dex_file.GetLocation();
1658*795d594fSAndroid Build Coastguard Worker     }
1659*795d594fSAndroid Build Coastguard Worker     return true;
1660*795d594fSAndroid Build Coastguard Worker   }
1661*795d594fSAndroid Build Coastguard Worker   return false;
1662*795d594fSAndroid Build Coastguard Worker }
1663*795d594fSAndroid Build Coastguard Worker 
DCheckResolveException(mirror::Throwable * exception)1664*795d594fSAndroid Build Coastguard Worker static void DCheckResolveException(mirror::Throwable* exception)
1665*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1666*795d594fSAndroid Build Coastguard Worker   if (!kIsDebugBuild) {
1667*795d594fSAndroid Build Coastguard Worker     return;
1668*795d594fSAndroid Build Coastguard Worker   }
1669*795d594fSAndroid Build Coastguard Worker   std::string temp;
1670*795d594fSAndroid Build Coastguard Worker   const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1671*795d594fSAndroid Build Coastguard Worker   const char* expected_exceptions[] = {
1672*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/ClassFormatError;",
1673*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/ClassCircularityError;",
1674*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/IllegalAccessError;",
1675*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/IncompatibleClassChangeError;",
1676*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/InstantiationError;",
1677*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/LinkageError;",
1678*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/NoClassDefFoundError;",
1679*795d594fSAndroid Build Coastguard Worker       "Ljava/lang/VerifyError;",
1680*795d594fSAndroid Build Coastguard Worker   };
1681*795d594fSAndroid Build Coastguard Worker   bool found = false;
1682*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1683*795d594fSAndroid Build Coastguard Worker     if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1684*795d594fSAndroid Build Coastguard Worker       found = true;
1685*795d594fSAndroid Build Coastguard Worker     }
1686*795d594fSAndroid Build Coastguard Worker   }
1687*795d594fSAndroid Build Coastguard Worker   if (!found) {
1688*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "Unexpected exception " << exception->Dump();
1689*795d594fSAndroid Build Coastguard Worker   }
1690*795d594fSAndroid Build Coastguard Worker }
1691*795d594fSAndroid Build Coastguard Worker 
1692*795d594fSAndroid Build Coastguard Worker template <bool kApp>
1693*795d594fSAndroid Build Coastguard Worker class ResolveTypeVisitor : public CompilationVisitor {
1694*795d594fSAndroid Build Coastguard Worker  public:
ResolveTypeVisitor(const ParallelCompilationManager * manager)1695*795d594fSAndroid Build Coastguard Worker   explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1696*795d594fSAndroid Build Coastguard Worker   }
Visit(size_t index)1697*795d594fSAndroid Build Coastguard Worker   void Visit(size_t index) override REQUIRES(!Locks::mutator_lock_) {
1698*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = *manager_->GetDexFile();
1699*795d594fSAndroid Build Coastguard Worker     // For boot images we resolve all referenced types, such as arrays,
1700*795d594fSAndroid Build Coastguard Worker     // whereas for applications just those with classdefs.
1701*795d594fSAndroid Build Coastguard Worker     dex::TypeIndex type_idx = kApp ? dex_file.GetClassDef(index).class_idx_ : dex::TypeIndex(index);
1702*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = manager_->GetClassLinker();
1703*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
1704*795d594fSAndroid Build Coastguard Worker     StackHandleScope<kApp ? 4u : 2u> hs(soa.Self());
1705*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader(
1706*795d594fSAndroid Build Coastguard Worker         hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
1707*795d594fSAndroid Build Coastguard Worker     // TODO: Fix tests that require `RegisterDexFile()` and use `FindDexCache()` in all cases.
1708*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1709*795d594fSAndroid Build Coastguard Worker         kApp ? class_linker->FindDexCache(soa.Self(), dex_file)
1710*795d594fSAndroid Build Coastguard Worker              : class_linker->RegisterDexFile(dex_file, class_loader.Get()));
1711*795d594fSAndroid Build Coastguard Worker     DCHECK(dex_cache != nullptr);
1712*795d594fSAndroid Build Coastguard Worker 
1713*795d594fSAndroid Build Coastguard Worker     // Resolve the class.
1714*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass = class_linker->ResolveType(type_idx, dex_cache, class_loader);
1715*795d594fSAndroid Build Coastguard Worker     if (klass == nullptr) {
1716*795d594fSAndroid Build Coastguard Worker       mirror::Throwable* exception = soa.Self()->GetException();
1717*795d594fSAndroid Build Coastguard Worker       DCHECK(exception != nullptr);
1718*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1719*795d594fSAndroid Build Coastguard Worker       if (exception->GetClass() == WellKnownClasses::java_lang_OutOfMemoryError.Get()) {
1720*795d594fSAndroid Build Coastguard Worker         // There's little point continuing compilation if the heap is exhausted.
1721*795d594fSAndroid Build Coastguard Worker         // Trying to do so would also introduce non-deterministic compilation results.
1722*795d594fSAndroid Build Coastguard Worker         LOG(FATAL) << "Out of memory during type resolution for compilation";
1723*795d594fSAndroid Build Coastguard Worker       }
1724*795d594fSAndroid Build Coastguard Worker       DCheckResolveException(exception);
1725*795d594fSAndroid Build Coastguard Worker       soa.Self()->ClearException();
1726*795d594fSAndroid Build Coastguard Worker     } else {
1727*795d594fSAndroid Build Coastguard Worker       if (kApp && manager_->GetCompiler()->GetCompilerOptions().IsCheckLinkageConditions()) {
1728*795d594fSAndroid Build Coastguard Worker         Handle<mirror::Class> hklass = hs.NewHandle(klass);
1729*795d594fSAndroid Build Coastguard Worker         bool is_fatal = manager_->GetCompiler()->GetCompilerOptions().IsCrashOnLinkageViolation();
1730*795d594fSAndroid Build Coastguard Worker         Handle<mirror::ClassLoader> defining_class_loader = hs.NewHandle(hklass->GetClassLoader());
1731*795d594fSAndroid Build Coastguard Worker         if (defining_class_loader.Get() != class_loader.Get()) {
1732*795d594fSAndroid Build Coastguard Worker           // Redefinition via different ClassLoaders.
1733*795d594fSAndroid Build Coastguard Worker           // This OptStat stuff is to enable logging from the APK scanner.
1734*795d594fSAndroid Build Coastguard Worker           if (is_fatal)
1735*795d594fSAndroid Build Coastguard Worker             LOG(FATAL) << "OptStat#" << hklass->PrettyClassAndClassLoader() << ": 1";
1736*795d594fSAndroid Build Coastguard Worker           else
1737*795d594fSAndroid Build Coastguard Worker             LOG(ERROR)
1738*795d594fSAndroid Build Coastguard Worker                 << "LINKAGE VIOLATION: "
1739*795d594fSAndroid Build Coastguard Worker                 << hklass->PrettyClassAndClassLoader()
1740*795d594fSAndroid Build Coastguard Worker                 << " was redefined";
1741*795d594fSAndroid Build Coastguard Worker         }
1742*795d594fSAndroid Build Coastguard Worker         // Check that the current class is not a subclass of java.lang.ClassLoader.
1743*795d594fSAndroid Build Coastguard Worker         if (!hklass->IsInterface() &&
1744*795d594fSAndroid Build Coastguard Worker             hklass->IsSubClass(GetClassRoot<mirror::ClassLoader>(class_linker))) {
1745*795d594fSAndroid Build Coastguard Worker           // Subclassing of java.lang.ClassLoader.
1746*795d594fSAndroid Build Coastguard Worker           // This OptStat stuff is to enable logging from the APK scanner.
1747*795d594fSAndroid Build Coastguard Worker           if (is_fatal) {
1748*795d594fSAndroid Build Coastguard Worker             LOG(FATAL) << "OptStat#" << hklass->PrettyClassAndClassLoader() << ": 1";
1749*795d594fSAndroid Build Coastguard Worker           } else {
1750*795d594fSAndroid Build Coastguard Worker             LOG(ERROR)
1751*795d594fSAndroid Build Coastguard Worker                 << "LINKAGE VIOLATION: "
1752*795d594fSAndroid Build Coastguard Worker                 << hklass->PrettyClassAndClassLoader()
1753*795d594fSAndroid Build Coastguard Worker                 << " is a subclass of java.lang.ClassLoader";
1754*795d594fSAndroid Build Coastguard Worker           }
1755*795d594fSAndroid Build Coastguard Worker         }
1756*795d594fSAndroid Build Coastguard Worker         CHECK(hklass->IsResolved()) << hklass->PrettyClass();
1757*795d594fSAndroid Build Coastguard Worker       }
1758*795d594fSAndroid Build Coastguard Worker     }
1759*795d594fSAndroid Build Coastguard Worker   }
1760*795d594fSAndroid Build Coastguard Worker 
1761*795d594fSAndroid Build Coastguard Worker  private:
1762*795d594fSAndroid Build Coastguard Worker   const ParallelCompilationManager* const manager_;
1763*795d594fSAndroid Build Coastguard Worker };
1764*795d594fSAndroid Build Coastguard Worker 
ResolveDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)1765*795d594fSAndroid Build Coastguard Worker void CompilerDriver::ResolveDexFile(jobject class_loader,
1766*795d594fSAndroid Build Coastguard Worker                                     const DexFile& dex_file,
1767*795d594fSAndroid Build Coastguard Worker                                     ThreadPool* thread_pool,
1768*795d594fSAndroid Build Coastguard Worker                                     size_t thread_count,
1769*795d594fSAndroid Build Coastguard Worker                                     TimingLogger* timings) {
1770*795d594fSAndroid Build Coastguard Worker   ScopedTrace trace(__FUNCTION__);
1771*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("Resolve Types", timings);
1772*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1773*795d594fSAndroid Build Coastguard Worker 
1774*795d594fSAndroid Build Coastguard Worker   // TODO: we could resolve strings here, although the string table is largely filled with class
1775*795d594fSAndroid Build Coastguard Worker   //       and method names.
1776*795d594fSAndroid Build Coastguard Worker 
1777*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1778*795d594fSAndroid Build Coastguard Worker   // For boot images we resolve all referenced types, such as arrays,
1779*795d594fSAndroid Build Coastguard Worker   // whereas for applications just those with classdefs.
1780*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
1781*795d594fSAndroid Build Coastguard Worker     ResolveTypeVisitor</*kApp=*/ false> visitor(&context);
1782*795d594fSAndroid Build Coastguard Worker     context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
1783*795d594fSAndroid Build Coastguard Worker   } else {
1784*795d594fSAndroid Build Coastguard Worker     ResolveTypeVisitor</*kApp=*/ true> visitor(&context);
1785*795d594fSAndroid Build Coastguard Worker     context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
1786*795d594fSAndroid Build Coastguard Worker   }
1787*795d594fSAndroid Build Coastguard Worker }
1788*795d594fSAndroid Build Coastguard Worker 
SetVerified(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1789*795d594fSAndroid Build Coastguard Worker void CompilerDriver::SetVerified(jobject class_loader,
1790*795d594fSAndroid Build Coastguard Worker                                  const std::vector<const DexFile*>& dex_files,
1791*795d594fSAndroid Build Coastguard Worker                                  TimingLogger* timings) {
1792*795d594fSAndroid Build Coastguard Worker   // This can be run in parallel.
1793*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
1794*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file != nullptr);
1795*795d594fSAndroid Build Coastguard Worker     SetVerifiedDexFile(class_loader,
1796*795d594fSAndroid Build Coastguard Worker                        *dex_file,
1797*795d594fSAndroid Build Coastguard Worker                        parallel_thread_pool_.get(),
1798*795d594fSAndroid Build Coastguard Worker                        parallel_thread_count_,
1799*795d594fSAndroid Build Coastguard Worker                        timings);
1800*795d594fSAndroid Build Coastguard Worker   }
1801*795d594fSAndroid Build Coastguard Worker }
1802*795d594fSAndroid Build Coastguard Worker 
LoadAndUpdateStatus(const ClassAccessor & accessor,ClassStatus status,Handle<mirror::ClassLoader> class_loader,Thread * self)1803*795d594fSAndroid Build Coastguard Worker static void LoadAndUpdateStatus(const ClassAccessor& accessor,
1804*795d594fSAndroid Build Coastguard Worker                                 ClassStatus status,
1805*795d594fSAndroid Build Coastguard Worker                                 Handle<mirror::ClassLoader> class_loader,
1806*795d594fSAndroid Build Coastguard Worker                                 Thread* self)
1807*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1808*795d594fSAndroid Build Coastguard Worker   StackHandleScope<1> hs(self);
1809*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1810*795d594fSAndroid Build Coastguard Worker   Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1811*795d594fSAndroid Build Coastguard Worker       class_linker->FindClass(self, accessor.GetDexFile(), accessor.GetClassIdx(), class_loader)));
1812*795d594fSAndroid Build Coastguard Worker   if (cls != nullptr) {
1813*795d594fSAndroid Build Coastguard Worker     // Check that the class is resolved with the current dex file. We might get
1814*795d594fSAndroid Build Coastguard Worker     // a boot image class, or a class in a different dex file for multidex, and
1815*795d594fSAndroid Build Coastguard Worker     // we should not update the status in that case.
1816*795d594fSAndroid Build Coastguard Worker     if (&cls->GetDexFile() == &accessor.GetDexFile()) {
1817*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Updating class status of " << accessor.GetDescriptor() << " to " << status;
1818*795d594fSAndroid Build Coastguard Worker       ObjectLock<mirror::Class> lock(self, cls);
1819*795d594fSAndroid Build Coastguard Worker       mirror::Class::SetStatus(cls, status, self);
1820*795d594fSAndroid Build Coastguard Worker     }
1821*795d594fSAndroid Build Coastguard Worker   } else {
1822*795d594fSAndroid Build Coastguard Worker     DCHECK(self->IsExceptionPending());
1823*795d594fSAndroid Build Coastguard Worker     self->ClearException();
1824*795d594fSAndroid Build Coastguard Worker   }
1825*795d594fSAndroid Build Coastguard Worker }
1826*795d594fSAndroid Build Coastguard Worker 
FastVerify(jobject jclass_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1827*795d594fSAndroid Build Coastguard Worker bool CompilerDriver::FastVerify(jobject jclass_loader,
1828*795d594fSAndroid Build Coastguard Worker                                 const std::vector<const DexFile*>& dex_files,
1829*795d594fSAndroid Build Coastguard Worker                                 TimingLogger* timings) {
1830*795d594fSAndroid Build Coastguard Worker   CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
1831*795d594fSAndroid Build Coastguard Worker   verifier::VerifierDeps* verifier_deps = callbacks->GetVerifierDeps();
1832*795d594fSAndroid Build Coastguard Worker   // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1833*795d594fSAndroid Build Coastguard Worker   if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
1834*795d594fSAndroid Build Coastguard Worker     return false;
1835*795d594fSAndroid Build Coastguard Worker   }
1836*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("Fast Verify", timings);
1837*795d594fSAndroid Build Coastguard Worker 
1838*795d594fSAndroid Build Coastguard Worker   ScopedObjectAccess soa(Thread::Current());
1839*795d594fSAndroid Build Coastguard Worker   StackHandleScope<2> hs(soa.Self());
1840*795d594fSAndroid Build Coastguard Worker   Handle<mirror::ClassLoader> class_loader(
1841*795d594fSAndroid Build Coastguard Worker       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1842*795d594fSAndroid Build Coastguard Worker   std::string error_msg;
1843*795d594fSAndroid Build Coastguard Worker 
1844*795d594fSAndroid Build Coastguard Worker   verifier_deps->ValidateDependenciesAndUpdateStatus(
1845*795d594fSAndroid Build Coastguard Worker       soa.Self(),
1846*795d594fSAndroid Build Coastguard Worker       class_loader,
1847*795d594fSAndroid Build Coastguard Worker       dex_files);
1848*795d594fSAndroid Build Coastguard Worker 
1849*795d594fSAndroid Build Coastguard Worker   bool compiler_only_verifies =
1850*795d594fSAndroid Build Coastguard Worker       !GetCompilerOptions().IsAnyCompilationEnabled() &&
1851*795d594fSAndroid Build Coastguard Worker       !GetCompilerOptions().IsGeneratingImage();
1852*795d594fSAndroid Build Coastguard Worker 
1853*795d594fSAndroid Build Coastguard Worker   const bool is_generating_image = GetCompilerOptions().IsGeneratingImage();
1854*795d594fSAndroid Build Coastguard Worker 
1855*795d594fSAndroid Build Coastguard Worker   // We successfully validated the dependencies, now update class status
1856*795d594fSAndroid Build Coastguard Worker   // of verified classes. Note that the dependencies also record which classes
1857*795d594fSAndroid Build Coastguard Worker   // could not be fully verified; we could try again, but that would hurt verification
1858*795d594fSAndroid Build Coastguard Worker   // time. So instead we assume these classes still need to be verified at
1859*795d594fSAndroid Build Coastguard Worker   // runtime.
1860*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
1861*795d594fSAndroid Build Coastguard Worker     // Fetch the list of verified classes.
1862*795d594fSAndroid Build Coastguard Worker     const std::vector<bool>& verified_classes = verifier_deps->GetVerifiedClasses(*dex_file);
1863*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(verified_classes.size(), dex_file->NumClassDefs());
1864*795d594fSAndroid Build Coastguard Worker     for (ClassAccessor accessor : dex_file->GetClasses()) {
1865*795d594fSAndroid Build Coastguard Worker       ClassStatus status = verified_classes[accessor.GetClassDefIndex()]
1866*795d594fSAndroid Build Coastguard Worker           ? ClassStatus::kVerifiedNeedsAccessChecks
1867*795d594fSAndroid Build Coastguard Worker           : ClassStatus::kRetryVerificationAtRuntime;
1868*795d594fSAndroid Build Coastguard Worker       if (compiler_only_verifies) {
1869*795d594fSAndroid Build Coastguard Worker         // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1870*795d594fSAndroid Build Coastguard Worker         // the type.
1871*795d594fSAndroid Build Coastguard Worker         ClassReference ref(dex_file, accessor.GetClassDefIndex());
1872*795d594fSAndroid Build Coastguard Worker         const ClassStatus existing = ClassStatus::kNotReady;
1873*795d594fSAndroid Build Coastguard Worker         // Note: when dex files are compiled inidividually, the class may have
1874*795d594fSAndroid Build Coastguard Worker         // been verified in a previous stage. This means this insertion can
1875*795d594fSAndroid Build Coastguard Worker         // fail, but that's OK.
1876*795d594fSAndroid Build Coastguard Worker         compiled_classes_.Insert(ref, existing, status);
1877*795d594fSAndroid Build Coastguard Worker       } else {
1878*795d594fSAndroid Build Coastguard Worker         if (is_generating_image &&
1879*795d594fSAndroid Build Coastguard Worker             status == ClassStatus::kVerifiedNeedsAccessChecks &&
1880*795d594fSAndroid Build Coastguard Worker             GetCompilerOptions().IsImageClass(accessor.GetDescriptor())) {
1881*795d594fSAndroid Build Coastguard Worker           // If the class will be in the image, we can rely on the ArtMethods
1882*795d594fSAndroid Build Coastguard Worker           // telling that they need access checks.
1883*795d594fSAndroid Build Coastguard Worker           VLOG(compiler) << "Promoting "
1884*795d594fSAndroid Build Coastguard Worker                          << std::string(accessor.GetDescriptor())
1885*795d594fSAndroid Build Coastguard Worker                          << " from needs access checks to verified given it is an image class";
1886*795d594fSAndroid Build Coastguard Worker           status = ClassStatus::kVerified;
1887*795d594fSAndroid Build Coastguard Worker         }
1888*795d594fSAndroid Build Coastguard Worker         // Update the class status, so later compilation stages know they don't need to verify
1889*795d594fSAndroid Build Coastguard Worker         // the class.
1890*795d594fSAndroid Build Coastguard Worker         LoadAndUpdateStatus(accessor, status, class_loader, soa.Self());
1891*795d594fSAndroid Build Coastguard Worker       }
1892*795d594fSAndroid Build Coastguard Worker 
1893*795d594fSAndroid Build Coastguard Worker       // Vdex marks class as unverified for two reasons only:
1894*795d594fSAndroid Build Coastguard Worker       // 1. It has a hard failure, or
1895*795d594fSAndroid Build Coastguard Worker       // 2. One of its method needs lock counting.
1896*795d594fSAndroid Build Coastguard Worker       //
1897*795d594fSAndroid Build Coastguard Worker       // The optimizing compiler expects a method to not have a hard failure before
1898*795d594fSAndroid Build Coastguard Worker       // compiling it, so for simplicity just disable any compilation of methods
1899*795d594fSAndroid Build Coastguard Worker       // of these classes.
1900*795d594fSAndroid Build Coastguard Worker       if (status == ClassStatus::kRetryVerificationAtRuntime) {
1901*795d594fSAndroid Build Coastguard Worker         ClassReference ref(dex_file, accessor.GetClassDefIndex());
1902*795d594fSAndroid Build Coastguard Worker         callbacks->AddUncompilableClass(ref);
1903*795d594fSAndroid Build Coastguard Worker       }
1904*795d594fSAndroid Build Coastguard Worker     }
1905*795d594fSAndroid Build Coastguard Worker   }
1906*795d594fSAndroid Build Coastguard Worker   return true;
1907*795d594fSAndroid Build Coastguard Worker }
1908*795d594fSAndroid Build Coastguard Worker 
Verify(jobject jclass_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)1909*795d594fSAndroid Build Coastguard Worker void CompilerDriver::Verify(jobject jclass_loader,
1910*795d594fSAndroid Build Coastguard Worker                             const std::vector<const DexFile*>& dex_files,
1911*795d594fSAndroid Build Coastguard Worker                             TimingLogger* timings) {
1912*795d594fSAndroid Build Coastguard Worker   if (FastVerify(jclass_loader, dex_files, timings)) {
1913*795d594fSAndroid Build Coastguard Worker     return;
1914*795d594fSAndroid Build Coastguard Worker   }
1915*795d594fSAndroid Build Coastguard Worker 
1916*795d594fSAndroid Build Coastguard Worker   // If there is no existing `verifier_deps` (because of non-existing vdex), or
1917*795d594fSAndroid Build Coastguard Worker   // the existing `verifier_deps` is not valid anymore, create a new one. The
1918*795d594fSAndroid Build Coastguard Worker   // verifier will need it to record the new dependencies. Then dex2oat can update
1919*795d594fSAndroid Build Coastguard Worker   // the vdex file with these new dependencies.
1920*795d594fSAndroid Build Coastguard Worker   // Dex2oat creates the verifier deps.
1921*795d594fSAndroid Build Coastguard Worker   // Create the main VerifierDeps, and set it to this thread.
1922*795d594fSAndroid Build Coastguard Worker   verifier::VerifierDeps* main_verifier_deps =
1923*795d594fSAndroid Build Coastguard Worker       Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1924*795d594fSAndroid Build Coastguard Worker   // Verifier deps can be null when unit testing.
1925*795d594fSAndroid Build Coastguard Worker   if (main_verifier_deps != nullptr) {
1926*795d594fSAndroid Build Coastguard Worker     Thread::Current()->SetVerifierDeps(main_verifier_deps);
1927*795d594fSAndroid Build Coastguard Worker     // Create per-thread VerifierDeps to avoid contention on the main one.
1928*795d594fSAndroid Build Coastguard Worker     // We will merge them after verification.
1929*795d594fSAndroid Build Coastguard Worker     for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1930*795d594fSAndroid Build Coastguard Worker       worker->GetThread()->SetVerifierDeps(
1931*795d594fSAndroid Build Coastguard Worker           new verifier::VerifierDeps(GetCompilerOptions().GetDexFilesForOatFile()));
1932*795d594fSAndroid Build Coastguard Worker     }
1933*795d594fSAndroid Build Coastguard Worker   }
1934*795d594fSAndroid Build Coastguard Worker 
1935*795d594fSAndroid Build Coastguard Worker   // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
1936*795d594fSAndroid Build Coastguard Worker   bool force_determinism = GetCompilerOptions().IsForceDeterminism();
1937*795d594fSAndroid Build Coastguard Worker   ThreadPool* verify_thread_pool =
1938*795d594fSAndroid Build Coastguard Worker       force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
1939*795d594fSAndroid Build Coastguard Worker   size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
1940*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
1941*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file != nullptr);
1942*795d594fSAndroid Build Coastguard Worker     VerifyDexFile(jclass_loader,
1943*795d594fSAndroid Build Coastguard Worker                   *dex_file,
1944*795d594fSAndroid Build Coastguard Worker                   verify_thread_pool,
1945*795d594fSAndroid Build Coastguard Worker                   verify_thread_count,
1946*795d594fSAndroid Build Coastguard Worker                   timings);
1947*795d594fSAndroid Build Coastguard Worker   }
1948*795d594fSAndroid Build Coastguard Worker 
1949*795d594fSAndroid Build Coastguard Worker   if (main_verifier_deps != nullptr) {
1950*795d594fSAndroid Build Coastguard Worker     // Merge all VerifierDeps into the main one.
1951*795d594fSAndroid Build Coastguard Worker     for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1952*795d594fSAndroid Build Coastguard Worker       std::unique_ptr<verifier::VerifierDeps> thread_deps(worker->GetThread()->GetVerifierDeps());
1953*795d594fSAndroid Build Coastguard Worker       worker->GetThread()->SetVerifierDeps(nullptr);  // We just took ownership.
1954*795d594fSAndroid Build Coastguard Worker       main_verifier_deps->MergeWith(std::move(thread_deps),
1955*795d594fSAndroid Build Coastguard Worker                                     GetCompilerOptions().GetDexFilesForOatFile());
1956*795d594fSAndroid Build Coastguard Worker     }
1957*795d594fSAndroid Build Coastguard Worker     Thread::Current()->SetVerifierDeps(nullptr);
1958*795d594fSAndroid Build Coastguard Worker   }
1959*795d594fSAndroid Build Coastguard Worker }
1960*795d594fSAndroid Build Coastguard Worker 
1961*795d594fSAndroid Build Coastguard Worker class VerifyClassVisitor : public CompilationVisitor {
1962*795d594fSAndroid Build Coastguard Worker  public:
VerifyClassVisitor(const ParallelCompilationManager * manager,verifier::HardFailLogMode log_level)1963*795d594fSAndroid Build Coastguard Worker   VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
1964*795d594fSAndroid Build Coastguard Worker      : manager_(manager),
1965*795d594fSAndroid Build Coastguard Worker        log_level_(log_level),
1966*795d594fSAndroid Build Coastguard Worker        sdk_version_(Runtime::Current()->GetTargetSdkVersion()) {}
1967*795d594fSAndroid Build Coastguard Worker 
Visit(size_t class_def_index)1968*795d594fSAndroid Build Coastguard Worker   void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
1969*795d594fSAndroid Build Coastguard Worker     ScopedTrace trace(__FUNCTION__);
1970*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
1971*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = *manager_->GetDexFile();
1972*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1973*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = manager_->GetClassLinker();
1974*795d594fSAndroid Build Coastguard Worker     jobject jclass_loader = manager_->GetClassLoader();
1975*795d594fSAndroid Build Coastguard Worker     StackHandleScope<3> hs(soa.Self());
1976*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader(
1977*795d594fSAndroid Build Coastguard Worker         hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1978*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> klass = hs.NewHandle(
1979*795d594fSAndroid Build Coastguard Worker         class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
1980*795d594fSAndroid Build Coastguard Worker     ClassReference ref(manager_->GetDexFile(), class_def_index);
1981*795d594fSAndroid Build Coastguard Worker     verifier::FailureKind failure_kind;
1982*795d594fSAndroid Build Coastguard Worker     if (klass == nullptr) {
1983*795d594fSAndroid Build Coastguard Worker       CHECK(soa.Self()->IsExceptionPending());
1984*795d594fSAndroid Build Coastguard Worker       soa.Self()->ClearException();
1985*795d594fSAndroid Build Coastguard Worker 
1986*795d594fSAndroid Build Coastguard Worker       /*
1987*795d594fSAndroid Build Coastguard Worker        * At compile time, we can still structurally verify the class even if FindClass fails.
1988*795d594fSAndroid Build Coastguard Worker        * This is to ensure the class is structurally sound for compilation. An unsound class
1989*795d594fSAndroid Build Coastguard Worker        * will be rejected by the verifier and later skipped during compilation in the compiler.
1990*795d594fSAndroid Build Coastguard Worker        */
1991*795d594fSAndroid Build Coastguard Worker       Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1992*795d594fSAndroid Build Coastguard Worker           soa.Self(), dex_file)));
1993*795d594fSAndroid Build Coastguard Worker       std::string error_msg;
1994*795d594fSAndroid Build Coastguard Worker       failure_kind =
1995*795d594fSAndroid Build Coastguard Worker           verifier::ClassVerifier::VerifyClass(soa.Self(),
1996*795d594fSAndroid Build Coastguard Worker                                                soa.Self()->GetVerifierDeps(),
1997*795d594fSAndroid Build Coastguard Worker                                                &dex_file,
1998*795d594fSAndroid Build Coastguard Worker                                                klass,
1999*795d594fSAndroid Build Coastguard Worker                                                dex_cache,
2000*795d594fSAndroid Build Coastguard Worker                                                class_loader,
2001*795d594fSAndroid Build Coastguard Worker                                                class_def,
2002*795d594fSAndroid Build Coastguard Worker                                                Runtime::Current()->GetCompilerCallbacks(),
2003*795d594fSAndroid Build Coastguard Worker                                                log_level_,
2004*795d594fSAndroid Build Coastguard Worker                                                sdk_version_,
2005*795d594fSAndroid Build Coastguard Worker                                                &error_msg);
2006*795d594fSAndroid Build Coastguard Worker       switch (failure_kind) {
2007*795d594fSAndroid Build Coastguard Worker         case verifier::FailureKind::kHardFailure: {
2008*795d594fSAndroid Build Coastguard Worker           manager_->GetCompiler()->SetHadHardVerifierFailure();
2009*795d594fSAndroid Build Coastguard Worker           break;
2010*795d594fSAndroid Build Coastguard Worker         }
2011*795d594fSAndroid Build Coastguard Worker         case verifier::FailureKind::kSoftFailure: {
2012*795d594fSAndroid Build Coastguard Worker           manager_->GetCompiler()->AddSoftVerifierFailure();
2013*795d594fSAndroid Build Coastguard Worker           break;
2014*795d594fSAndroid Build Coastguard Worker         }
2015*795d594fSAndroid Build Coastguard Worker         case verifier::FailureKind::kTypeChecksFailure: {
2016*795d594fSAndroid Build Coastguard Worker           // Don't record anything, we will do the type checks from the vdex
2017*795d594fSAndroid Build Coastguard Worker           // file at runtime.
2018*795d594fSAndroid Build Coastguard Worker           break;
2019*795d594fSAndroid Build Coastguard Worker         }
2020*795d594fSAndroid Build Coastguard Worker         case verifier::FailureKind::kAccessChecksFailure: {
2021*795d594fSAndroid Build Coastguard Worker           manager_->GetCompiler()->RecordClassStatus(ref, ClassStatus::kVerifiedNeedsAccessChecks);
2022*795d594fSAndroid Build Coastguard Worker           break;
2023*795d594fSAndroid Build Coastguard Worker         }
2024*795d594fSAndroid Build Coastguard Worker         case verifier::FailureKind::kNoFailure: {
2025*795d594fSAndroid Build Coastguard Worker           manager_->GetCompiler()->RecordClassStatus(ref, ClassStatus::kVerified);
2026*795d594fSAndroid Build Coastguard Worker           break;
2027*795d594fSAndroid Build Coastguard Worker         }
2028*795d594fSAndroid Build Coastguard Worker       }
2029*795d594fSAndroid Build Coastguard Worker     } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2030*795d594fSAndroid Build Coastguard Worker       // Skip a duplicate class (as the resolved class is from another, earlier dex file).
2031*795d594fSAndroid Build Coastguard Worker       return;  // Do not update state.
2032*795d594fSAndroid Build Coastguard Worker     } else {
2033*795d594fSAndroid Build Coastguard Worker       CHECK(klass->IsResolved()) << klass->PrettyClass();
2034*795d594fSAndroid Build Coastguard Worker       failure_kind = class_linker->VerifyClass(soa.Self(),
2035*795d594fSAndroid Build Coastguard Worker                                                soa.Self()->GetVerifierDeps(),
2036*795d594fSAndroid Build Coastguard Worker                                                klass,
2037*795d594fSAndroid Build Coastguard Worker                                                log_level_);
2038*795d594fSAndroid Build Coastguard Worker 
2039*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(klass->IsErroneous(), failure_kind == verifier::FailureKind::kHardFailure);
2040*795d594fSAndroid Build Coastguard Worker       if (failure_kind == verifier::FailureKind::kHardFailure) {
2041*795d594fSAndroid Build Coastguard Worker         // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2042*795d594fSAndroid Build Coastguard Worker         CHECK(soa.Self()->IsExceptionPending());
2043*795d594fSAndroid Build Coastguard Worker         soa.Self()->ClearException();
2044*795d594fSAndroid Build Coastguard Worker         manager_->GetCompiler()->SetHadHardVerifierFailure();
2045*795d594fSAndroid Build Coastguard Worker       } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2046*795d594fSAndroid Build Coastguard Worker         manager_->GetCompiler()->AddSoftVerifierFailure();
2047*795d594fSAndroid Build Coastguard Worker       }
2048*795d594fSAndroid Build Coastguard Worker 
2049*795d594fSAndroid Build Coastguard Worker       CHECK(klass->ShouldVerifyAtRuntime() ||
2050*795d594fSAndroid Build Coastguard Worker             klass->IsVerifiedNeedsAccessChecks() ||
2051*795d594fSAndroid Build Coastguard Worker             klass->IsVerified() ||
2052*795d594fSAndroid Build Coastguard Worker             klass->IsErroneous())
2053*795d594fSAndroid Build Coastguard Worker           << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
2054*795d594fSAndroid Build Coastguard Worker 
2055*795d594fSAndroid Build Coastguard Worker       // Class has a meaningful status for the compiler now, record it.
2056*795d594fSAndroid Build Coastguard Worker       ClassStatus status = klass->GetStatus();
2057*795d594fSAndroid Build Coastguard Worker       if (status == ClassStatus::kInitialized) {
2058*795d594fSAndroid Build Coastguard Worker         // Initialized classes shall be visibly initialized when loaded from the image.
2059*795d594fSAndroid Build Coastguard Worker         status = ClassStatus::kVisiblyInitialized;
2060*795d594fSAndroid Build Coastguard Worker       }
2061*795d594fSAndroid Build Coastguard Worker       manager_->GetCompiler()->RecordClassStatus(ref, status);
2062*795d594fSAndroid Build Coastguard Worker 
2063*795d594fSAndroid Build Coastguard Worker       // It is *very* problematic if there are resolution errors in the boot classpath.
2064*795d594fSAndroid Build Coastguard Worker       //
2065*795d594fSAndroid Build Coastguard Worker       // It is also bad if classes fail verification. For example, we rely on things working
2066*795d594fSAndroid Build Coastguard Worker       // OK without verification when the decryption dialog is brought up. It is thus highly
2067*795d594fSAndroid Build Coastguard Worker       // recommended to compile the boot classpath with
2068*795d594fSAndroid Build Coastguard Worker       //   --abort-on-hard-verifier-error --abort-on-soft-verifier-error
2069*795d594fSAndroid Build Coastguard Worker       // which is the default build system configuration.
2070*795d594fSAndroid Build Coastguard Worker       if (kIsDebugBuild) {
2071*795d594fSAndroid Build Coastguard Worker         if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage() ||
2072*795d594fSAndroid Build Coastguard Worker             manager_->GetCompiler()->GetCompilerOptions().IsBootImageExtension()) {
2073*795d594fSAndroid Build Coastguard Worker           if (!klass->IsResolved() || klass->IsErroneous()) {
2074*795d594fSAndroid Build Coastguard Worker             LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
2075*795d594fSAndroid Build Coastguard Worker                        << " failed to resolve/is erroneous: state= " << klass->GetStatus();
2076*795d594fSAndroid Build Coastguard Worker             UNREACHABLE();
2077*795d594fSAndroid Build Coastguard Worker           }
2078*795d594fSAndroid Build Coastguard Worker         }
2079*795d594fSAndroid Build Coastguard Worker         if (klass->IsVerified()) {
2080*795d594fSAndroid Build Coastguard Worker           DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
2081*795d594fSAndroid Build Coastguard Worker         } else if (klass->IsVerifiedNeedsAccessChecks()) {
2082*795d594fSAndroid Build Coastguard Worker           DCHECK_EQ(failure_kind, verifier::FailureKind::kAccessChecksFailure);
2083*795d594fSAndroid Build Coastguard Worker         } else if (klass->ShouldVerifyAtRuntime()) {
2084*795d594fSAndroid Build Coastguard Worker           DCHECK_NE(failure_kind, verifier::FailureKind::kHardFailure);
2085*795d594fSAndroid Build Coastguard Worker           // This could either be due to:
2086*795d594fSAndroid Build Coastguard Worker           // - kTypeChecksFailure, or
2087*795d594fSAndroid Build Coastguard Worker           // - kSoftFailure, or
2088*795d594fSAndroid Build Coastguard Worker           // - the superclass or interfaces not being verified.
2089*795d594fSAndroid Build Coastguard Worker         } else {
2090*795d594fSAndroid Build Coastguard Worker           DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
2091*795d594fSAndroid Build Coastguard Worker         }
2092*795d594fSAndroid Build Coastguard Worker       }
2093*795d594fSAndroid Build Coastguard Worker     }
2094*795d594fSAndroid Build Coastguard Worker     verifier::VerifierDeps::MaybeRecordVerificationStatus(soa.Self()->GetVerifierDeps(),
2095*795d594fSAndroid Build Coastguard Worker                                                           dex_file,
2096*795d594fSAndroid Build Coastguard Worker                                                           class_def,
2097*795d594fSAndroid Build Coastguard Worker                                                           failure_kind);
2098*795d594fSAndroid Build Coastguard Worker     soa.Self()->AssertNoPendingException();
2099*795d594fSAndroid Build Coastguard Worker   }
2100*795d594fSAndroid Build Coastguard Worker 
2101*795d594fSAndroid Build Coastguard Worker  private:
2102*795d594fSAndroid Build Coastguard Worker   const ParallelCompilationManager* const manager_;
2103*795d594fSAndroid Build Coastguard Worker   const verifier::HardFailLogMode log_level_;
2104*795d594fSAndroid Build Coastguard Worker   const uint32_t sdk_version_;
2105*795d594fSAndroid Build Coastguard Worker };
2106*795d594fSAndroid Build Coastguard Worker 
VerifyDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)2107*795d594fSAndroid Build Coastguard Worker void CompilerDriver::VerifyDexFile(jobject class_loader,
2108*795d594fSAndroid Build Coastguard Worker                                    const DexFile& dex_file,
2109*795d594fSAndroid Build Coastguard Worker                                    ThreadPool* thread_pool,
2110*795d594fSAndroid Build Coastguard Worker                                    size_t thread_count,
2111*795d594fSAndroid Build Coastguard Worker                                    TimingLogger* timings) {
2112*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("Verify Dex File", timings);
2113*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2114*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
2115*795d594fSAndroid Build Coastguard Worker   bool abort_on_verifier_failures = GetCompilerOptions().AbortOnHardVerifierFailure()
2116*795d594fSAndroid Build Coastguard Worker                                     || GetCompilerOptions().AbortOnSoftVerifierFailure();
2117*795d594fSAndroid Build Coastguard Worker   verifier::HardFailLogMode log_level = abort_on_verifier_failures
2118*795d594fSAndroid Build Coastguard Worker                               ? verifier::HardFailLogMode::kLogInternalFatal
2119*795d594fSAndroid Build Coastguard Worker                               : verifier::HardFailLogMode::kLogWarning;
2120*795d594fSAndroid Build Coastguard Worker   VerifyClassVisitor visitor(&context, log_level);
2121*795d594fSAndroid Build Coastguard Worker   context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
2122*795d594fSAndroid Build Coastguard Worker 
2123*795d594fSAndroid Build Coastguard Worker   // Make initialized classes visibly initialized.
2124*795d594fSAndroid Build Coastguard Worker   class_linker->MakeInitializedClassesVisiblyInitialized(Thread::Current(), /*wait=*/ true);
2125*795d594fSAndroid Build Coastguard Worker }
2126*795d594fSAndroid Build Coastguard Worker 
2127*795d594fSAndroid Build Coastguard Worker class SetVerifiedClassVisitor : public CompilationVisitor {
2128*795d594fSAndroid Build Coastguard Worker  public:
SetVerifiedClassVisitor(const ParallelCompilationManager * manager)2129*795d594fSAndroid Build Coastguard Worker   explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2130*795d594fSAndroid Build Coastguard Worker 
Visit(size_t class_def_index)2131*795d594fSAndroid Build Coastguard Worker   void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
2132*795d594fSAndroid Build Coastguard Worker     ScopedTrace trace(__FUNCTION__);
2133*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
2134*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = *manager_->GetDexFile();
2135*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2136*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = manager_->GetClassLinker();
2137*795d594fSAndroid Build Coastguard Worker     jobject jclass_loader = manager_->GetClassLoader();
2138*795d594fSAndroid Build Coastguard Worker     StackHandleScope<3> hs(soa.Self());
2139*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader(
2140*795d594fSAndroid Build Coastguard Worker         hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2141*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> klass = hs.NewHandle(
2142*795d594fSAndroid Build Coastguard Worker         class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
2143*795d594fSAndroid Build Coastguard Worker     // Class might have failed resolution. Then don't set it to verified.
2144*795d594fSAndroid Build Coastguard Worker     if (klass != nullptr) {
2145*795d594fSAndroid Build Coastguard Worker       // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2146*795d594fSAndroid Build Coastguard Worker       // very wrong.
2147*795d594fSAndroid Build Coastguard Worker       if (klass->IsResolved() && !klass->IsErroneousResolved()) {
2148*795d594fSAndroid Build Coastguard Worker         if (klass->GetStatus() < ClassStatus::kVerified) {
2149*795d594fSAndroid Build Coastguard Worker           ObjectLock<mirror::Class> lock(soa.Self(), klass);
2150*795d594fSAndroid Build Coastguard Worker           // Set class status to verified.
2151*795d594fSAndroid Build Coastguard Worker           mirror::Class::SetStatus(klass, ClassStatus::kVerified, soa.Self());
2152*795d594fSAndroid Build Coastguard Worker           // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2153*795d594fSAndroid Build Coastguard Worker           // access checks.
2154*795d594fSAndroid Build Coastguard Worker           InstructionSet instruction_set =
2155*795d594fSAndroid Build Coastguard Worker               manager_->GetCompiler()->GetCompilerOptions().GetInstructionSet();
2156*795d594fSAndroid Build Coastguard Worker           klass->SetSkipAccessChecksFlagOnAllMethods(GetInstructionSetPointerSize(instruction_set));
2157*795d594fSAndroid Build Coastguard Worker         }
2158*795d594fSAndroid Build Coastguard Worker         // Record the final class status if necessary.
2159*795d594fSAndroid Build Coastguard Worker         ClassReference ref(manager_->GetDexFile(), class_def_index);
2160*795d594fSAndroid Build Coastguard Worker         manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
2161*795d594fSAndroid Build Coastguard Worker       }
2162*795d594fSAndroid Build Coastguard Worker     } else {
2163*795d594fSAndroid Build Coastguard Worker       Thread* self = soa.Self();
2164*795d594fSAndroid Build Coastguard Worker       DCHECK(self->IsExceptionPending());
2165*795d594fSAndroid Build Coastguard Worker       self->ClearException();
2166*795d594fSAndroid Build Coastguard Worker     }
2167*795d594fSAndroid Build Coastguard Worker   }
2168*795d594fSAndroid Build Coastguard Worker 
2169*795d594fSAndroid Build Coastguard Worker  private:
2170*795d594fSAndroid Build Coastguard Worker   const ParallelCompilationManager* const manager_;
2171*795d594fSAndroid Build Coastguard Worker };
2172*795d594fSAndroid Build Coastguard Worker 
SetVerifiedDexFile(jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings)2173*795d594fSAndroid Build Coastguard Worker void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2174*795d594fSAndroid Build Coastguard Worker                                         const DexFile& dex_file,
2175*795d594fSAndroid Build Coastguard Worker                                         ThreadPool* thread_pool,
2176*795d594fSAndroid Build Coastguard Worker                                         size_t thread_count,
2177*795d594fSAndroid Build Coastguard Worker                                         TimingLogger* timings) {
2178*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("Set Verified Dex File", timings);
2179*795d594fSAndroid Build Coastguard Worker   if (!compiled_classes_.HaveDexFile(&dex_file)) {
2180*795d594fSAndroid Build Coastguard Worker     compiled_classes_.AddDexFile(&dex_file);
2181*795d594fSAndroid Build Coastguard Worker   }
2182*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2183*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
2184*795d594fSAndroid Build Coastguard Worker   SetVerifiedClassVisitor visitor(&context);
2185*795d594fSAndroid Build Coastguard Worker   context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
2186*795d594fSAndroid Build Coastguard Worker }
2187*795d594fSAndroid Build Coastguard Worker 
2188*795d594fSAndroid Build Coastguard Worker class InitializeClassVisitor : public CompilationVisitor {
2189*795d594fSAndroid Build Coastguard Worker  public:
InitializeClassVisitor(const ParallelCompilationManager * manager)2190*795d594fSAndroid Build Coastguard Worker   explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2191*795d594fSAndroid Build Coastguard Worker 
Visit(size_t class_def_index)2192*795d594fSAndroid Build Coastguard Worker   void Visit(size_t class_def_index) override {
2193*795d594fSAndroid Build Coastguard Worker     ScopedTrace trace(__FUNCTION__);
2194*795d594fSAndroid Build Coastguard Worker     jobject jclass_loader = manager_->GetClassLoader();
2195*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = *manager_->GetDexFile();
2196*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2197*795d594fSAndroid Build Coastguard Worker 
2198*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
2199*795d594fSAndroid Build Coastguard Worker     StackHandleScope<3> hs(soa.Self());
2200*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader(
2201*795d594fSAndroid Build Coastguard Worker         hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2202*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> klass = hs.NewHandle(manager_->GetClassLinker()->FindClass(
2203*795d594fSAndroid Build Coastguard Worker         soa.Self(), dex_file, class_def.class_idx_, class_loader));
2204*795d594fSAndroid Build Coastguard Worker 
2205*795d594fSAndroid Build Coastguard Worker     if (klass != nullptr) {
2206*795d594fSAndroid Build Coastguard Worker       if (!SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2207*795d594fSAndroid Build Coastguard Worker         TryInitializeClass(soa.Self(), klass, class_loader);
2208*795d594fSAndroid Build Coastguard Worker       }
2209*795d594fSAndroid Build Coastguard Worker       manager_->GetCompiler()->stats_->AddClassStatus(klass->GetStatus());
2210*795d594fSAndroid Build Coastguard Worker     }
2211*795d594fSAndroid Build Coastguard Worker     // Clear any class not found or verification exceptions.
2212*795d594fSAndroid Build Coastguard Worker     soa.Self()->ClearException();
2213*795d594fSAndroid Build Coastguard Worker   }
2214*795d594fSAndroid Build Coastguard Worker 
2215*795d594fSAndroid Build Coastguard Worker   // A helper function for initializing klass.
TryInitializeClass(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ClassLoader> & class_loader)2216*795d594fSAndroid Build Coastguard Worker   void TryInitializeClass(Thread* self,
2217*795d594fSAndroid Build Coastguard Worker                           Handle<mirror::Class> klass,
2218*795d594fSAndroid Build Coastguard Worker                           Handle<mirror::ClassLoader>& class_loader)
2219*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2220*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = klass->GetDexFile();
2221*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef* class_def = klass->GetClassDef();
2222*795d594fSAndroid Build Coastguard Worker     const dex::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2223*795d594fSAndroid Build Coastguard Worker     const char* descriptor = dex_file.GetStringData(class_type_id.descriptor_idx_);
2224*795d594fSAndroid Build Coastguard Worker     StackHandleScope<3> hs(self);
2225*795d594fSAndroid Build Coastguard Worker     AotClassLinker* const class_linker = down_cast<AotClassLinker*>(manager_->GetClassLinker());
2226*795d594fSAndroid Build Coastguard Worker     Runtime* const runtime = Runtime::Current();
2227*795d594fSAndroid Build Coastguard Worker     const CompilerOptions& compiler_options = manager_->GetCompiler()->GetCompilerOptions();
2228*795d594fSAndroid Build Coastguard Worker     const bool is_boot_image = compiler_options.IsBootImage();
2229*795d594fSAndroid Build Coastguard Worker     const bool is_boot_image_extension = compiler_options.IsBootImageExtension();
2230*795d594fSAndroid Build Coastguard Worker     const bool is_app_image = compiler_options.IsAppImage();
2231*795d594fSAndroid Build Coastguard Worker 
2232*795d594fSAndroid Build Coastguard Worker     // For boot image extension, do not initialize classes defined
2233*795d594fSAndroid Build Coastguard Worker     // in dex files belonging to the boot image we're compiling against.
2234*795d594fSAndroid Build Coastguard Worker     if (is_boot_image_extension &&
2235*795d594fSAndroid Build Coastguard Worker         runtime->GetHeap()->ObjectIsInBootImageSpace(klass->GetDexCache())) {
2236*795d594fSAndroid Build Coastguard Worker       // Also return early and don't store the class status in the recorded class status.
2237*795d594fSAndroid Build Coastguard Worker       return;
2238*795d594fSAndroid Build Coastguard Worker     }
2239*795d594fSAndroid Build Coastguard Worker     // Do not initialize classes in boot space when compiling app (with or without image).
2240*795d594fSAndroid Build Coastguard Worker     if ((!is_boot_image && !is_boot_image_extension) && klass->IsBootStrapClassLoaded()) {
2241*795d594fSAndroid Build Coastguard Worker       // Also return early and don't store the class status in the recorded class status.
2242*795d594fSAndroid Build Coastguard Worker       return;
2243*795d594fSAndroid Build Coastguard Worker     }
2244*795d594fSAndroid Build Coastguard Worker 
2245*795d594fSAndroid Build Coastguard Worker     ClassStatus old_status = klass->GetStatus();
2246*795d594fSAndroid Build Coastguard Worker     // Only try to initialize classes that were successfully verified.
2247*795d594fSAndroid Build Coastguard Worker     if (klass->IsVerified()) {
2248*795d594fSAndroid Build Coastguard Worker       // Attempt to initialize the class but bail if we either need to initialize the super-class
2249*795d594fSAndroid Build Coastguard Worker       // or static fields.
2250*795d594fSAndroid Build Coastguard Worker       class_linker->EnsureInitialized(self, klass, false, false);
2251*795d594fSAndroid Build Coastguard Worker       DCHECK(!self->IsExceptionPending());
2252*795d594fSAndroid Build Coastguard Worker       old_status = klass->GetStatus();
2253*795d594fSAndroid Build Coastguard Worker       if (!klass->IsInitialized()) {
2254*795d594fSAndroid Build Coastguard Worker         // We don't want non-trivial class initialization occurring on multiple threads due to
2255*795d594fSAndroid Build Coastguard Worker         // deadlock problems. For example, a parent class is initialized (holding its lock) that
2256*795d594fSAndroid Build Coastguard Worker         // refers to a sub-class in its static/class initializer causing it to try to acquire the
2257*795d594fSAndroid Build Coastguard Worker         // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2258*795d594fSAndroid Build Coastguard Worker         // after first initializing its parents, whose locks are acquired. This leads to a
2259*795d594fSAndroid Build Coastguard Worker         // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2260*795d594fSAndroid Build Coastguard Worker         // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2261*795d594fSAndroid Build Coastguard Worker         // than use a special Object for the purpose we use the Class of java.lang.Class.
2262*795d594fSAndroid Build Coastguard Worker         Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2263*795d594fSAndroid Build Coastguard Worker         ObjectLock<mirror::Class> lock(self, h_klass);
2264*795d594fSAndroid Build Coastguard Worker         // Attempt to initialize allowing initialization of parent classes but still not static
2265*795d594fSAndroid Build Coastguard Worker         // fields.
2266*795d594fSAndroid Build Coastguard Worker         // Initialize dependencies first only for app or boot image extension,
2267*795d594fSAndroid Build Coastguard Worker         // to make TryInitializeClass() recursive.
2268*795d594fSAndroid Build Coastguard Worker         bool try_initialize_with_superclasses =
2269*795d594fSAndroid Build Coastguard Worker             is_boot_image ? true : InitializeDependencies(klass, class_loader, self);
2270*795d594fSAndroid Build Coastguard Worker         if (try_initialize_with_superclasses) {
2271*795d594fSAndroid Build Coastguard Worker           class_linker->EnsureInitialized(self, klass, false, true);
2272*795d594fSAndroid Build Coastguard Worker           DCHECK(!self->IsExceptionPending());
2273*795d594fSAndroid Build Coastguard Worker         }
2274*795d594fSAndroid Build Coastguard Worker         // Otherwise it's in app image or boot image extension but superclasses
2275*795d594fSAndroid Build Coastguard Worker         // cannot be initialized, no need to proceed.
2276*795d594fSAndroid Build Coastguard Worker         old_status = klass->GetStatus();
2277*795d594fSAndroid Build Coastguard Worker 
2278*795d594fSAndroid Build Coastguard Worker         bool too_many_encoded_fields = (!is_boot_image && !is_boot_image_extension) &&
2279*795d594fSAndroid Build Coastguard Worker             klass->NumStaticFields() > kMaxEncodedFields;
2280*795d594fSAndroid Build Coastguard Worker 
2281*795d594fSAndroid Build Coastguard Worker         bool have_profile = (compiler_options.GetProfileCompilationInfo() != nullptr) &&
2282*795d594fSAndroid Build Coastguard Worker             !compiler_options.GetProfileCompilationInfo()->IsEmpty();
2283*795d594fSAndroid Build Coastguard Worker         // If the class was not initialized, we can proceed to see if we can initialize static
2284*795d594fSAndroid Build Coastguard Worker         // fields. Limit the max number of encoded fields.
2285*795d594fSAndroid Build Coastguard Worker         if (!klass->IsInitialized() &&
2286*795d594fSAndroid Build Coastguard Worker             (is_app_image || is_boot_image || is_boot_image_extension) &&
2287*795d594fSAndroid Build Coastguard Worker             try_initialize_with_superclasses && !too_many_encoded_fields &&
2288*795d594fSAndroid Build Coastguard Worker             compiler_options.IsImageClass(descriptor) &&
2289*795d594fSAndroid Build Coastguard Worker             // TODO(b/274077782): remove this test.
2290*795d594fSAndroid Build Coastguard Worker             (have_profile || !is_boot_image_extension)) {
2291*795d594fSAndroid Build Coastguard Worker           bool can_init_static_fields = false;
2292*795d594fSAndroid Build Coastguard Worker           if (is_boot_image || is_boot_image_extension) {
2293*795d594fSAndroid Build Coastguard Worker             // We need to initialize static fields, we only do this for image classes that aren't
2294*795d594fSAndroid Build Coastguard Worker             // marked with the $NoPreloadHolder (which implies this should not be initialized
2295*795d594fSAndroid Build Coastguard Worker             // early).
2296*795d594fSAndroid Build Coastguard Worker             can_init_static_fields = !std::string_view(descriptor).ends_with("$NoPreloadHolder;");
2297*795d594fSAndroid Build Coastguard Worker           } else {
2298*795d594fSAndroid Build Coastguard Worker             CHECK(is_app_image);
2299*795d594fSAndroid Build Coastguard Worker             // The boot image case doesn't need to recursively initialize the dependencies with
2300*795d594fSAndroid Build Coastguard Worker             // special logic since the class linker already does this.
2301*795d594fSAndroid Build Coastguard Worker             // Optimization will be disabled in debuggable build, because in debuggable mode we
2302*795d594fSAndroid Build Coastguard Worker             // want the <clinit> behavior to be observable for the debugger, so we don't do the
2303*795d594fSAndroid Build Coastguard Worker             // <clinit> at compile time.
2304*795d594fSAndroid Build Coastguard Worker             can_init_static_fields =
2305*795d594fSAndroid Build Coastguard Worker                 ClassLinker::kAppImageMayContainStrings &&
2306*795d594fSAndroid Build Coastguard Worker                 !self->IsExceptionPending() &&
2307*795d594fSAndroid Build Coastguard Worker                 !compiler_options.GetDebuggable() &&
2308*795d594fSAndroid Build Coastguard Worker                 (compiler_options.InitializeAppImageClasses() ||
2309*795d594fSAndroid Build Coastguard Worker                  NoClinitInDependency(klass, self, &class_loader));
2310*795d594fSAndroid Build Coastguard Worker             // TODO The checking for clinit can be removed since it's already
2311*795d594fSAndroid Build Coastguard Worker             // checked when init superclass. Currently keep it because it contains
2312*795d594fSAndroid Build Coastguard Worker             // processing of intern strings. Will be removed later when intern strings
2313*795d594fSAndroid Build Coastguard Worker             // and clinit are both initialized.
2314*795d594fSAndroid Build Coastguard Worker           }
2315*795d594fSAndroid Build Coastguard Worker 
2316*795d594fSAndroid Build Coastguard Worker           if (can_init_static_fields) {
2317*795d594fSAndroid Build Coastguard Worker             VLOG(compiler) << "Initializing: " << descriptor;
2318*795d594fSAndroid Build Coastguard Worker             // TODO multithreading support. We should ensure the current compilation thread has
2319*795d594fSAndroid Build Coastguard Worker             // exclusive access to the runtime and the transaction. To achieve this, we could use
2320*795d594fSAndroid Build Coastguard Worker             // a ReaderWriterMutex but we're holding the mutator lock so we fail the check of mutex
2321*795d594fSAndroid Build Coastguard Worker             // validity in Thread::AssertThreadSuspensionIsAllowable.
2322*795d594fSAndroid Build Coastguard Worker 
2323*795d594fSAndroid Build Coastguard Worker             // Resolve and initialize the exception type before enabling the transaction in case
2324*795d594fSAndroid Build Coastguard Worker             // the transaction aborts and cannot resolve the type.
2325*795d594fSAndroid Build Coastguard Worker             // TransactionAbortError is not initialized ant not in boot image, needed only by
2326*795d594fSAndroid Build Coastguard Worker             // compiler and will be pruned by ImageWriter.
2327*795d594fSAndroid Build Coastguard Worker             Handle<mirror::Class> exception_class =
2328*795d594fSAndroid Build Coastguard Worker                 hs.NewHandle(class_linker->FindSystemClass(self, kTransactionAbortErrorDescriptor));
2329*795d594fSAndroid Build Coastguard Worker             bool exception_initialized =
2330*795d594fSAndroid Build Coastguard Worker                 class_linker->EnsureInitialized(self, exception_class, true, true);
2331*795d594fSAndroid Build Coastguard Worker             DCHECK(exception_initialized);
2332*795d594fSAndroid Build Coastguard Worker 
2333*795d594fSAndroid Build Coastguard Worker             // Run the class initializer in transaction mode.
2334*795d594fSAndroid Build Coastguard Worker             class_linker->EnterTransactionMode(is_app_image, klass.Get());
2335*795d594fSAndroid Build Coastguard Worker 
2336*795d594fSAndroid Build Coastguard Worker             bool success = class_linker->EnsureInitialized(self, klass, true, true);
2337*795d594fSAndroid Build Coastguard Worker             // TODO we detach transaction from runtime to indicate we quit the transactional
2338*795d594fSAndroid Build Coastguard Worker             // mode which prevents the GC from visiting objects modified during the transaction.
2339*795d594fSAndroid Build Coastguard Worker             // Ensure GC is not run so don't access freed objects when aborting transaction.
2340*795d594fSAndroid Build Coastguard Worker 
2341*795d594fSAndroid Build Coastguard Worker             {
2342*795d594fSAndroid Build Coastguard Worker               ScopedAssertNoThreadSuspension ants("Transaction end");
2343*795d594fSAndroid Build Coastguard Worker 
2344*795d594fSAndroid Build Coastguard Worker               if (success) {
2345*795d594fSAndroid Build Coastguard Worker                 class_linker->ExitTransactionMode();
2346*795d594fSAndroid Build Coastguard Worker                 DCHECK(!runtime->IsActiveTransaction());
2347*795d594fSAndroid Build Coastguard Worker 
2348*795d594fSAndroid Build Coastguard Worker                 if (is_boot_image || is_boot_image_extension) {
2349*795d594fSAndroid Build Coastguard Worker                   // For boot image and boot image extension, we want to put the updated
2350*795d594fSAndroid Build Coastguard Worker                   // status in the oat class. This is not the case for app image as we
2351*795d594fSAndroid Build Coastguard Worker                   // want to keep the ability to load the oat file without the app image.
2352*795d594fSAndroid Build Coastguard Worker                   old_status = klass->GetStatus();
2353*795d594fSAndroid Build Coastguard Worker                 }
2354*795d594fSAndroid Build Coastguard Worker               } else {
2355*795d594fSAndroid Build Coastguard Worker                 CHECK(self->IsExceptionPending());
2356*795d594fSAndroid Build Coastguard Worker                 mirror::Throwable* exception = self->GetException();
2357*795d594fSAndroid Build Coastguard Worker                 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2358*795d594fSAndroid Build Coastguard Worker                                << exception->Dump();
2359*795d594fSAndroid Build Coastguard Worker                 std::ostream* file_log = manager_->GetCompiler()->
2360*795d594fSAndroid Build Coastguard Worker                     GetCompilerOptions().GetInitFailureOutput();
2361*795d594fSAndroid Build Coastguard Worker                 if (file_log != nullptr) {
2362*795d594fSAndroid Build Coastguard Worker                   *file_log << descriptor << "\n";
2363*795d594fSAndroid Build Coastguard Worker                   *file_log << exception->Dump() << "\n";
2364*795d594fSAndroid Build Coastguard Worker                 }
2365*795d594fSAndroid Build Coastguard Worker                 self->ClearException();
2366*795d594fSAndroid Build Coastguard Worker                 class_linker->RollbackAllTransactions();
2367*795d594fSAndroid Build Coastguard Worker                 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
2368*795d594fSAndroid Build Coastguard Worker               }
2369*795d594fSAndroid Build Coastguard Worker             }
2370*795d594fSAndroid Build Coastguard Worker 
2371*795d594fSAndroid Build Coastguard Worker             if (!success && (is_boot_image || is_boot_image_extension)) {
2372*795d594fSAndroid Build Coastguard Worker               // On failure, still intern strings of static fields and seen in <clinit>, as these
2373*795d594fSAndroid Build Coastguard Worker               // will be created in the zygote. This is separated from the transaction code just
2374*795d594fSAndroid Build Coastguard Worker               // above as we will allocate strings, so must be allowed to suspend.
2375*795d594fSAndroid Build Coastguard Worker               // We only need to intern strings for boot image and boot image extension
2376*795d594fSAndroid Build Coastguard Worker               // because classes that failed to be initialized will not appear in app image.
2377*795d594fSAndroid Build Coastguard Worker               if (&klass->GetDexFile() == manager_->GetDexFile()) {
2378*795d594fSAndroid Build Coastguard Worker                 InternStrings(klass, class_loader);
2379*795d594fSAndroid Build Coastguard Worker               } else {
2380*795d594fSAndroid Build Coastguard Worker                 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
2381*795d594fSAndroid Build Coastguard Worker               }
2382*795d594fSAndroid Build Coastguard Worker             }
2383*795d594fSAndroid Build Coastguard Worker           }
2384*795d594fSAndroid Build Coastguard Worker         }
2385*795d594fSAndroid Build Coastguard Worker         // Clear exception in case EnsureInitialized has caused one in the code above.
2386*795d594fSAndroid Build Coastguard Worker         // It's OK to clear the exception here since the compiler is supposed to be fault
2387*795d594fSAndroid Build Coastguard Worker         // tolerant and will silently not initialize classes that have exceptions.
2388*795d594fSAndroid Build Coastguard Worker         self->ClearException();
2389*795d594fSAndroid Build Coastguard Worker 
2390*795d594fSAndroid Build Coastguard Worker         // If the class still isn't initialized, at least try some checks that initialization
2391*795d594fSAndroid Build Coastguard Worker         // would do so they can be skipped at runtime.
2392*795d594fSAndroid Build Coastguard Worker         if (!klass->IsInitialized() && class_linker->ValidateSuperClassDescriptors(klass)) {
2393*795d594fSAndroid Build Coastguard Worker           old_status = ClassStatus::kSuperclassValidated;
2394*795d594fSAndroid Build Coastguard Worker         } else {
2395*795d594fSAndroid Build Coastguard Worker           self->ClearException();
2396*795d594fSAndroid Build Coastguard Worker         }
2397*795d594fSAndroid Build Coastguard Worker         self->AssertNoPendingException();
2398*795d594fSAndroid Build Coastguard Worker       }
2399*795d594fSAndroid Build Coastguard Worker     }
2400*795d594fSAndroid Build Coastguard Worker     if (old_status == ClassStatus::kInitialized) {
2401*795d594fSAndroid Build Coastguard Worker       // Initialized classes shall be visibly initialized when loaded from the image.
2402*795d594fSAndroid Build Coastguard Worker       old_status = ClassStatus::kVisiblyInitialized;
2403*795d594fSAndroid Build Coastguard Worker     }
2404*795d594fSAndroid Build Coastguard Worker     // Record the final class status if necessary.
2405*795d594fSAndroid Build Coastguard Worker     ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2406*795d594fSAndroid Build Coastguard Worker     // Back up the status before doing initialization for static encoded fields,
2407*795d594fSAndroid Build Coastguard Worker     // because the static encoded branch wants to keep the status to uninitialized.
2408*795d594fSAndroid Build Coastguard Worker     manager_->GetCompiler()->RecordClassStatus(ref, old_status);
2409*795d594fSAndroid Build Coastguard Worker 
2410*795d594fSAndroid Build Coastguard Worker     if (kIsDebugBuild) {
2411*795d594fSAndroid Build Coastguard Worker       // Make sure the class initialization did not leave any local references.
2412*795d594fSAndroid Build Coastguard Worker       self->GetJniEnv()->AssertLocalsEmpty();
2413*795d594fSAndroid Build Coastguard Worker     }
2414*795d594fSAndroid Build Coastguard Worker 
2415*795d594fSAndroid Build Coastguard Worker     if (!klass->IsInitialized() &&
2416*795d594fSAndroid Build Coastguard Worker         (is_boot_image || is_boot_image_extension) &&
2417*795d594fSAndroid Build Coastguard Worker         !compiler_options.IsPreloadedClass(PrettyDescriptor(descriptor))) {
2418*795d594fSAndroid Build Coastguard Worker       klass->SetInBootImageAndNotInPreloadedClasses();
2419*795d594fSAndroid Build Coastguard Worker     }
2420*795d594fSAndroid Build Coastguard Worker 
2421*795d594fSAndroid Build Coastguard Worker     if (compiler_options.CompileArtTest()) {
2422*795d594fSAndroid Build Coastguard Worker       // For stress testing and unit-testing the clinit check in compiled code feature.
2423*795d594fSAndroid Build Coastguard Worker       if (kIsDebugBuild || std::string_view(descriptor).ends_with("$NoPreloadHolder;")) {
2424*795d594fSAndroid Build Coastguard Worker         klass->SetInBootImageAndNotInPreloadedClasses();
2425*795d594fSAndroid Build Coastguard Worker       }
2426*795d594fSAndroid Build Coastguard Worker     }
2427*795d594fSAndroid Build Coastguard Worker   }
2428*795d594fSAndroid Build Coastguard Worker 
2429*795d594fSAndroid Build Coastguard Worker  private:
InternStrings(Handle<mirror::Class> klass,Handle<mirror::ClassLoader> class_loader)2430*795d594fSAndroid Build Coastguard Worker   void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2431*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2432*795d594fSAndroid Build Coastguard Worker     DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage() ||
2433*795d594fSAndroid Build Coastguard Worker            manager_->GetCompiler()->GetCompilerOptions().IsBootImageExtension());
2434*795d594fSAndroid Build Coastguard Worker     DCHECK(klass->IsVerified());
2435*795d594fSAndroid Build Coastguard Worker     DCHECK(!klass->IsInitialized());
2436*795d594fSAndroid Build Coastguard Worker 
2437*795d594fSAndroid Build Coastguard Worker     StackHandleScope<1> hs(Thread::Current());
2438*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
2439*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef* class_def = klass->GetClassDef();
2440*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = manager_->GetClassLinker();
2441*795d594fSAndroid Build Coastguard Worker 
2442*795d594fSAndroid Build Coastguard Worker     // Check encoded final field values for strings and intern.
2443*795d594fSAndroid Build Coastguard Worker     annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
2444*795d594fSAndroid Build Coastguard Worker                                                                  class_loader,
2445*795d594fSAndroid Build Coastguard Worker                                                                  manager_->GetClassLinker(),
2446*795d594fSAndroid Build Coastguard Worker                                                                  *class_def);
2447*795d594fSAndroid Build Coastguard Worker     for ( ; value_it.HasNext(); value_it.Next()) {
2448*795d594fSAndroid Build Coastguard Worker       if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2449*795d594fSAndroid Build Coastguard Worker         // Resolve the string. This will intern the string.
2450*795d594fSAndroid Build Coastguard Worker         art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
2451*795d594fSAndroid Build Coastguard Worker             dex::StringIndex(value_it.GetJavaValue().i), dex_cache);
2452*795d594fSAndroid Build Coastguard Worker         CHECK(resolved != nullptr);
2453*795d594fSAndroid Build Coastguard Worker       }
2454*795d594fSAndroid Build Coastguard Worker     }
2455*795d594fSAndroid Build Coastguard Worker 
2456*795d594fSAndroid Build Coastguard Worker     // Intern strings seen in <clinit>.
2457*795d594fSAndroid Build Coastguard Worker     ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2458*795d594fSAndroid Build Coastguard Worker     if (clinit != nullptr) {
2459*795d594fSAndroid Build Coastguard Worker       for (const DexInstructionPcPair& inst : clinit->DexInstructions()) {
2460*795d594fSAndroid Build Coastguard Worker         if (inst->Opcode() == Instruction::CONST_STRING) {
2461*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::String> s = class_linker->ResolveString(
2462*795d594fSAndroid Build Coastguard Worker               dex::StringIndex(inst->VRegB_21c()), dex_cache);
2463*795d594fSAndroid Build Coastguard Worker           CHECK(s != nullptr);
2464*795d594fSAndroid Build Coastguard Worker         } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
2465*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::String> s = class_linker->ResolveString(
2466*795d594fSAndroid Build Coastguard Worker               dex::StringIndex(inst->VRegB_31c()), dex_cache);
2467*795d594fSAndroid Build Coastguard Worker           CHECK(s != nullptr);
2468*795d594fSAndroid Build Coastguard Worker         }
2469*795d594fSAndroid Build Coastguard Worker       }
2470*795d594fSAndroid Build Coastguard Worker     }
2471*795d594fSAndroid Build Coastguard Worker   }
2472*795d594fSAndroid Build Coastguard Worker 
ResolveTypesOfMethods(Thread * self,ArtMethod * m)2473*795d594fSAndroid Build Coastguard Worker   bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2474*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2475*795d594fSAndroid Build Coastguard Worker     // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2476*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
2477*795d594fSAndroid Build Coastguard Worker     if (rtn_type == nullptr) {
2478*795d594fSAndroid Build Coastguard Worker       self->ClearException();
2479*795d594fSAndroid Build Coastguard Worker       return false;
2480*795d594fSAndroid Build Coastguard Worker     }
2481*795d594fSAndroid Build Coastguard Worker     const dex::TypeList* types = m->GetParameterTypeList();
2482*795d594fSAndroid Build Coastguard Worker     if (types != nullptr) {
2483*795d594fSAndroid Build Coastguard Worker       for (uint32_t i = 0; i < types->Size(); ++i) {
2484*795d594fSAndroid Build Coastguard Worker         dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
2485*795d594fSAndroid Build Coastguard Worker         ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
2486*795d594fSAndroid Build Coastguard Worker         if (param_type == nullptr) {
2487*795d594fSAndroid Build Coastguard Worker           self->ClearException();
2488*795d594fSAndroid Build Coastguard Worker           return false;
2489*795d594fSAndroid Build Coastguard Worker         }
2490*795d594fSAndroid Build Coastguard Worker       }
2491*795d594fSAndroid Build Coastguard Worker     }
2492*795d594fSAndroid Build Coastguard Worker     return true;
2493*795d594fSAndroid Build Coastguard Worker   }
2494*795d594fSAndroid Build Coastguard Worker 
2495*795d594fSAndroid Build Coastguard Worker   // Pre resolve types mentioned in all method signatures before start a transaction
2496*795d594fSAndroid Build Coastguard Worker   // since ResolveType doesn't work in transaction mode.
PreResolveTypes(Thread * self,const Handle<mirror::Class> & klass)2497*795d594fSAndroid Build Coastguard Worker   bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2498*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2499*795d594fSAndroid Build Coastguard Worker     PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2500*795d594fSAndroid Build Coastguard Worker     for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2501*795d594fSAndroid Build Coastguard Worker       if (!ResolveTypesOfMethods(self, &m)) {
2502*795d594fSAndroid Build Coastguard Worker         return false;
2503*795d594fSAndroid Build Coastguard Worker       }
2504*795d594fSAndroid Build Coastguard Worker     }
2505*795d594fSAndroid Build Coastguard Worker     if (klass->IsInterface()) {
2506*795d594fSAndroid Build Coastguard Worker       return true;
2507*795d594fSAndroid Build Coastguard Worker     } else if (klass->HasSuperClass()) {
2508*795d594fSAndroid Build Coastguard Worker       StackHandleScope<1> hs(self);
2509*795d594fSAndroid Build Coastguard Worker       MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2510*795d594fSAndroid Build Coastguard Worker       for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2511*795d594fSAndroid Build Coastguard Worker         ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2512*795d594fSAndroid Build Coastguard Worker         ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2513*795d594fSAndroid Build Coastguard Worker         if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2514*795d594fSAndroid Build Coastguard Worker           return false;
2515*795d594fSAndroid Build Coastguard Worker         }
2516*795d594fSAndroid Build Coastguard Worker       }
2517*795d594fSAndroid Build Coastguard Worker       for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2518*795d594fSAndroid Build Coastguard Worker         super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2519*795d594fSAndroid Build Coastguard Worker         if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2520*795d594fSAndroid Build Coastguard Worker           uint32_t num_methods = super_klass->NumVirtualMethods();
2521*795d594fSAndroid Build Coastguard Worker           for (uint32_t j = 0; j < num_methods; ++j) {
2522*795d594fSAndroid Build Coastguard Worker             ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2523*795d594fSAndroid Build Coastguard Worker                 j, pointer_size);
2524*795d594fSAndroid Build Coastguard Worker             ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2525*795d594fSAndroid Build Coastguard Worker             if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2526*795d594fSAndroid Build Coastguard Worker               return false;
2527*795d594fSAndroid Build Coastguard Worker             }
2528*795d594fSAndroid Build Coastguard Worker           }
2529*795d594fSAndroid Build Coastguard Worker         }
2530*795d594fSAndroid Build Coastguard Worker       }
2531*795d594fSAndroid Build Coastguard Worker     }
2532*795d594fSAndroid Build Coastguard Worker     return true;
2533*795d594fSAndroid Build Coastguard Worker   }
2534*795d594fSAndroid Build Coastguard Worker 
2535*795d594fSAndroid Build Coastguard Worker   // Initialize the klass's dependencies recursively before initializing itself.
2536*795d594fSAndroid Build Coastguard Worker   // Checking for interfaces is also necessary since interfaces that contain
2537*795d594fSAndroid Build Coastguard Worker   // default methods must be initialized before the class.
InitializeDependencies(const Handle<mirror::Class> & klass,Handle<mirror::ClassLoader> class_loader,Thread * self)2538*795d594fSAndroid Build Coastguard Worker   bool InitializeDependencies(const Handle<mirror::Class>& klass,
2539*795d594fSAndroid Build Coastguard Worker                               Handle<mirror::ClassLoader> class_loader,
2540*795d594fSAndroid Build Coastguard Worker                               Thread* self)
2541*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2542*795d594fSAndroid Build Coastguard Worker     if (klass->HasSuperClass()) {
2543*795d594fSAndroid Build Coastguard Worker       StackHandleScope<1> hs(self);
2544*795d594fSAndroid Build Coastguard Worker       Handle<mirror::Class> super_class = hs.NewHandle(klass->GetSuperClass());
2545*795d594fSAndroid Build Coastguard Worker       if (!super_class->IsInitialized()) {
2546*795d594fSAndroid Build Coastguard Worker         this->TryInitializeClass(self, super_class, class_loader);
2547*795d594fSAndroid Build Coastguard Worker         if (!super_class->IsInitialized()) {
2548*795d594fSAndroid Build Coastguard Worker           return false;
2549*795d594fSAndroid Build Coastguard Worker         }
2550*795d594fSAndroid Build Coastguard Worker       }
2551*795d594fSAndroid Build Coastguard Worker     }
2552*795d594fSAndroid Build Coastguard Worker 
2553*795d594fSAndroid Build Coastguard Worker     if (!klass->IsInterface()) {
2554*795d594fSAndroid Build Coastguard Worker       size_t num_interfaces = klass->GetIfTableCount();
2555*795d594fSAndroid Build Coastguard Worker       for (size_t i = 0; i < num_interfaces; ++i) {
2556*795d594fSAndroid Build Coastguard Worker         StackHandleScope<1> hs(self);
2557*795d594fSAndroid Build Coastguard Worker         Handle<mirror::Class> iface = hs.NewHandle(klass->GetIfTable()->GetInterface(i));
2558*795d594fSAndroid Build Coastguard Worker         if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
2559*795d594fSAndroid Build Coastguard Worker           TryInitializeClass(self, iface, class_loader);
2560*795d594fSAndroid Build Coastguard Worker           if (!iface->IsInitialized()) {
2561*795d594fSAndroid Build Coastguard Worker             return false;
2562*795d594fSAndroid Build Coastguard Worker           }
2563*795d594fSAndroid Build Coastguard Worker         }
2564*795d594fSAndroid Build Coastguard Worker       }
2565*795d594fSAndroid Build Coastguard Worker     }
2566*795d594fSAndroid Build Coastguard Worker 
2567*795d594fSAndroid Build Coastguard Worker     return PreResolveTypes(self, klass);
2568*795d594fSAndroid Build Coastguard Worker   }
2569*795d594fSAndroid Build Coastguard Worker 
2570*795d594fSAndroid Build Coastguard Worker   // In this phase the classes containing class initializers are ignored. Make sure no
2571*795d594fSAndroid Build Coastguard Worker   // clinit appears in klass's super class chain and interfaces.
NoClinitInDependency(const Handle<mirror::Class> & klass,Thread * self,Handle<mirror::ClassLoader> * class_loader)2572*795d594fSAndroid Build Coastguard Worker   bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2573*795d594fSAndroid Build Coastguard Worker                             Thread* self,
2574*795d594fSAndroid Build Coastguard Worker                             Handle<mirror::ClassLoader>* class_loader)
2575*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2576*795d594fSAndroid Build Coastguard Worker     ArtMethod* clinit =
2577*795d594fSAndroid Build Coastguard Worker         klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2578*795d594fSAndroid Build Coastguard Worker     if (clinit != nullptr) {
2579*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2580*795d594fSAndroid Build Coastguard Worker       return false;
2581*795d594fSAndroid Build Coastguard Worker     }
2582*795d594fSAndroid Build Coastguard Worker     if (klass->HasSuperClass()) {
2583*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2584*795d594fSAndroid Build Coastguard Worker       StackHandleScope<1> hs(self);
2585*795d594fSAndroid Build Coastguard Worker       Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2586*795d594fSAndroid Build Coastguard Worker       if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2587*795d594fSAndroid Build Coastguard Worker         return false;
2588*795d594fSAndroid Build Coastguard Worker       }
2589*795d594fSAndroid Build Coastguard Worker     }
2590*795d594fSAndroid Build Coastguard Worker 
2591*795d594fSAndroid Build Coastguard Worker     uint32_t num_if = klass->NumDirectInterfaces();
2592*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < num_if; i++) {
2593*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> interface = klass->GetDirectInterface(i);
2594*795d594fSAndroid Build Coastguard Worker       DCHECK(interface != nullptr);
2595*795d594fSAndroid Build Coastguard Worker       StackHandleScope<1> hs(self);
2596*795d594fSAndroid Build Coastguard Worker       Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2597*795d594fSAndroid Build Coastguard Worker       if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2598*795d594fSAndroid Build Coastguard Worker         return false;
2599*795d594fSAndroid Build Coastguard Worker       }
2600*795d594fSAndroid Build Coastguard Worker     }
2601*795d594fSAndroid Build Coastguard Worker 
2602*795d594fSAndroid Build Coastguard Worker     return true;
2603*795d594fSAndroid Build Coastguard Worker   }
2604*795d594fSAndroid Build Coastguard Worker 
2605*795d594fSAndroid Build Coastguard Worker   const ParallelCompilationManager* const manager_;
2606*795d594fSAndroid Build Coastguard Worker };
2607*795d594fSAndroid Build Coastguard Worker 
InitializeClasses(jobject jni_class_loader,const DexFile & dex_file,TimingLogger * timings)2608*795d594fSAndroid Build Coastguard Worker void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2609*795d594fSAndroid Build Coastguard Worker                                        const DexFile& dex_file,
2610*795d594fSAndroid Build Coastguard Worker                                        TimingLogger* timings) {
2611*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
2612*795d594fSAndroid Build Coastguard Worker 
2613*795d594fSAndroid Build Coastguard Worker   // Initialization allocates objects and needs to run single-threaded to be deterministic.
2614*795d594fSAndroid Build Coastguard Worker   bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2615*795d594fSAndroid Build Coastguard Worker   ThreadPool* init_thread_pool = force_determinism
2616*795d594fSAndroid Build Coastguard Worker                                      ? single_thread_pool_.get()
2617*795d594fSAndroid Build Coastguard Worker                                      : parallel_thread_pool_.get();
2618*795d594fSAndroid Build Coastguard Worker   size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2619*795d594fSAndroid Build Coastguard Worker 
2620*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2621*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager context(
2622*795d594fSAndroid Build Coastguard Worker       class_linker, jni_class_loader, this, &dex_file, init_thread_pool);
2623*795d594fSAndroid Build Coastguard Worker 
2624*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsBootImage() ||
2625*795d594fSAndroid Build Coastguard Worker       GetCompilerOptions().IsBootImageExtension() ||
2626*795d594fSAndroid Build Coastguard Worker       GetCompilerOptions().IsAppImage()) {
2627*795d594fSAndroid Build Coastguard Worker     // Set the concurrency thread to 1 to support initialization for images since transaction
2628*795d594fSAndroid Build Coastguard Worker     // doesn't support multithreading now.
2629*795d594fSAndroid Build Coastguard Worker     // TODO: remove this when transactional mode supports multithreading.
2630*795d594fSAndroid Build Coastguard Worker     init_thread_count = 1U;
2631*795d594fSAndroid Build Coastguard Worker   }
2632*795d594fSAndroid Build Coastguard Worker   InitializeClassVisitor visitor(&context);
2633*795d594fSAndroid Build Coastguard Worker   context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
2634*795d594fSAndroid Build Coastguard Worker 
2635*795d594fSAndroid Build Coastguard Worker   // Make initialized classes visibly initialized.
2636*795d594fSAndroid Build Coastguard Worker   class_linker->MakeInitializedClassesVisiblyInitialized(Thread::Current(), /*wait=*/ true);
2637*795d594fSAndroid Build Coastguard Worker }
2638*795d594fSAndroid Build Coastguard Worker 
InitializeClasses(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)2639*795d594fSAndroid Build Coastguard Worker void CompilerDriver::InitializeClasses(jobject class_loader,
2640*795d594fSAndroid Build Coastguard Worker                                        const std::vector<const DexFile*>& dex_files,
2641*795d594fSAndroid Build Coastguard Worker                                        TimingLogger* timings) {
2642*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
2643*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file != nullptr);
2644*795d594fSAndroid Build Coastguard Worker     InitializeClasses(class_loader, *dex_file, timings);
2645*795d594fSAndroid Build Coastguard Worker   }
2646*795d594fSAndroid Build Coastguard Worker   if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
2647*795d594fSAndroid Build Coastguard Worker     // Prune garbage objects created during aborted transactions.
2648*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ true);
2649*795d594fSAndroid Build Coastguard Worker   }
2650*795d594fSAndroid Build Coastguard Worker }
2651*795d594fSAndroid Build Coastguard Worker 
2652*795d594fSAndroid Build Coastguard Worker template <typename CompileFn>
CompileDexFile(CompilerDriver * driver,jobject class_loader,const DexFile & dex_file,ThreadPool * thread_pool,size_t thread_count,TimingLogger * timings,const char * timing_name,CompileFn compile_fn)2653*795d594fSAndroid Build Coastguard Worker static void CompileDexFile(CompilerDriver* driver,
2654*795d594fSAndroid Build Coastguard Worker                            jobject class_loader,
2655*795d594fSAndroid Build Coastguard Worker                            const DexFile& dex_file,
2656*795d594fSAndroid Build Coastguard Worker                            ThreadPool* thread_pool,
2657*795d594fSAndroid Build Coastguard Worker                            size_t thread_count,
2658*795d594fSAndroid Build Coastguard Worker                            TimingLogger* timings,
2659*795d594fSAndroid Build Coastguard Worker                            const char* timing_name,
2660*795d594fSAndroid Build Coastguard Worker                            CompileFn compile_fn) {
2661*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t(timing_name, timings);
2662*795d594fSAndroid Build Coastguard Worker   ParallelCompilationManager context(Runtime::Current()->GetClassLinker(),
2663*795d594fSAndroid Build Coastguard Worker                                      class_loader,
2664*795d594fSAndroid Build Coastguard Worker                                      driver,
2665*795d594fSAndroid Build Coastguard Worker                                      &dex_file,
2666*795d594fSAndroid Build Coastguard Worker                                      thread_pool);
2667*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = driver->GetCompilerOptions();
2668*795d594fSAndroid Build Coastguard Worker   bool have_profile = (compiler_options.GetProfileCompilationInfo() != nullptr);
2669*795d594fSAndroid Build Coastguard Worker   bool use_profile = CompilerFilter::DependsOnProfile(compiler_options.GetCompilerFilter());
2670*795d594fSAndroid Build Coastguard Worker   ProfileCompilationInfo::ProfileIndexType profile_index = (have_profile && use_profile)
2671*795d594fSAndroid Build Coastguard Worker       ? compiler_options.GetProfileCompilationInfo()->FindDexFile(dex_file)
2672*795d594fSAndroid Build Coastguard Worker       : ProfileCompilationInfo::MaxProfileIndex();
2673*795d594fSAndroid Build Coastguard Worker 
2674*795d594fSAndroid Build Coastguard Worker   auto compile = [&context, &compile_fn, profile_index](size_t class_def_index) {
2675*795d594fSAndroid Build Coastguard Worker     const DexFile& dex_file = *context.GetDexFile();
2676*795d594fSAndroid Build Coastguard Worker     SCOPED_TRACE << "compile " << dex_file.GetLocation() << "@" << class_def_index;
2677*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = context.GetClassLinker();
2678*795d594fSAndroid Build Coastguard Worker     jobject jclass_loader = context.GetClassLoader();
2679*795d594fSAndroid Build Coastguard Worker     ClassReference ref(&dex_file, class_def_index);
2680*795d594fSAndroid Build Coastguard Worker     const dex::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2681*795d594fSAndroid Build Coastguard Worker     ClassAccessor accessor(dex_file, class_def_index);
2682*795d594fSAndroid Build Coastguard Worker     CompilerDriver* const driver = context.GetCompiler();
2683*795d594fSAndroid Build Coastguard Worker     // Skip compiling classes with generic verifier failures since they will still fail at runtime
2684*795d594fSAndroid Build Coastguard Worker     DCHECK(driver->GetVerificationResults() != nullptr);
2685*795d594fSAndroid Build Coastguard Worker     if (driver->GetVerificationResults()->IsClassRejected(ref)) {
2686*795d594fSAndroid Build Coastguard Worker       return;
2687*795d594fSAndroid Build Coastguard Worker     }
2688*795d594fSAndroid Build Coastguard Worker     // Use a scoped object access to perform to the quick SkipClass check.
2689*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(Thread::Current());
2690*795d594fSAndroid Build Coastguard Worker     StackHandleScope<3> hs(soa.Self());
2691*795d594fSAndroid Build Coastguard Worker     Handle<mirror::ClassLoader> class_loader(
2692*795d594fSAndroid Build Coastguard Worker         hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
2693*795d594fSAndroid Build Coastguard Worker     Handle<mirror::Class> klass = hs.NewHandle(
2694*795d594fSAndroid Build Coastguard Worker         class_linker->FindClass(soa.Self(), dex_file, class_def.class_idx_, class_loader));
2695*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache;
2696*795d594fSAndroid Build Coastguard Worker     if (klass == nullptr) {
2697*795d594fSAndroid Build Coastguard Worker       soa.Self()->AssertPendingException();
2698*795d594fSAndroid Build Coastguard Worker       soa.Self()->ClearException();
2699*795d594fSAndroid Build Coastguard Worker       dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2700*795d594fSAndroid Build Coastguard Worker     } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2701*795d594fSAndroid Build Coastguard Worker       // Skip a duplicate class (as the resolved class is from another, earlier dex file).
2702*795d594fSAndroid Build Coastguard Worker       return;  // Do not update state.
2703*795d594fSAndroid Build Coastguard Worker     } else {
2704*795d594fSAndroid Build Coastguard Worker       dex_cache = hs.NewHandle(klass->GetDexCache());
2705*795d594fSAndroid Build Coastguard Worker     }
2706*795d594fSAndroid Build Coastguard Worker 
2707*795d594fSAndroid Build Coastguard Worker     // Avoid suspension if there are no methods to compile.
2708*795d594fSAndroid Build Coastguard Worker     if (accessor.NumDirectMethods() + accessor.NumVirtualMethods() == 0) {
2709*795d594fSAndroid Build Coastguard Worker       return;
2710*795d594fSAndroid Build Coastguard Worker     }
2711*795d594fSAndroid Build Coastguard Worker 
2712*795d594fSAndroid Build Coastguard Worker     // Go to native so that we don't block GC during compilation.
2713*795d594fSAndroid Build Coastguard Worker     ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
2714*795d594fSAndroid Build Coastguard Worker 
2715*795d594fSAndroid Build Coastguard Worker     // Compile direct and virtual methods.
2716*795d594fSAndroid Build Coastguard Worker     int64_t previous_method_idx = -1;
2717*795d594fSAndroid Build Coastguard Worker     for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2718*795d594fSAndroid Build Coastguard Worker       const uint32_t method_idx = method.GetIndex();
2719*795d594fSAndroid Build Coastguard Worker       if (method_idx == previous_method_idx) {
2720*795d594fSAndroid Build Coastguard Worker         // smali can create dex files with two encoded_methods sharing the same method_idx
2721*795d594fSAndroid Build Coastguard Worker         // http://code.google.com/p/smali/issues/detail?id=119
2722*795d594fSAndroid Build Coastguard Worker         continue;
2723*795d594fSAndroid Build Coastguard Worker       }
2724*795d594fSAndroid Build Coastguard Worker       previous_method_idx = method_idx;
2725*795d594fSAndroid Build Coastguard Worker       compile_fn(soa.Self(),
2726*795d594fSAndroid Build Coastguard Worker                  driver,
2727*795d594fSAndroid Build Coastguard Worker                  method.GetCodeItem(),
2728*795d594fSAndroid Build Coastguard Worker                  method.GetAccessFlags(),
2729*795d594fSAndroid Build Coastguard Worker                  class_def_index,
2730*795d594fSAndroid Build Coastguard Worker                  method_idx,
2731*795d594fSAndroid Build Coastguard Worker                  class_loader,
2732*795d594fSAndroid Build Coastguard Worker                  dex_file,
2733*795d594fSAndroid Build Coastguard Worker                  dex_cache,
2734*795d594fSAndroid Build Coastguard Worker                  profile_index);
2735*795d594fSAndroid Build Coastguard Worker     }
2736*795d594fSAndroid Build Coastguard Worker   };
2737*795d594fSAndroid Build Coastguard Worker   context.ForAllLambda(0, dex_file.NumClassDefs(), compile, thread_count);
2738*795d594fSAndroid Build Coastguard Worker }
2739*795d594fSAndroid Build Coastguard Worker 
Compile(jobject class_loader,const std::vector<const DexFile * > & dex_files,TimingLogger * timings)2740*795d594fSAndroid Build Coastguard Worker void CompilerDriver::Compile(jobject class_loader,
2741*795d594fSAndroid Build Coastguard Worker                              const std::vector<const DexFile*>& dex_files,
2742*795d594fSAndroid Build Coastguard Worker                              TimingLogger* timings) {
2743*795d594fSAndroid Build Coastguard Worker   if (kDebugProfileGuidedCompilation) {
2744*795d594fSAndroid Build Coastguard Worker     const ProfileCompilationInfo* profile_compilation_info =
2745*795d594fSAndroid Build Coastguard Worker         GetCompilerOptions().GetProfileCompilationInfo();
2746*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "[ProfileGuidedCompilation] " <<
2747*795d594fSAndroid Build Coastguard Worker         ((profile_compilation_info == nullptr)
2748*795d594fSAndroid Build Coastguard Worker             ? "null"
2749*795d594fSAndroid Build Coastguard Worker             : profile_compilation_info->DumpInfo(dex_files));
2750*795d594fSAndroid Build Coastguard Worker   }
2751*795d594fSAndroid Build Coastguard Worker 
2752*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : dex_files) {
2753*795d594fSAndroid Build Coastguard Worker     CHECK(dex_file != nullptr);
2754*795d594fSAndroid Build Coastguard Worker     CompileDexFile(this,
2755*795d594fSAndroid Build Coastguard Worker                    class_loader,
2756*795d594fSAndroid Build Coastguard Worker                    *dex_file,
2757*795d594fSAndroid Build Coastguard Worker                    parallel_thread_pool_.get(),
2758*795d594fSAndroid Build Coastguard Worker                    parallel_thread_count_,
2759*795d594fSAndroid Build Coastguard Worker                    timings,
2760*795d594fSAndroid Build Coastguard Worker                    "Compile Dex File Quick",
2761*795d594fSAndroid Build Coastguard Worker                    CompileMethodQuick);
2762*795d594fSAndroid Build Coastguard Worker     const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2763*795d594fSAndroid Build Coastguard Worker     const size_t arena_alloc = arena_pool->GetBytesAllocated();
2764*795d594fSAndroid Build Coastguard Worker     max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
2765*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->ReclaimArenaPoolMemory();
2766*795d594fSAndroid Build Coastguard Worker   }
2767*795d594fSAndroid Build Coastguard Worker 
2768*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
2769*795d594fSAndroid Build Coastguard Worker }
2770*795d594fSAndroid Build Coastguard Worker 
AddCompiledMethod(const MethodReference & method_ref,CompiledMethod * const compiled_method)2771*795d594fSAndroid Build Coastguard Worker void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2772*795d594fSAndroid Build Coastguard Worker                                        CompiledMethod* const compiled_method) {
2773*795d594fSAndroid Build Coastguard Worker   DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2774*795d594fSAndroid Build Coastguard Worker   MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2775*795d594fSAndroid Build Coastguard Worker                                                               /*expected*/ nullptr,
2776*795d594fSAndroid Build Coastguard Worker                                                               compiled_method);
2777*795d594fSAndroid Build Coastguard Worker   CHECK(result == MethodTable::kInsertResultSuccess);
2778*795d594fSAndroid Build Coastguard Worker   DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
2779*795d594fSAndroid Build Coastguard Worker }
2780*795d594fSAndroid Build Coastguard Worker 
RemoveCompiledMethod(const MethodReference & method_ref)2781*795d594fSAndroid Build Coastguard Worker CompiledMethod* CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2782*795d594fSAndroid Build Coastguard Worker   CompiledMethod* ret = nullptr;
2783*795d594fSAndroid Build Coastguard Worker   CHECK(compiled_methods_.Remove(method_ref, &ret));
2784*795d594fSAndroid Build Coastguard Worker   return ret;
2785*795d594fSAndroid Build Coastguard Worker }
2786*795d594fSAndroid Build Coastguard Worker 
GetCompiledClass(const ClassReference & ref,ClassStatus * status) const2787*795d594fSAndroid Build Coastguard Worker bool CompilerDriver::GetCompiledClass(const ClassReference& ref, ClassStatus* status) const {
2788*795d594fSAndroid Build Coastguard Worker   DCHECK(status != nullptr);
2789*795d594fSAndroid Build Coastguard Worker   // The table doesn't know if something wasn't inserted. For this case it will return
2790*795d594fSAndroid Build Coastguard Worker   // ClassStatus::kNotReady. To handle this, just assume anything we didn't try to verify
2791*795d594fSAndroid Build Coastguard Worker   // is not compiled.
2792*795d594fSAndroid Build Coastguard Worker   if (!compiled_classes_.Get(ref, status) ||
2793*795d594fSAndroid Build Coastguard Worker       *status < ClassStatus::kRetryVerificationAtRuntime) {
2794*795d594fSAndroid Build Coastguard Worker     return false;
2795*795d594fSAndroid Build Coastguard Worker   }
2796*795d594fSAndroid Build Coastguard Worker   return true;
2797*795d594fSAndroid Build Coastguard Worker }
2798*795d594fSAndroid Build Coastguard Worker 
GetClassStatus(const ClassReference & ref) const2799*795d594fSAndroid Build Coastguard Worker ClassStatus CompilerDriver::GetClassStatus(const ClassReference& ref) const {
2800*795d594fSAndroid Build Coastguard Worker   ClassStatus status = ClassStatus::kNotReady;
2801*795d594fSAndroid Build Coastguard Worker   if (!GetCompiledClass(ref, &status)) {
2802*795d594fSAndroid Build Coastguard Worker     classpath_classes_.Get(ref, &status);
2803*795d594fSAndroid Build Coastguard Worker   }
2804*795d594fSAndroid Build Coastguard Worker   return status;
2805*795d594fSAndroid Build Coastguard Worker }
2806*795d594fSAndroid Build Coastguard Worker 
RecordClassStatus(const ClassReference & ref,ClassStatus status)2807*795d594fSAndroid Build Coastguard Worker void CompilerDriver::RecordClassStatus(const ClassReference& ref, ClassStatus status) {
2808*795d594fSAndroid Build Coastguard Worker   switch (status) {
2809*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kErrorResolved:
2810*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kErrorUnresolved:
2811*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kNotReady:
2812*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kResolved:
2813*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kRetryVerificationAtRuntime:
2814*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kVerifiedNeedsAccessChecks:
2815*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kVerified:
2816*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kSuperclassValidated:
2817*795d594fSAndroid Build Coastguard Worker     case ClassStatus::kVisiblyInitialized:
2818*795d594fSAndroid Build Coastguard Worker       break;  // Expected states.
2819*795d594fSAndroid Build Coastguard Worker     default:
2820*795d594fSAndroid Build Coastguard Worker       LOG(FATAL) << "Unexpected class status for class "
2821*795d594fSAndroid Build Coastguard Worker           << PrettyDescriptor(
2822*795d594fSAndroid Build Coastguard Worker               ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
2823*795d594fSAndroid Build Coastguard Worker           << " of " << status;
2824*795d594fSAndroid Build Coastguard Worker   }
2825*795d594fSAndroid Build Coastguard Worker 
2826*795d594fSAndroid Build Coastguard Worker   ClassStateTable::InsertResult result;
2827*795d594fSAndroid Build Coastguard Worker   ClassStateTable* table = &compiled_classes_;
2828*795d594fSAndroid Build Coastguard Worker   do {
2829*795d594fSAndroid Build Coastguard Worker     ClassStatus existing = ClassStatus::kNotReady;
2830*795d594fSAndroid Build Coastguard Worker     if (!table->Get(ref, &existing)) {
2831*795d594fSAndroid Build Coastguard Worker       // A classpath class.
2832*795d594fSAndroid Build Coastguard Worker       if (kIsDebugBuild) {
2833*795d594fSAndroid Build Coastguard Worker         // Check to make sure it's not a dex file for an oat file we are compiling since these
2834*795d594fSAndroid Build Coastguard Worker         // should always succeed. These do not include classes in for used libraries.
2835*795d594fSAndroid Build Coastguard Worker         for (const DexFile* dex_file : GetCompilerOptions().GetDexFilesForOatFile()) {
2836*795d594fSAndroid Build Coastguard Worker           CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
2837*795d594fSAndroid Build Coastguard Worker         }
2838*795d594fSAndroid Build Coastguard Worker       }
2839*795d594fSAndroid Build Coastguard Worker       if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
2840*795d594fSAndroid Build Coastguard Worker         // Boot classpath dex file.
2841*795d594fSAndroid Build Coastguard Worker         return;
2842*795d594fSAndroid Build Coastguard Worker       }
2843*795d594fSAndroid Build Coastguard Worker       table = &classpath_classes_;
2844*795d594fSAndroid Build Coastguard Worker       table->Get(ref, &existing);
2845*795d594fSAndroid Build Coastguard Worker     }
2846*795d594fSAndroid Build Coastguard Worker     if (existing >= status) {
2847*795d594fSAndroid Build Coastguard Worker       // Existing status is already better than we expect, break.
2848*795d594fSAndroid Build Coastguard Worker       break;
2849*795d594fSAndroid Build Coastguard Worker     }
2850*795d594fSAndroid Build Coastguard Worker     // Update the status if we now have a greater one. This happens with vdex,
2851*795d594fSAndroid Build Coastguard Worker     // which records a class is verified, but does not resolve it.
2852*795d594fSAndroid Build Coastguard Worker     result = table->Insert(ref, existing, status);
2853*795d594fSAndroid Build Coastguard Worker     CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
2854*795d594fSAndroid Build Coastguard Worker   } while (result != ClassStateTable::kInsertResultSuccess);
2855*795d594fSAndroid Build Coastguard Worker }
2856*795d594fSAndroid Build Coastguard Worker 
GetCompiledMethod(MethodReference ref) const2857*795d594fSAndroid Build Coastguard Worker CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2858*795d594fSAndroid Build Coastguard Worker   CompiledMethod* compiled_method = nullptr;
2859*795d594fSAndroid Build Coastguard Worker   compiled_methods_.Get(ref, &compiled_method);
2860*795d594fSAndroid Build Coastguard Worker   return compiled_method;
2861*795d594fSAndroid Build Coastguard Worker }
2862*795d594fSAndroid Build Coastguard Worker 
GetMemoryUsageString(bool extended) const2863*795d594fSAndroid Build Coastguard Worker std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
2864*795d594fSAndroid Build Coastguard Worker   std::ostringstream oss;
2865*795d594fSAndroid Build Coastguard Worker   const gc::Heap* const heap = Runtime::Current()->GetHeap();
2866*795d594fSAndroid Build Coastguard Worker   const size_t java_alloc = heap->GetBytesAllocated();
2867*795d594fSAndroid Build Coastguard Worker   oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
2868*795d594fSAndroid Build Coastguard Worker   oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
2869*795d594fSAndroid Build Coastguard Worker #if defined(__BIONIC__) || defined(__GLIBC__) || defined(ANDROID_HOST_MUSL)
2870*795d594fSAndroid Build Coastguard Worker   const struct mallinfo info = mallinfo();
2871*795d594fSAndroid Build Coastguard Worker   const size_t allocated_space = static_cast<size_t>(info.uordblks);
2872*795d594fSAndroid Build Coastguard Worker   const size_t free_space = static_cast<size_t>(info.fordblks);
2873*795d594fSAndroid Build Coastguard Worker   oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2874*795d594fSAndroid Build Coastguard Worker       << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
2875*795d594fSAndroid Build Coastguard Worker #endif
2876*795d594fSAndroid Build Coastguard Worker   compiled_method_storage_.DumpMemoryUsage(oss, extended);
2877*795d594fSAndroid Build Coastguard Worker   return oss.str();
2878*795d594fSAndroid Build Coastguard Worker }
2879*795d594fSAndroid Build Coastguard Worker 
InitializeThreadPools()2880*795d594fSAndroid Build Coastguard Worker void CompilerDriver::InitializeThreadPools() {
2881*795d594fSAndroid Build Coastguard Worker   size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2882*795d594fSAndroid Build Coastguard Worker   parallel_thread_pool_.reset(
2883*795d594fSAndroid Build Coastguard Worker       ThreadPool::Create("Compiler driver thread pool", parallel_count));
2884*795d594fSAndroid Build Coastguard Worker   single_thread_pool_.reset(ThreadPool::Create("Single-threaded Compiler driver thread pool", 0));
2885*795d594fSAndroid Build Coastguard Worker }
2886*795d594fSAndroid Build Coastguard Worker 
FreeThreadPools()2887*795d594fSAndroid Build Coastguard Worker void CompilerDriver::FreeThreadPools() {
2888*795d594fSAndroid Build Coastguard Worker   parallel_thread_pool_.reset();
2889*795d594fSAndroid Build Coastguard Worker   single_thread_pool_.reset();
2890*795d594fSAndroid Build Coastguard Worker }
2891*795d594fSAndroid Build Coastguard Worker 
SetClasspathDexFiles(const std::vector<const DexFile * > & dex_files)2892*795d594fSAndroid Build Coastguard Worker void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
2893*795d594fSAndroid Build Coastguard Worker   classpath_classes_.AddDexFiles(dex_files);
2894*795d594fSAndroid Build Coastguard Worker }
2895*795d594fSAndroid Build Coastguard Worker 
2896*795d594fSAndroid Build Coastguard Worker }  // namespace art
2897