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