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