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