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