compiler_driver.cc revision 3d504075f7c1204d581923460754bf6d3714b13f
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#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <utils/Trace.h>
21
22#include <vector>
23#include <unistd.h>
24
25#include "base/stl_util.h"
26#include "base/timing_logger.h"
27#include "class_linker.h"
28#include "compiler_backend.h"
29#include "dex_compilation_unit.h"
30#include "dex_file-inl.h"
31#include "dex/verification_results.h"
32#include "dex/verified_method.h"
33#include "dex/quick/dex_file_method_inliner.h"
34#include "jni_internal.h"
35#include "object_utils.h"
36#include "runtime.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap.h"
39#include "gc/space/space.h"
40#include "mirror/art_field-inl.h"
41#include "mirror/art_method-inl.h"
42#include "mirror/class_loader.h"
43#include "mirror/class-inl.h"
44#include "mirror/dex_cache-inl.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
47#include "mirror/throwable.h"
48#include "scoped_thread_state_change.h"
49#include "ScopedLocalRef.h"
50#include "thread.h"
51#include "thread_pool.h"
52#include "trampolines/trampoline_compiler.h"
53#include "transaction.h"
54#include "verifier/method_verifier.h"
55#include "verifier/method_verifier-inl.h"
56
57namespace art {
58
59static double Percentage(size_t x, size_t y) {
60  return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
61}
62
63static void DumpStat(size_t x, size_t y, const char* str) {
64  if (x == 0 && y == 0) {
65    return;
66  }
67  LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
68}
69
70class AOTCompilationStats {
71 public:
72  AOTCompilationStats()
73      : stats_lock_("AOT compilation statistics lock"),
74        types_in_dex_cache_(0), types_not_in_dex_cache_(0),
75        strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
76        resolved_types_(0), unresolved_types_(0),
77        resolved_instance_fields_(0), unresolved_instance_fields_(0),
78        resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
79        type_based_devirtualization_(0),
80        safe_casts_(0), not_safe_casts_(0) {
81    for (size_t i = 0; i <= kMaxInvokeType; i++) {
82      resolved_methods_[i] = 0;
83      unresolved_methods_[i] = 0;
84      virtual_made_direct_[i] = 0;
85      direct_calls_to_boot_[i] = 0;
86      direct_methods_to_boot_[i] = 0;
87    }
88  }
89
90  void Dump() {
91    DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
92    DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
93    DumpStat(resolved_types_, unresolved_types_, "types resolved");
94    DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
95    DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
96             "static fields resolved");
97    DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
98             "static fields local to a class");
99    DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
100    // Note, the code below subtracts the stat value so that when added to the stat value we have
101    // 100% of samples. TODO: clean this up.
102    DumpStat(type_based_devirtualization_,
103             resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
104             resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
105             type_based_devirtualization_,
106             "virtual/interface calls made direct based on type information");
107
108    for (size_t i = 0; i <= kMaxInvokeType; i++) {
109      std::ostringstream oss;
110      oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
111      DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
112      if (virtual_made_direct_[i] > 0) {
113        std::ostringstream oss2;
114        oss2 << static_cast<InvokeType>(i) << " methods made direct";
115        DumpStat(virtual_made_direct_[i],
116                 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
117                 oss2.str().c_str());
118      }
119      if (direct_calls_to_boot_[i] > 0) {
120        std::ostringstream oss2;
121        oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
122        DumpStat(direct_calls_to_boot_[i],
123                 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
124                 oss2.str().c_str());
125      }
126      if (direct_methods_to_boot_[i] > 0) {
127        std::ostringstream oss2;
128        oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
129        DumpStat(direct_methods_to_boot_[i],
130                 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
131                 oss2.str().c_str());
132      }
133    }
134  }
135
136// Allow lossy statistics in non-debug builds.
137#ifndef NDEBUG
138#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
139#else
140#define STATS_LOCK()
141#endif
142
143  void TypeInDexCache() {
144    STATS_LOCK();
145    types_in_dex_cache_++;
146  }
147
148  void TypeNotInDexCache() {
149    STATS_LOCK();
150    types_not_in_dex_cache_++;
151  }
152
153  void StringInDexCache() {
154    STATS_LOCK();
155    strings_in_dex_cache_++;
156  }
157
158  void StringNotInDexCache() {
159    STATS_LOCK();
160    strings_not_in_dex_cache_++;
161  }
162
163  void TypeDoesntNeedAccessCheck() {
164    STATS_LOCK();
165    resolved_types_++;
166  }
167
168  void TypeNeedsAccessCheck() {
169    STATS_LOCK();
170    unresolved_types_++;
171  }
172
173  void ResolvedInstanceField() {
174    STATS_LOCK();
175    resolved_instance_fields_++;
176  }
177
178  void UnresolvedInstanceField() {
179    STATS_LOCK();
180    unresolved_instance_fields_++;
181  }
182
183  void ResolvedLocalStaticField() {
184    STATS_LOCK();
185    resolved_local_static_fields_++;
186  }
187
188  void ResolvedStaticField() {
189    STATS_LOCK();
190    resolved_static_fields_++;
191  }
192
193  void UnresolvedStaticField() {
194    STATS_LOCK();
195    unresolved_static_fields_++;
196  }
197
198  // Indicate that type information from the verifier led to devirtualization.
199  void PreciseTypeDevirtualization() {
200    STATS_LOCK();
201    type_based_devirtualization_++;
202  }
203
204  // Indicate that a method of the given type was resolved at compile time.
205  void ResolvedMethod(InvokeType type) {
206    DCHECK_LE(type, kMaxInvokeType);
207    STATS_LOCK();
208    resolved_methods_[type]++;
209  }
210
211  // Indicate that a method of the given type was unresolved at compile time as it was in an
212  // unknown dex file.
213  void UnresolvedMethod(InvokeType type) {
214    DCHECK_LE(type, kMaxInvokeType);
215    STATS_LOCK();
216    unresolved_methods_[type]++;
217  }
218
219  // Indicate that a type of virtual method dispatch has been converted into a direct method
220  // dispatch.
221  void VirtualMadeDirect(InvokeType type) {
222    DCHECK(type == kVirtual || type == kInterface || type == kSuper);
223    STATS_LOCK();
224    virtual_made_direct_[type]++;
225  }
226
227  // Indicate that a method of the given type was able to call directly into boot.
228  void DirectCallsToBoot(InvokeType type) {
229    DCHECK_LE(type, kMaxInvokeType);
230    STATS_LOCK();
231    direct_calls_to_boot_[type]++;
232  }
233
234  // Indicate that a method of the given type was able to be resolved directly from boot.
235  void DirectMethodsToBoot(InvokeType type) {
236    DCHECK_LE(type, kMaxInvokeType);
237    STATS_LOCK();
238    direct_methods_to_boot_[type]++;
239  }
240
241  // A check-cast could be eliminated due to verifier type analysis.
242  void SafeCast() {
243    STATS_LOCK();
244    safe_casts_++;
245  }
246
247  // A check-cast couldn't be eliminated due to verifier type analysis.
248  void NotASafeCast() {
249    STATS_LOCK();
250    not_safe_casts_++;
251  }
252
253 private:
254  Mutex stats_lock_;
255
256  size_t types_in_dex_cache_;
257  size_t types_not_in_dex_cache_;
258
259  size_t strings_in_dex_cache_;
260  size_t strings_not_in_dex_cache_;
261
262  size_t resolved_types_;
263  size_t unresolved_types_;
264
265  size_t resolved_instance_fields_;
266  size_t unresolved_instance_fields_;
267
268  size_t resolved_local_static_fields_;
269  size_t resolved_static_fields_;
270  size_t unresolved_static_fields_;
271  // Type based devirtualization for invoke interface and virtual.
272  size_t type_based_devirtualization_;
273
274  size_t resolved_methods_[kMaxInvokeType + 1];
275  size_t unresolved_methods_[kMaxInvokeType + 1];
276  size_t virtual_made_direct_[kMaxInvokeType + 1];
277  size_t direct_calls_to_boot_[kMaxInvokeType + 1];
278  size_t direct_methods_to_boot_[kMaxInvokeType + 1];
279
280  size_t safe_casts_;
281  size_t not_safe_casts_;
282
283  DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
284};
285
286
287extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
288                                              const art::DexFile::CodeItem* code_item,
289                                              uint32_t access_flags,
290                                              art::InvokeType invoke_type,
291                                              uint16_t class_def_idx,
292                                              uint32_t method_idx,
293                                              jobject class_loader,
294                                              const art::DexFile& dex_file);
295
296CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
297                               VerificationResults* verification_results,
298                               DexFileToMethodInlinerMap* method_inliner_map,
299                               CompilerBackend::Kind compiler_backend_kind,
300                               InstructionSet instruction_set,
301                               InstructionSetFeatures instruction_set_features,
302                               bool image, DescriptorSet* image_classes, size_t thread_count,
303                               bool dump_stats, bool dump_passes, CumulativeLogger* timer)
304    : compiler_options_(compiler_options),
305      verification_results_(verification_results),
306      method_inliner_map_(method_inliner_map),
307      compiler_backend_(CompilerBackend::Create(compiler_backend_kind)),
308      instruction_set_(instruction_set),
309      instruction_set_features_(instruction_set_features),
310      freezing_constructor_lock_("freezing constructor lock"),
311      compiled_classes_lock_("compiled classes lock"),
312      compiled_methods_lock_("compiled method lock"),
313      image_(image),
314      image_classes_(image_classes),
315      thread_count_(thread_count),
316      start_ns_(0),
317      stats_(new AOTCompilationStats),
318      dump_stats_(dump_stats),
319      dump_passes_(dump_passes),
320      timings_logger_(timer),
321      compiler_library_(NULL),
322      compiler_context_(NULL),
323      compiler_enable_auto_elf_loading_(NULL),
324      compiler_get_method_code_addr_(NULL),
325      support_boot_image_fixup_(instruction_set != kMips),
326      dedupe_code_("dedupe code"),
327      dedupe_mapping_table_("dedupe mapping table"),
328      dedupe_vmap_table_("dedupe vmap table"),
329      dedupe_gc_map_("dedupe gc map") {
330  DCHECK(compiler_options_ != nullptr);
331  DCHECK(verification_results_ != nullptr);
332  DCHECK(method_inliner_map_ != nullptr);
333
334  CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, NULL), "compiler tls key");
335
336  dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
337
338  compiler_backend_->Init(*this);
339
340  CHECK(!Runtime::Current()->IsStarted());
341  if (!image_) {
342    CHECK(image_classes_.get() == NULL);
343  }
344}
345
346std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
347  return dedupe_code_.Add(Thread::Current(), code);
348}
349
350std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
351  return dedupe_mapping_table_.Add(Thread::Current(), code);
352}
353
354std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
355  return dedupe_vmap_table_.Add(Thread::Current(), code);
356}
357
358std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
359  return dedupe_gc_map_.Add(Thread::Current(), code);
360}
361
362CompilerDriver::~CompilerDriver() {
363  Thread* self = Thread::Current();
364  {
365    MutexLock mu(self, compiled_classes_lock_);
366    STLDeleteValues(&compiled_classes_);
367  }
368  {
369    MutexLock mu(self, compiled_methods_lock_);
370    STLDeleteValues(&compiled_methods_);
371  }
372  {
373    MutexLock mu(self, compiled_methods_lock_);
374    STLDeleteElements(&code_to_patch_);
375  }
376  {
377    MutexLock mu(self, compiled_methods_lock_);
378    STLDeleteElements(&methods_to_patch_);
379  }
380  {
381    MutexLock mu(self, compiled_methods_lock_);
382    STLDeleteElements(&classes_to_patch_);
383  }
384  CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
385  compiler_backend_->UnInit(*this);
386}
387
388CompilerTls* CompilerDriver::GetTls() {
389  // Lazily create thread-local storage
390  CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
391  if (res == NULL) {
392    res = new CompilerTls();
393    CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
394  }
395  return res;
396}
397
398const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
399  return CreateTrampoline(instruction_set_, kInterpreterAbi,
400                          INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToInterpreterBridge));
401}
402
403const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
404  return CreateTrampoline(instruction_set_, kInterpreterAbi,
405                          INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToCompiledCodeBridge));
406}
407
408const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
409  return CreateTrampoline(instruction_set_, kJniAbi, JNI_ENTRYPOINT_OFFSET(pDlsymLookup));
410}
411
412const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
413  return CreateTrampoline(instruction_set_, kPortableAbi,
414                          PORTABLE_ENTRYPOINT_OFFSET(pPortableImtConflictTrampoline));
415}
416
417const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
418  return CreateTrampoline(instruction_set_, kPortableAbi,
419                          PORTABLE_ENTRYPOINT_OFFSET(pPortableResolutionTrampoline));
420}
421
422const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
423  return CreateTrampoline(instruction_set_, kPortableAbi,
424                          PORTABLE_ENTRYPOINT_OFFSET(pPortableToInterpreterBridge));
425}
426
427const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
428  return CreateTrampoline(instruction_set_, kQuickAbi,
429                          QUICK_ENTRYPOINT_OFFSET(pQuickImtConflictTrampoline));
430}
431
432const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
433  return CreateTrampoline(instruction_set_, kQuickAbi,
434                          QUICK_ENTRYPOINT_OFFSET(pQuickResolutionTrampoline));
435}
436
437const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
438  return CreateTrampoline(instruction_set_, kQuickAbi,
439                          QUICK_ENTRYPOINT_OFFSET(pQuickToInterpreterBridge));
440}
441
442void CompilerDriver::CompileAll(jobject class_loader,
443                                const std::vector<const DexFile*>& dex_files,
444                                TimingLogger* timings) {
445  DCHECK(!Runtime::Current()->IsStarted());
446  UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
447  PreCompile(class_loader, dex_files, thread_pool.get(), timings);
448  Compile(class_loader, dex_files, thread_pool.get(), timings);
449  if (dump_stats_) {
450    stats_->Dump();
451  }
452}
453
454static DexToDexCompilationLevel GetDexToDexCompilationlevel(
455    Thread* self, SirtRef<mirror::ClassLoader>& class_loader, const DexFile& dex_file,
456    const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
457  const char* descriptor = dex_file.GetClassDescriptor(class_def);
458  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
459  mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
460  if (klass == NULL) {
461    CHECK(self->IsExceptionPending());
462    self->ClearException();
463    return kDontDexToDexCompile;
464  }
465  // The verifier can only run on "quick" instructions at runtime (see usage of
466  // FindAccessedFieldAtDexPc and FindInvokedMethodAtDexPc in ThrowNullPointerExceptionFromDexPC
467  // function). Since image classes can be verified again while compiling an application,
468  // we must prevent the DEX-to-DEX compiler from introducing them.
469  // TODO: find a way to enable "quick" instructions for image classes and remove this check.
470  bool compiling_image_classes = class_loader.get() == nullptr;
471  if (compiling_image_classes) {
472    return kRequired;
473  } else if (klass->IsVerified()) {
474    // Class is verified so we can enable DEX-to-DEX compilation for performance.
475    return kOptimize;
476  } else if (klass->IsCompileTimeVerified()) {
477    // Class verification has soft-failed. Anyway, ensure at least correctness.
478    DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
479    return kRequired;
480  } else {
481    // Class verification has failed: do not run DEX-to-DEX compilation.
482    return kDontDexToDexCompile;
483  }
484}
485
486void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
487  DCHECK(!Runtime::Current()->IsStarted());
488  Thread* self = Thread::Current();
489  jobject jclass_loader;
490  const DexFile* dex_file;
491  uint16_t class_def_idx;
492  uint32_t method_idx = method->GetDexMethodIndex();
493  uint32_t access_flags = method->GetAccessFlags();
494  InvokeType invoke_type = method->GetInvokeType();
495  {
496    ScopedObjectAccessUnchecked soa(self);
497    ScopedLocalRef<jobject>
498      local_class_loader(soa.Env(),
499                    soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
500    jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
501    // Find the dex_file
502    MethodHelper mh(method);
503    dex_file = &mh.GetDexFile();
504    class_def_idx = mh.GetClassDefIndex();
505  }
506  const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
507  self->TransitionFromRunnableToSuspended(kNative);
508
509  std::vector<const DexFile*> dex_files;
510  dex_files.push_back(dex_file);
511
512  UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
513  PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
514
515  // Can we run DEX-to-DEX compiler on this class ?
516  DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
517  {
518    ScopedObjectAccess soa(Thread::Current());
519    const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
520    SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
521                                              soa.Decode<mirror::ClassLoader*>(jclass_loader));
522    dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
523                                                               class_def);
524  }
525  CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
526                *dex_file, dex_to_dex_compilation_level);
527
528  self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
529
530  self->TransitionFromSuspendedToRunnable();
531}
532
533void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
534                             ThreadPool* thread_pool, TimingLogger* timings) {
535  for (size_t i = 0; i != dex_files.size(); ++i) {
536    const DexFile* dex_file = dex_files[i];
537    CHECK(dex_file != NULL);
538    ResolveDexFile(class_loader, *dex_file, thread_pool, timings);
539  }
540}
541
542void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
543                                ThreadPool* thread_pool, TimingLogger* timings) {
544  LoadImageClasses(timings);
545
546  Resolve(class_loader, dex_files, thread_pool, timings);
547
548  Verify(class_loader, dex_files, thread_pool, timings);
549
550  InitializeClasses(class_loader, dex_files, thread_pool, timings);
551
552  UpdateImageClasses(timings);
553}
554
555bool CompilerDriver::IsImageClass(const char* descriptor) const {
556  if (!IsImage()) {
557    return true;
558  } else {
559    return image_classes_->find(descriptor) != image_classes_->end();
560  }
561}
562
563static void ResolveExceptionsForMethod(MethodHelper* mh,
564    std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
565    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
566  const DexFile::CodeItem* code_item = mh->GetCodeItem();
567  if (code_item == NULL) {
568    return;  // native or abstract method
569  }
570  if (code_item->tries_size_ == 0) {
571    return;  // nothing to process
572  }
573  const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
574  size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
575  for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
576    int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
577    bool has_catch_all = false;
578    if (encoded_catch_handler_size <= 0) {
579      encoded_catch_handler_size = -encoded_catch_handler_size;
580      has_catch_all = true;
581    }
582    for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
583      uint16_t encoded_catch_handler_handlers_type_idx =
584          DecodeUnsignedLeb128(&encoded_catch_handler_list);
585      // Add to set of types to resolve if not already in the dex cache resolved types
586      if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
587        exceptions_to_resolve.insert(
588            std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
589                                                &mh->GetDexFile()));
590      }
591      // ignore address associated with catch handler
592      DecodeUnsignedLeb128(&encoded_catch_handler_list);
593    }
594    if (has_catch_all) {
595      // ignore catch all address
596      DecodeUnsignedLeb128(&encoded_catch_handler_list);
597    }
598  }
599}
600
601static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
602    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
603  std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
604      reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
605  MethodHelper mh;
606  for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
607    mirror::ArtMethod* m = c->GetVirtualMethod(i);
608    mh.ChangeMethod(m);
609    ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
610  }
611  for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
612    mirror::ArtMethod* m = c->GetDirectMethod(i);
613    mh.ChangeMethod(m);
614    ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
615  }
616  return true;
617}
618
619static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
620    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
621  CompilerDriver::DescriptorSet* image_classes =
622      reinterpret_cast<CompilerDriver::DescriptorSet*>(arg);
623  image_classes->insert(ClassHelper(klass).GetDescriptor());
624  return true;
625}
626
627// Make a list of descriptors for classes to include in the image
628void CompilerDriver::LoadImageClasses(TimingLogger* timings)
629      LOCKS_EXCLUDED(Locks::mutator_lock_) {
630  if (!IsImage()) {
631    return;
632  }
633
634  timings->NewSplit("LoadImageClasses");
635  // Make a first class to load all classes explicitly listed in the file
636  Thread* self = Thread::Current();
637  ScopedObjectAccess soa(self);
638  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
639  for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
640    const std::string& descriptor(*it);
641    SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(self, descriptor.c_str()));
642    if (klass.get() == NULL) {
643      VLOG(compiler) << "Failed to find class " << descriptor;
644      image_classes_->erase(it++);
645      self->ClearException();
646    } else {
647      ++it;
648    }
649  }
650
651  // Resolve exception classes referenced by the loaded classes. The catch logic assumes
652  // exceptions are resolved by the verifier when there is a catch block in an interested method.
653  // Do this here so that exception classes appear to have been specified image classes.
654  std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
655  SirtRef<mirror::Class> java_lang_Throwable(self,
656                                     class_linker->FindSystemClass(self, "Ljava/lang/Throwable;"));
657  do {
658    unresolved_exception_types.clear();
659    class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
660                               &unresolved_exception_types);
661    for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
662      uint16_t exception_type_idx = exception_type.first;
663      const DexFile* dex_file = exception_type.second;
664      SirtRef<mirror::DexCache> dex_cache(self, class_linker->FindDexCache(*dex_file));
665      SirtRef<mirror::ClassLoader> class_loader(self, nullptr);
666      SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
667                                                                   dex_cache, class_loader));
668      if (klass.get() == NULL) {
669        const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
670        const char* descriptor = dex_file->GetTypeDescriptor(type_id);
671        LOG(FATAL) << "Failed to resolve class " << descriptor;
672      }
673      DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
674    }
675    // Resolving exceptions may load classes that reference more exceptions, iterate until no
676    // more are found
677  } while (!unresolved_exception_types.empty());
678
679  // We walk the roots looking for classes so that we'll pick up the
680  // above classes plus any classes them depend on such super
681  // classes, interfaces, and the required ClassLinker roots.
682  class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
683
684  CHECK_NE(image_classes_->size(), 0U);
685}
686
687static void MaybeAddToImageClasses(mirror::Class* klass, CompilerDriver::DescriptorSet* image_classes)
688    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
689  while (!klass->IsObjectClass()) {
690    ClassHelper kh(klass);
691    const char* descriptor = kh.GetDescriptor();
692    std::pair<CompilerDriver::DescriptorSet::iterator, bool> result =
693        image_classes->insert(descriptor);
694    if (result.second) {
695        VLOG(compiler) << "Adding " << descriptor << " to image classes";
696    } else {
697      return;
698    }
699    for (size_t i = 0; i < kh.NumDirectInterfaces(); ++i) {
700      MaybeAddToImageClasses(kh.GetDirectInterface(i), image_classes);
701    }
702    if (klass->IsArrayClass()) {
703      MaybeAddToImageClasses(klass->GetComponentType(), image_classes);
704    }
705    klass = klass->GetSuperClass();
706  }
707}
708
709void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
710  DCHECK(object != NULL);
711  DCHECK(arg != NULL);
712  CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
713  MaybeAddToImageClasses(object->GetClass(), compiler_driver->image_classes_.get());
714}
715
716void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
717  if (IsImage()) {
718    timings->NewSplit("UpdateImageClasses");
719
720    // Update image_classes_ with classes for objects created by <clinit> methods.
721    Thread* self = Thread::Current();
722    const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
723    gc::Heap* heap = Runtime::Current()->GetHeap();
724    // TODO: Image spaces only?
725    ScopedObjectAccess soa(Thread::Current());
726    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
727    heap->VisitObjects(FindClinitImageClassesCallback, this);
728    self->EndAssertNoThreadSuspension(old_cause);
729  }
730}
731
732bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
733  if (IsImage() &&
734      IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
735    if (kIsDebugBuild) {
736      ScopedObjectAccess soa(Thread::Current());
737      mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
738      mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
739      CHECK(resolved_class != NULL);
740    }
741    stats_->TypeInDexCache();
742    return true;
743  } else {
744    stats_->TypeNotInDexCache();
745    return false;
746  }
747}
748
749bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
750                                                        uint32_t string_idx) {
751  // See also Compiler::ResolveDexFile
752
753  bool result = false;
754  if (IsImage()) {
755    // We resolve all const-string strings when building for the image.
756    ScopedObjectAccess soa(Thread::Current());
757    SirtRef<mirror::DexCache> dex_cache(soa.Self(), Runtime::Current()->GetClassLinker()->FindDexCache(dex_file));
758    Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
759    result = true;
760  }
761  if (result) {
762    stats_->StringInDexCache();
763  } else {
764    stats_->StringNotInDexCache();
765  }
766  return result;
767}
768
769bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
770                                                uint32_t type_idx,
771                                                bool* type_known_final, bool* type_known_abstract,
772                                                bool* equals_referrers_class) {
773  if (type_known_final != NULL) {
774    *type_known_final = false;
775  }
776  if (type_known_abstract != NULL) {
777    *type_known_abstract = false;
778  }
779  if (equals_referrers_class != NULL) {
780    *equals_referrers_class = false;
781  }
782  ScopedObjectAccess soa(Thread::Current());
783  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
784  // Get type from dex cache assuming it was populated by the verifier
785  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
786  if (resolved_class == NULL) {
787    stats_->TypeNeedsAccessCheck();
788    return false;  // Unknown class needs access checks.
789  }
790  const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
791  if (equals_referrers_class != NULL) {
792    *equals_referrers_class = (method_id.class_idx_ == type_idx);
793  }
794  mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
795  if (referrer_class == NULL) {
796    stats_->TypeNeedsAccessCheck();
797    return false;  // Incomplete referrer knowledge needs access check.
798  }
799  // Perform access check, will return true if access is ok or false if we're going to have to
800  // check this at runtime (for example for class loaders).
801  bool result = referrer_class->CanAccess(resolved_class);
802  if (result) {
803    stats_->TypeDoesntNeedAccessCheck();
804    if (type_known_final != NULL) {
805      *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
806    }
807    if (type_known_abstract != NULL) {
808      *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
809    }
810  } else {
811    stats_->TypeNeedsAccessCheck();
812  }
813  return result;
814}
815
816bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
817                                                            const DexFile& dex_file,
818                                                            uint32_t type_idx) {
819  ScopedObjectAccess soa(Thread::Current());
820  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
821  // Get type from dex cache assuming it was populated by the verifier.
822  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
823  if (resolved_class == NULL) {
824    stats_->TypeNeedsAccessCheck();
825    return false;  // Unknown class needs access checks.
826  }
827  const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
828  mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
829  if (referrer_class == NULL) {
830    stats_->TypeNeedsAccessCheck();
831    return false;  // Incomplete referrer knowledge needs access check.
832  }
833  // Perform access and instantiable checks, will return true if access is ok or false if we're
834  // going to have to check this at runtime (for example for class loaders).
835  bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
836  if (result) {
837    stats_->TypeDoesntNeedAccessCheck();
838  } else {
839    stats_->TypeNeedsAccessCheck();
840  }
841  return result;
842}
843
844bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
845                                        bool* is_type_initialized, bool* use_direct_type_ptr,
846                                        uintptr_t* direct_type_ptr) {
847  ScopedObjectAccess soa(Thread::Current());
848  mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
849  mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
850  if (resolved_class == nullptr) {
851    return false;
852  }
853  const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
854  if (compiling_boot) {
855    // boot -> boot class pointers.
856    // True if the class is in the image at boot compiling time.
857    const bool is_image_class = IsImage() && IsImageClass(
858        dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
859    // True if pc relative load works.
860    const bool support_boot_image_fixup = GetSupportBootImageFixup();
861    if (is_image_class && support_boot_image_fixup) {
862      *is_type_initialized = resolved_class->IsInitialized();
863      *use_direct_type_ptr = false;
864      *direct_type_ptr = 0;
865      return true;
866    } else {
867      return false;
868    }
869  } else {
870    // True if the class is in the image at app compiling time.
871    const bool class_in_image =
872        Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
873    if (class_in_image) {
874      // boot -> app class pointers.
875      *is_type_initialized = resolved_class->IsInitialized();
876      *use_direct_type_ptr = true;
877      *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
878      return true;
879    } else {
880      // app -> app class pointers.
881      // Give up because app does not have an image and class
882      // isn't created at compile time.  TODO: implement this
883      // if/when each app gets an image.
884      return false;
885    }
886  }
887}
888
889static mirror::Class* ComputeCompilingMethodsClass(ScopedObjectAccess& soa,
890                                                   SirtRef<mirror::DexCache>& dex_cache,
891                                                   const DexCompilationUnit* mUnit)
892    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
893  // The passed dex_cache is a hint, sanity check before asking the class linker that will take a
894  // lock.
895  if (dex_cache->GetDexFile() != mUnit->GetDexFile()) {
896    dex_cache.reset(mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
897  }
898  SirtRef<mirror::ClassLoader>
899      class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
900  const DexFile::MethodId& referrer_method_id =
901      mUnit->GetDexFile()->GetMethodId(mUnit->GetDexMethodIndex());
902  return mUnit->GetClassLinker()->ResolveType(*mUnit->GetDexFile(), referrer_method_id.class_idx_,
903                                              dex_cache, class_loader);
904}
905
906static mirror::ArtField* ComputeFieldReferencedFromCompilingMethod(
907    ScopedObjectAccess& soa, const DexCompilationUnit* mUnit, uint32_t field_idx, bool is_static)
908    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
909  SirtRef<mirror::DexCache> dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
910  SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
911  return mUnit->GetClassLinker()->ResolveField(*mUnit->GetDexFile(), field_idx, dex_cache,
912                                               class_loader, is_static);
913}
914
915static mirror::ArtMethod* ComputeMethodReferencedFromCompilingMethod(ScopedObjectAccess& soa,
916                                                                     const DexCompilationUnit* mUnit,
917                                                                     uint32_t method_idx,
918                                                                     InvokeType type)
919    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
920  SirtRef<mirror::DexCache> dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
921  SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
922  return mUnit->GetClassLinker()->ResolveMethod(*mUnit->GetDexFile(), method_idx, dex_cache,
923                                                class_loader, NULL, type);
924}
925
926bool CompilerDriver::ComputeSpecialAccessorInfo(uint32_t field_idx, bool is_put,
927                                                verifier::MethodVerifier* verifier,
928                                                InlineIGetIPutData* result) {
929  mirror::DexCache* dex_cache = verifier->GetDexCache();
930  uint32_t method_idx = verifier->GetMethodReference().dex_method_index;
931  mirror::ArtMethod* method = dex_cache->GetResolvedMethod(method_idx);
932  mirror::ArtField* field = dex_cache->GetResolvedField(field_idx);
933  if (method == nullptr || field == nullptr || field->IsStatic()) {
934    return false;
935  }
936  mirror::Class* method_class = method->GetDeclaringClass();
937  mirror::Class* field_class = field->GetDeclaringClass();
938  if (!method_class->CanAccessResolvedField(field_class, field, dex_cache, field_idx) ||
939      (is_put && field->IsFinal() && method_class != field_class)) {
940    return false;
941  }
942  DCHECK_GE(field->GetOffset().Int32Value(), 0);
943  result->field_idx = field_idx;
944  result->field_offset = field->GetOffset().Int32Value();
945  result->is_volatile = field->IsVolatile();
946  return true;
947}
948
949bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
950                                              bool is_put, int* field_offset, bool* is_volatile) {
951  ScopedObjectAccess soa(Thread::Current());
952  // Conservative defaults.
953  *field_offset = -1;
954  *is_volatile = true;
955  // Try to resolve field and ignore if an Incompatible Class Change Error (ie is static).
956  mirror::ArtField* resolved_field =
957      ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx, false);
958  if (resolved_field != NULL && !resolved_field->IsStatic()) {
959    SirtRef<mirror::DexCache> dex_cache(soa.Self(),
960                                        resolved_field->GetDeclaringClass()->GetDexCache());
961    mirror::Class* referrer_class =
962        ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
963    if (referrer_class != NULL) {
964      mirror::Class* fields_class = resolved_field->GetDeclaringClass();
965      bool access_ok = referrer_class->CanAccessResolvedField(fields_class, resolved_field,
966                                                              dex_cache.get(), field_idx);
967      bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
968          fields_class != referrer_class;
969      if (access_ok && !is_write_to_final_from_wrong_class) {
970        *field_offset = resolved_field->GetOffset().Int32Value();
971        *is_volatile = resolved_field->IsVolatile();
972        stats_->ResolvedInstanceField();
973        return true;  // Fast path.
974      }
975    }
976  }
977  // Clean up any exception left by field/type resolution
978  if (soa.Self()->IsExceptionPending()) {
979    soa.Self()->ClearException();
980  }
981  stats_->UnresolvedInstanceField();
982  return false;  // Incomplete knowledge needs slow path.
983}
984
985bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
986                                            bool is_put, int* field_offset, int* storage_index,
987                                            bool* is_referrers_class, bool* is_volatile,
988                                            bool* is_initialized) {
989  ScopedObjectAccess soa(Thread::Current());
990  // Conservative defaults.
991  *field_offset = -1;
992  *storage_index = -1;
993  *is_referrers_class = false;
994  *is_volatile = true;
995  *is_initialized = false;
996  // Try to resolve field and ignore if an Incompatible Class Change Error (ie isn't static).
997  mirror::ArtField* resolved_field =
998      ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx, true);
999  if (resolved_field != NULL && resolved_field->IsStatic()) {
1000    SirtRef<mirror::DexCache> dex_cache(soa.Self(), resolved_field->GetDeclaringClass()->GetDexCache());
1001    mirror::Class* referrer_class =
1002        ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
1003    if (referrer_class != NULL) {
1004      mirror::Class* fields_class = resolved_field->GetDeclaringClass();
1005      if (fields_class == referrer_class) {
1006        *is_referrers_class = true;  // implies no worrying about class initialization
1007        *is_initialized = true;
1008        *field_offset = resolved_field->GetOffset().Int32Value();
1009        *is_volatile = resolved_field->IsVolatile();
1010        stats_->ResolvedLocalStaticField();
1011        return true;  // fast path
1012      } else {
1013        bool access_ok = referrer_class->CanAccessResolvedField(fields_class, resolved_field,
1014                                                                dex_cache.get(), field_idx);
1015        bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
1016        if (access_ok && !is_write_to_final_from_wrong_class) {
1017          // We have the resolved field, we must make it into a index for the referrer
1018          // in its static storage (which may fail if it doesn't have a slot for it)
1019          // TODO: for images we can elide the static storage base null check
1020          // if we know there's a non-null entry in the image
1021          mirror::DexCache* dex_cache = mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile());
1022          if (fields_class->GetDexCache() == dex_cache) {
1023            // common case where the dex cache of both the referrer and the field are the same,
1024            // no need to search the dex file
1025            *storage_index = fields_class->GetDexTypeIndex();
1026            *field_offset = resolved_field->GetOffset().Int32Value();
1027            *is_volatile = resolved_field->IsVolatile();
1028            *is_initialized = fields_class->IsInitialized() &&
1029                CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index);
1030            stats_->ResolvedStaticField();
1031            return true;
1032          }
1033          // Search dex file for localized ssb index, may fail if field's class is a parent
1034          // of the class mentioned in the dex file and there is no dex cache entry.
1035          const DexFile::StringId* string_id =
1036              mUnit->GetDexFile()->FindStringId(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
1037          if (string_id != NULL) {
1038            const DexFile::TypeId* type_id =
1039               mUnit->GetDexFile()->FindTypeId(mUnit->GetDexFile()->GetIndexForStringId(*string_id));
1040            if (type_id != NULL) {
1041              // medium path, needs check of static storage base being initialized
1042              *storage_index = mUnit->GetDexFile()->GetIndexForTypeId(*type_id);
1043              *field_offset = resolved_field->GetOffset().Int32Value();
1044              *is_volatile = resolved_field->IsVolatile();
1045              *is_initialized = fields_class->IsInitialized() &&
1046                  CanAssumeTypeIsPresentInDexCache(*mUnit->GetDexFile(), *storage_index);
1047              stats_->ResolvedStaticField();
1048              return true;
1049            }
1050          }
1051        }
1052      }
1053    }
1054  }
1055  // Clean up any exception left by field/type resolution
1056  if (soa.Self()->IsExceptionPending()) {
1057    soa.Self()->ClearException();
1058  }
1059  stats_->UnresolvedStaticField();
1060  return false;  // Incomplete knowledge needs slow path.
1061}
1062
1063void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1064                                                   bool no_guarantee_of_dex_cache_entry,
1065                                                   mirror::Class* referrer_class,
1066                                                   mirror::ArtMethod* method,
1067                                                   bool update_stats,
1068                                                   MethodReference* target_method,
1069                                                   uintptr_t* direct_code,
1070                                                   uintptr_t* direct_method) {
1071  // For direct and static methods compute possible direct_code and direct_method values, ie
1072  // an address for the Method* being invoked and an address of the code for that Method*.
1073  // For interface calls compute a value for direct_method that is the interface method being
1074  // invoked, so this can be passed to the out-of-line runtime support code.
1075  *direct_code = 0;
1076  *direct_method = 0;
1077  bool use_dex_cache = false;
1078  const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
1079  if (compiler_backend_->IsPortable()) {
1080    if (sharp_type != kStatic && sharp_type != kDirect) {
1081      return;
1082    }
1083    use_dex_cache = true;
1084  } else {
1085    if (sharp_type != kStatic && sharp_type != kDirect) {
1086      return;
1087    }
1088    // TODO: support patching on all architectures.
1089    use_dex_cache = compiling_boot && !support_boot_image_fixup_;
1090  }
1091  bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1092  if (!use_dex_cache) {
1093    if (!method_code_in_boot) {
1094      use_dex_cache = true;
1095    } else {
1096      bool has_clinit_trampoline =
1097          method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1098      if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1099        // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1100        // class.
1101        use_dex_cache = true;
1102      }
1103    }
1104  }
1105  if (update_stats && method_code_in_boot) {
1106    stats_->DirectCallsToBoot(*type);
1107    stats_->DirectMethodsToBoot(*type);
1108  }
1109  if (!use_dex_cache && compiling_boot) {
1110    MethodHelper mh(method);
1111    if (!IsImageClass(mh.GetDeclaringClassDescriptor())) {
1112      // We can only branch directly to Methods that are resolved in the DexCache.
1113      // Otherwise we won't invoke the resolution trampoline.
1114      use_dex_cache = true;
1115    }
1116  }
1117  // The method is defined not within this dex file. We need a dex cache slot within the current
1118  // dex file or direct pointers.
1119  bool must_use_direct_pointers = false;
1120  if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1121    target_method->dex_method_index = method->GetDexMethodIndex();
1122  } else {
1123    // TODO: support patching from one dex file to another in the boot image.
1124    use_dex_cache = use_dex_cache || compiling_boot;
1125    if (no_guarantee_of_dex_cache_entry) {
1126      // See if the method is also declared in this dex cache.
1127      uint32_t dex_method_idx = MethodHelper(method).FindDexMethodIndexInOtherDexFile(
1128          *target_method->dex_file, target_method->dex_method_index);
1129      if (dex_method_idx != DexFile::kDexNoIndex) {
1130        target_method->dex_method_index = dex_method_idx;
1131      } else {
1132        must_use_direct_pointers = true;
1133      }
1134    }
1135  }
1136  if (use_dex_cache) {
1137    if (must_use_direct_pointers) {
1138      // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1139      // pointers are required as the dex cache lacks an appropriate entry.
1140      VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1141    } else {
1142      *type = sharp_type;
1143    }
1144  } else {
1145    if (compiling_boot) {
1146      *type = sharp_type;
1147      *direct_method = -1;
1148      *direct_code = -1;
1149    } else {
1150      bool method_in_image =
1151          Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
1152      if (method_in_image) {
1153        CHECK(!method->IsAbstract());
1154        *type = sharp_type;
1155        *direct_method = reinterpret_cast<uintptr_t>(method);
1156        *direct_code = compiler_backend_->GetEntryPointOf(method);
1157        target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1158        target_method->dex_method_index = method->GetDexMethodIndex();
1159      } else if (!must_use_direct_pointers) {
1160        // Set the code and rely on the dex cache for the method.
1161        *type = sharp_type;
1162        *direct_code = compiler_backend_->GetEntryPointOf(method);
1163      } else {
1164        // Direct pointers were required but none were available.
1165        VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1166      }
1167    }
1168  }
1169}
1170
1171bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
1172                                       bool update_stats, bool enable_devirtualization,
1173                                       InvokeType* invoke_type, MethodReference* target_method,
1174                                       int* vtable_idx, uintptr_t* direct_code,
1175                                       uintptr_t* direct_method) {
1176  ScopedObjectAccess soa(Thread::Current());
1177  *vtable_idx = -1;
1178  *direct_code = 0;
1179  *direct_method = 0;
1180  mirror::ArtMethod* resolved_method =
1181      ComputeMethodReferencedFromCompilingMethod(soa, mUnit, target_method->dex_method_index,
1182                                                 *invoke_type);
1183  if (resolved_method != NULL) {
1184    if (*invoke_type == kVirtual || *invoke_type == kSuper) {
1185      *vtable_idx = resolved_method->GetMethodIndex();
1186    } else if (*invoke_type == kInterface) {
1187      *vtable_idx = resolved_method->GetDexMethodIndex();
1188    }
1189    // Don't try to fast-path if we don't understand the caller's class or this appears to be an
1190    // Incompatible Class Change Error.
1191    SirtRef<mirror::DexCache> dex_cache(soa.Self(), resolved_method->GetDeclaringClass()->GetDexCache());
1192    mirror::Class* referrer_class =
1193        ComputeCompilingMethodsClass(soa, dex_cache, mUnit);
1194    bool icce = resolved_method->CheckIncompatibleClassChange(*invoke_type);
1195    if (referrer_class != NULL && !icce) {
1196      mirror::Class* methods_class = resolved_method->GetDeclaringClass();
1197      if (referrer_class->CanAccessResolvedMethod(methods_class, resolved_method, dex_cache.get(),
1198                                                  target_method->dex_method_index)) {
1199        const bool enableFinalBasedSharpening = enable_devirtualization;
1200        // Sharpen a virtual call into a direct call when the target is known not to have been
1201        // overridden (ie is final).
1202        bool can_sharpen_virtual_based_on_type =
1203            (*invoke_type == kVirtual) && (resolved_method->IsFinal() || methods_class->IsFinal());
1204        // For invoke-super, ensure the vtable index will be correct to dispatch in the vtable of
1205        // the super class.
1206        bool can_sharpen_super_based_on_type = (*invoke_type == kSuper) &&
1207            (referrer_class != methods_class) && referrer_class->IsSubClass(methods_class) &&
1208            resolved_method->GetMethodIndex() < methods_class->GetVTable()->GetLength() &&
1209            (methods_class->GetVTable()->Get(resolved_method->GetMethodIndex()) == resolved_method);
1210
1211        if (enableFinalBasedSharpening && (can_sharpen_virtual_based_on_type ||
1212                                            can_sharpen_super_based_on_type)) {
1213          // Sharpen a virtual call into a direct call. The method_idx is into the DexCache
1214          // associated with target_method->dex_file.
1215          CHECK(target_method->dex_file == mUnit->GetDexFile());
1216          DCHECK(dex_cache.get() == mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1217          CHECK(dex_cache->GetResolvedMethod(target_method->dex_method_index) ==
1218                resolved_method) << PrettyMethod(resolved_method);
1219          InvokeType orig_invoke_type = *invoke_type;
1220          GetCodeAndMethodForDirectCall(invoke_type, kDirect, false, referrer_class, resolved_method,
1221                                        update_stats, target_method, direct_code, direct_method);
1222          if (update_stats && (*invoke_type == kDirect)) {
1223            stats_->ResolvedMethod(orig_invoke_type);
1224            stats_->VirtualMadeDirect(orig_invoke_type);
1225          }
1226          DCHECK_NE(*invoke_type, kSuper) << PrettyMethod(resolved_method);
1227          return true;
1228        }
1229        const bool enableVerifierBasedSharpening = enable_devirtualization;
1230        if (enableVerifierBasedSharpening && (*invoke_type == kVirtual ||
1231                                              *invoke_type == kInterface)) {
1232          // Did the verifier record a more precise invoke target based on its type information?
1233          DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1234          const MethodReference* devirt_map_target =
1235              mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1236          if (devirt_map_target != NULL) {
1237            SirtRef<mirror::DexCache> target_dex_cache(soa.Self(), mUnit->GetClassLinker()->FindDexCache(*devirt_map_target->dex_file));
1238            SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
1239            mirror::ArtMethod* called_method =
1240                mUnit->GetClassLinker()->ResolveMethod(*devirt_map_target->dex_file,
1241                                                       devirt_map_target->dex_method_index,
1242                                                       target_dex_cache, class_loader, NULL,
1243                                                       kVirtual);
1244            CHECK(called_method != NULL);
1245            CHECK(!called_method->IsAbstract());
1246            InvokeType orig_invoke_type = *invoke_type;
1247            GetCodeAndMethodForDirectCall(invoke_type, kDirect, true, referrer_class, called_method,
1248                                          update_stats, target_method, direct_code, direct_method);
1249            if (update_stats && (*invoke_type == kDirect)) {
1250              stats_->ResolvedMethod(orig_invoke_type);
1251              stats_->VirtualMadeDirect(orig_invoke_type);
1252              stats_->PreciseTypeDevirtualization();
1253            }
1254            DCHECK_NE(*invoke_type, kSuper);
1255            return true;
1256          }
1257        }
1258        if (*invoke_type == kSuper) {
1259          // Unsharpened super calls are suspicious so go slow-path.
1260        } else {
1261          // Sharpening failed so generate a regular resolved method dispatch.
1262          if (update_stats) {
1263            stats_->ResolvedMethod(*invoke_type);
1264          }
1265          GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1266                                        update_stats, target_method, direct_code, direct_method);
1267          return true;
1268        }
1269      }
1270    }
1271  }
1272  // Clean up any exception left by method/invoke_type resolution
1273  if (soa.Self()->IsExceptionPending()) {
1274      soa.Self()->ClearException();
1275  }
1276  if (update_stats) {
1277    stats_->UnresolvedMethod(*invoke_type);
1278  }
1279  return false;  // Incomplete knowledge needs slow path.
1280}
1281
1282const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1283                                                        uint32_t method_idx) const {
1284  MethodReference ref(dex_file, method_idx);
1285  return verification_results_->GetVerifiedMethod(ref);
1286}
1287
1288bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
1289  DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1290  bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
1291  if (result) {
1292    stats_->SafeCast();
1293  } else {
1294    stats_->NotASafeCast();
1295  }
1296  return result;
1297}
1298
1299
1300void CompilerDriver::AddCodePatch(const DexFile* dex_file,
1301                                  uint16_t referrer_class_def_idx,
1302                                  uint32_t referrer_method_idx,
1303                                  InvokeType referrer_invoke_type,
1304                                  uint32_t target_method_idx,
1305                                  InvokeType target_invoke_type,
1306                                  size_t literal_offset) {
1307  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1308  code_to_patch_.push_back(new CallPatchInformation(dex_file,
1309                                                    referrer_class_def_idx,
1310                                                    referrer_method_idx,
1311                                                    referrer_invoke_type,
1312                                                    target_method_idx,
1313                                                    target_invoke_type,
1314                                                    literal_offset));
1315}
1316void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1317                                          uint16_t referrer_class_def_idx,
1318                                          uint32_t referrer_method_idx,
1319                                          InvokeType referrer_invoke_type,
1320                                          uint32_t target_method_idx,
1321                                          InvokeType target_invoke_type,
1322                                          size_t literal_offset,
1323                                          int32_t pc_relative_offset) {
1324  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1325  code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1326                                                            referrer_class_def_idx,
1327                                                            referrer_method_idx,
1328                                                            referrer_invoke_type,
1329                                                            target_method_idx,
1330                                                            target_invoke_type,
1331                                                            literal_offset,
1332                                                            pc_relative_offset));
1333}
1334void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
1335                                    uint16_t referrer_class_def_idx,
1336                                    uint32_t referrer_method_idx,
1337                                    InvokeType referrer_invoke_type,
1338                                    uint32_t target_method_idx,
1339                                    InvokeType target_invoke_type,
1340                                    size_t literal_offset) {
1341  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1342  methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1343                                                       referrer_class_def_idx,
1344                                                       referrer_method_idx,
1345                                                       referrer_invoke_type,
1346                                                       target_method_idx,
1347                                                       target_invoke_type,
1348                                                       literal_offset));
1349}
1350void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1351                                    uint16_t referrer_class_def_idx,
1352                                    uint32_t referrer_method_idx,
1353                                    uint32_t target_type_idx,
1354                                    size_t literal_offset) {
1355  MutexLock mu(Thread::Current(), compiled_methods_lock_);
1356  classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1357                                                       referrer_class_def_idx,
1358                                                       referrer_method_idx,
1359                                                       target_type_idx,
1360                                                       literal_offset));
1361}
1362
1363class ParallelCompilationManager {
1364 public:
1365  typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1366
1367  ParallelCompilationManager(ClassLinker* class_linker,
1368                             jobject class_loader,
1369                             CompilerDriver* compiler,
1370                             const DexFile* dex_file,
1371                             ThreadPool* thread_pool)
1372    : index_(0),
1373      class_linker_(class_linker),
1374      class_loader_(class_loader),
1375      compiler_(compiler),
1376      dex_file_(dex_file),
1377      thread_pool_(thread_pool) {}
1378
1379  ClassLinker* GetClassLinker() const {
1380    CHECK(class_linker_ != NULL);
1381    return class_linker_;
1382  }
1383
1384  jobject GetClassLoader() const {
1385    return class_loader_;
1386  }
1387
1388  CompilerDriver* GetCompiler() const {
1389    CHECK(compiler_ != NULL);
1390    return compiler_;
1391  }
1392
1393  const DexFile* GetDexFile() const {
1394    CHECK(dex_file_ != NULL);
1395    return dex_file_;
1396  }
1397
1398  void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1399    Thread* self = Thread::Current();
1400    self->AssertNoPendingException();
1401    CHECK_GT(work_units, 0U);
1402
1403    index_ = begin;
1404    for (size_t i = 0; i < work_units; ++i) {
1405      thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
1406    }
1407    thread_pool_->StartWorkers(self);
1408
1409    // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1410    // thread destructor's called below perform join).
1411    CHECK_NE(self->GetState(), kRunnable);
1412
1413    // Wait for all the worker threads to finish.
1414    thread_pool_->Wait(self, true, false);
1415  }
1416
1417  size_t NextIndex() {
1418    return index_.FetchAndAdd(1);
1419  }
1420
1421 private:
1422  class ForAllClosure : public Task {
1423   public:
1424    ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
1425        : manager_(manager),
1426          end_(end),
1427          callback_(callback) {}
1428
1429    virtual void Run(Thread* self) {
1430      while (true) {
1431        const size_t index = manager_->NextIndex();
1432        if (UNLIKELY(index >= end_)) {
1433          break;
1434        }
1435        callback_(manager_, index);
1436        self->AssertNoPendingException();
1437      }
1438    }
1439
1440    virtual void Finalize() {
1441      delete this;
1442    }
1443
1444   private:
1445    ParallelCompilationManager* const manager_;
1446    const size_t end_;
1447    Callback* const callback_;
1448  };
1449
1450  AtomicInteger index_;
1451  ClassLinker* const class_linker_;
1452  const jobject class_loader_;
1453  CompilerDriver* const compiler_;
1454  const DexFile* const dex_file_;
1455  ThreadPool* const thread_pool_;
1456
1457  DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
1458};
1459
1460// Return true if the class should be skipped during compilation.
1461//
1462// The first case where we skip is for redundant class definitions in
1463// the boot classpath. We skip all but the first definition in that case.
1464//
1465// The second case where we skip is when an app bundles classes found
1466// in the boot classpath. Since at runtime we will select the class from
1467// the boot classpath, we ignore the one from the app.
1468static bool SkipClass(ClassLinker* class_linker, jobject class_loader, const DexFile& dex_file,
1469                      const DexFile::ClassDef& class_def) {
1470  const char* descriptor = dex_file.GetClassDescriptor(class_def);
1471  if (class_loader == NULL) {
1472    DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_linker->GetBootClassPath());
1473    CHECK(pair.second != NULL);
1474    if (pair.first != &dex_file) {
1475      LOG(WARNING) << "Skipping class " << descriptor << " from " << dex_file.GetLocation()
1476                   << " previously found in " << pair.first->GetLocation();
1477      return true;
1478    }
1479    return false;
1480  }
1481  return class_linker->IsInBootClassPath(descriptor);
1482}
1483
1484// A fast version of SkipClass above if the class pointer is available
1485// that avoids the expensive FindInClassPath search.
1486static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1487    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1488  DCHECK(klass != NULL);
1489  const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1490  if (&dex_file != &original_dex_file) {
1491    if (class_loader == NULL) {
1492      LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1493                   << dex_file.GetLocation() << " previously found in "
1494                   << original_dex_file.GetLocation();
1495    }
1496    return true;
1497  }
1498  return false;
1499}
1500
1501static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1502                                         size_t class_def_index)
1503    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1504  ATRACE_CALL();
1505  Thread* self = Thread::Current();
1506  jobject jclass_loader = manager->GetClassLoader();
1507  const DexFile& dex_file = *manager->GetDexFile();
1508  ClassLinker* class_linker = manager->GetClassLinker();
1509
1510  // If an instance field is final then we need to have a barrier on the return, static final
1511  // fields are assigned within the lock held for class initialization. Conservatively assume
1512  // constructor barriers are always required.
1513  bool requires_constructor_barrier = true;
1514
1515  // Method and Field are the worst. We can't resolve without either
1516  // context from the code use (to disambiguate virtual vs direct
1517  // method and instance vs static field) or from class
1518  // definitions. While the compiler will resolve what it can as it
1519  // needs it, here we try to resolve fields and methods used in class
1520  // definitions, since many of them many never be referenced by
1521  // generated code.
1522  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1523  if (!SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
1524    ScopedObjectAccess soa(self);
1525    SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
1526    SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
1527    // Resolve the class.
1528    mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1529                                                     class_loader);
1530    bool resolve_fields_and_methods;
1531    if (klass == NULL) {
1532      // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1533      // attempt to resolve methods and fields when there is no declaring class.
1534      CHECK(soa.Self()->IsExceptionPending());
1535      soa.Self()->ClearException();
1536      resolve_fields_and_methods = false;
1537    } else {
1538      resolve_fields_and_methods = manager->GetCompiler()->IsImage();
1539    }
1540    // Note the class_data pointer advances through the headers,
1541    // static fields, instance fields, direct methods, and virtual
1542    // methods.
1543    const byte* class_data = dex_file.GetClassData(class_def);
1544    if (class_data == NULL) {
1545      // Empty class such as a marker interface.
1546      requires_constructor_barrier = false;
1547    } else {
1548      ClassDataItemIterator it(dex_file, class_data);
1549      while (it.HasNextStaticField()) {
1550        if (resolve_fields_and_methods) {
1551          mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1552                                                               dex_cache, class_loader, true);
1553          if (field == NULL) {
1554            CHECK(soa.Self()->IsExceptionPending());
1555            soa.Self()->ClearException();
1556          }
1557        }
1558        it.Next();
1559      }
1560      // We require a constructor barrier if there are final instance fields.
1561      requires_constructor_barrier = false;
1562      while (it.HasNextInstanceField()) {
1563        if ((it.GetMemberAccessFlags() & kAccFinal) != 0) {
1564          requires_constructor_barrier = true;
1565        }
1566        if (resolve_fields_and_methods) {
1567          mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1568                                                               dex_cache, class_loader, false);
1569          if (field == NULL) {
1570            CHECK(soa.Self()->IsExceptionPending());
1571            soa.Self()->ClearException();
1572          }
1573        }
1574        it.Next();
1575      }
1576      if (resolve_fields_and_methods) {
1577        while (it.HasNextDirectMethod()) {
1578          mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1579                                                                  dex_cache, class_loader, NULL,
1580                                                                  it.GetMethodInvokeType(class_def));
1581          if (method == NULL) {
1582            CHECK(soa.Self()->IsExceptionPending());
1583            soa.Self()->ClearException();
1584          }
1585          it.Next();
1586        }
1587        while (it.HasNextVirtualMethod()) {
1588          mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1589                                                                  dex_cache, class_loader, NULL,
1590                                                                  it.GetMethodInvokeType(class_def));
1591          if (method == NULL) {
1592            CHECK(soa.Self()->IsExceptionPending());
1593            soa.Self()->ClearException();
1594          }
1595          it.Next();
1596        }
1597        DCHECK(!it.HasNext());
1598      }
1599    }
1600  }
1601  if (requires_constructor_barrier) {
1602    manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
1603  }
1604}
1605
1606static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1607    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1608  // Class derived values are more complicated, they require the linker and loader.
1609  ScopedObjectAccess soa(Thread::Current());
1610  ClassLinker* class_linker = manager->GetClassLinker();
1611  const DexFile& dex_file = *manager->GetDexFile();
1612  SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
1613  SirtRef<mirror::ClassLoader> class_loader(
1614      soa.Self(), soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader()));
1615  mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1616
1617  if (klass == NULL) {
1618    CHECK(soa.Self()->IsExceptionPending());
1619    mirror::Throwable* exception = soa.Self()->GetException(NULL);
1620    VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1621    if (strcmp("Ljava/lang/OutOfMemoryError;",
1622               ClassHelper(exception->GetClass()).GetDescriptor()) == 0) {
1623      // There's little point continuing compilation if the heap is exhausted.
1624      LOG(FATAL) << "Out of memory during type resolution for compilation";
1625    }
1626    soa.Self()->ClearException();
1627  }
1628}
1629
1630void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
1631                                    ThreadPool* thread_pool, TimingLogger* timings) {
1632  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1633
1634  // TODO: we could resolve strings here, although the string table is largely filled with class
1635  //       and method names.
1636
1637  ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1638  if (IsImage()) {
1639    // For images we resolve all types, such as array, whereas for applications just those with
1640    // classdefs are resolved by ResolveClassFieldsAndMethods.
1641    timings->NewSplit("Resolve Types");
1642    context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1643  }
1644
1645  timings->NewSplit("Resolve MethodsAndFields");
1646  context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
1647}
1648
1649void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1650                            ThreadPool* thread_pool, TimingLogger* timings) {
1651  for (size_t i = 0; i != dex_files.size(); ++i) {
1652    const DexFile* dex_file = dex_files[i];
1653    CHECK(dex_file != NULL);
1654    VerifyDexFile(class_loader, *dex_file, thread_pool, timings);
1655  }
1656}
1657
1658static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1659    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1660  ATRACE_CALL();
1661  ScopedObjectAccess soa(Thread::Current());
1662  const DexFile& dex_file = *manager->GetDexFile();
1663  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1664  const char* descriptor = dex_file.GetClassDescriptor(class_def);
1665  ClassLinker* class_linker = manager->GetClassLinker();
1666  jobject jclass_loader = manager->GetClassLoader();
1667  SirtRef<mirror::ClassLoader> class_loader(
1668      soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
1669  SirtRef<mirror::Class> klass(soa.Self(), class_linker->FindClass(soa.Self(), descriptor,
1670                                                                   class_loader));
1671  if (klass.get() == nullptr) {
1672    CHECK(soa.Self()->IsExceptionPending());
1673    soa.Self()->ClearException();
1674
1675    /*
1676     * At compile time, we can still structurally verify the class even if FindClass fails.
1677     * This is to ensure the class is structurally sound for compilation. An unsound class
1678     * will be rejected by the verifier and later skipped during compilation in the compiler.
1679     */
1680    SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
1681    std::string error_msg;
1682    if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1683                                              &error_msg) ==
1684                                                  verifier::MethodVerifier::kHardFailure) {
1685      LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
1686                 << " because: " << error_msg;
1687    }
1688  } else if (!SkipClass(jclass_loader, dex_file, klass.get())) {
1689    CHECK(klass->IsResolved()) << PrettyClass(klass.get());
1690    class_linker->VerifyClass(klass);
1691
1692    if (klass->IsErroneous()) {
1693      // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1694      CHECK(soa.Self()->IsExceptionPending());
1695      soa.Self()->ClearException();
1696    }
1697
1698    CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
1699        << PrettyDescriptor(klass.get()) << ": state=" << klass->GetStatus();
1700  }
1701  soa.Self()->AssertNoPendingException();
1702}
1703
1704void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
1705                                   ThreadPool* thread_pool, TimingLogger* timings) {
1706  timings->NewSplit("Verify Dex File");
1707  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1708  ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1709  context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
1710}
1711
1712static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1713    LOCKS_EXCLUDED(Locks::mutator_lock_) {
1714  ATRACE_CALL();
1715  jobject jclass_loader = manager->GetClassLoader();
1716  const DexFile& dex_file = *manager->GetDexFile();
1717  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1718  const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1719  const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
1720
1721  ScopedObjectAccess soa(Thread::Current());
1722  SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1723                                            soa.Decode<mirror::ClassLoader*>(jclass_loader));
1724  SirtRef<mirror::Class> klass(soa.Self(),
1725                               manager->GetClassLinker()->FindClass(soa.Self(), descriptor,
1726                                                                    class_loader));
1727
1728  if (klass.get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.get())) {
1729    // Only try to initialize classes that were successfully verified.
1730    if (klass->IsVerified()) {
1731      // Attempt to initialize the class but bail if we either need to initialize the super-class
1732      // or static fields.
1733      manager->GetClassLinker()->EnsureInitialized(klass, false, false);
1734      if (!klass->IsInitialized()) {
1735        // We don't want non-trivial class initialization occurring on multiple threads due to
1736        // deadlock problems. For example, a parent class is initialized (holding its lock) that
1737        // refers to a sub-class in its static/class initializer causing it to try to acquire the
1738        // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1739        // after first initializing its parents, whose locks are acquired. This leads to a
1740        // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1741        // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1742        // than use a special Object for the purpose we use the Class of java.lang.Class.
1743        SirtRef<mirror::Class> sirt_klass(soa.Self(), klass->GetClass());
1744        ObjectLock<mirror::Class> lock(soa.Self(), &sirt_klass);
1745        // Attempt to initialize allowing initialization of parent classes but still not static
1746        // fields.
1747        manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1748        if (!klass->IsInitialized()) {
1749          // We need to initialize static fields, we only do this for image classes that aren't
1750          // marked with the $NoPreloadHolder (which implies this should not be initialized early).
1751          bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
1752              manager->GetCompiler()->IsImageClass(descriptor) &&
1753              !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
1754          if (can_init_static_fields) {
1755            VLOG(compiler) << "Initializing: " << descriptor;
1756            if (strcmp("Ljava/lang/Void;", descriptor) == 0) {
1757              // Hand initialize j.l.Void to avoid Dex file operations in un-started runtime.
1758              ObjectLock<mirror::Class> lock(soa.Self(), &klass);
1759              mirror::ObjectArray<mirror::ArtField>* fields = klass->GetSFields();
1760              CHECK_EQ(fields->GetLength(), 1);
1761              fields->Get(0)->SetObj<false>(klass.get(),
1762                                                     manager->GetClassLinker()->FindPrimitiveClass('V'));
1763              klass->SetStatus(mirror::Class::kStatusInitialized, soa.Self());
1764            } else {
1765              // TODO multithreading support. We should ensure the current compilation thread has
1766              // exclusive access to the runtime and the transaction. To achieve this, we could use
1767              // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1768              // checks in Thread::AssertThreadSuspensionIsAllowable.
1769              Runtime* const runtime = Runtime::Current();
1770              Transaction transaction;
1771
1772              // Run the class initializer in transaction mode.
1773              runtime->EnterTransactionMode(&transaction);
1774              const mirror::Class::Status old_status = klass->GetStatus();
1775              bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1776              // TODO we detach transaction from runtime to indicate we quit the transactional
1777              // mode which prevents the GC from visiting objects modified during the transaction.
1778              // Ensure GC is not run so don't access freed objects when aborting transaction.
1779              const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1780              runtime->ExitTransactionMode();
1781
1782              if (!success) {
1783                CHECK(soa.Self()->IsExceptionPending());
1784                ThrowLocation throw_location;
1785                mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1786                VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1787                               << exception->Dump();
1788                soa.Self()->ClearException();
1789                transaction.Abort();
1790                CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
1791              }
1792              soa.Self()->EndAssertNoThreadSuspension(old_casue);
1793            }
1794          }
1795        }
1796        soa.Self()->AssertNoPendingException();
1797      }
1798    }
1799    // Record the final class status if necessary.
1800    ClassReference ref(manager->GetDexFile(), class_def_index);
1801    manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
1802  }
1803  // Clear any class not found or verification exceptions.
1804  soa.Self()->ClearException();
1805}
1806
1807void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
1808                                       ThreadPool* thread_pool, TimingLogger* timings) {
1809  timings->NewSplit("InitializeNoClinit");
1810  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1811  ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, thread_pool);
1812  size_t thread_count;
1813  if (IsImage()) {
1814    // TODO: remove this when transactional mode supports multithreading.
1815    thread_count = 1U;
1816  } else {
1817    thread_count = thread_count_;
1818  }
1819  context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
1820  if (IsImage()) {
1821    // Prune garbage objects created during aborted transactions.
1822    Runtime::Current()->GetHeap()->CollectGarbage(true);
1823  }
1824}
1825
1826void CompilerDriver::InitializeClasses(jobject class_loader,
1827                                       const std::vector<const DexFile*>& dex_files,
1828                                       ThreadPool* thread_pool, TimingLogger* timings) {
1829  for (size_t i = 0; i != dex_files.size(); ++i) {
1830    const DexFile* dex_file = dex_files[i];
1831    CHECK(dex_file != NULL);
1832    InitializeClasses(class_loader, *dex_file, thread_pool, timings);
1833  }
1834}
1835
1836void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
1837                             ThreadPool* thread_pool, TimingLogger* timings) {
1838  for (size_t i = 0; i != dex_files.size(); ++i) {
1839    const DexFile* dex_file = dex_files[i];
1840    CHECK(dex_file != NULL);
1841    CompileDexFile(class_loader, *dex_file, thread_pool, timings);
1842  }
1843}
1844
1845void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
1846  ATRACE_CALL();
1847  jobject jclass_loader = manager->GetClassLoader();
1848  const DexFile& dex_file = *manager->GetDexFile();
1849  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1850  ClassLinker* class_linker = manager->GetClassLinker();
1851  if (SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
1852    return;
1853  }
1854  ClassReference ref(&dex_file, class_def_index);
1855  // Skip compiling classes with generic verifier failures since they will still fail at runtime
1856  if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
1857    return;
1858  }
1859  const byte* class_data = dex_file.GetClassData(class_def);
1860  if (class_data == NULL) {
1861    // empty class, probably a marker interface
1862    return;
1863  }
1864
1865  // Can we run DEX-to-DEX compiler on this class ?
1866  DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
1867  {
1868    ScopedObjectAccess soa(Thread::Current());
1869    SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1870                                              soa.Decode<mirror::ClassLoader*>(jclass_loader));
1871    dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
1872                                                               class_def);
1873  }
1874  ClassDataItemIterator it(dex_file, class_data);
1875  // Skip fields
1876  while (it.HasNextStaticField()) {
1877    it.Next();
1878  }
1879  while (it.HasNextInstanceField()) {
1880    it.Next();
1881  }
1882  CompilerDriver* driver = manager->GetCompiler();
1883  // Compile direct methods
1884  int64_t previous_direct_method_idx = -1;
1885  while (it.HasNextDirectMethod()) {
1886    uint32_t method_idx = it.GetMemberIndex();
1887    if (method_idx == previous_direct_method_idx) {
1888      // smali can create dex files with two encoded_methods sharing the same method_idx
1889      // http://code.google.com/p/smali/issues/detail?id=119
1890      it.Next();
1891      continue;
1892    }
1893    previous_direct_method_idx = method_idx;
1894    driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1895                          it.GetMethodInvokeType(class_def), class_def_index,
1896                          method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
1897    it.Next();
1898  }
1899  // Compile virtual methods
1900  int64_t previous_virtual_method_idx = -1;
1901  while (it.HasNextVirtualMethod()) {
1902    uint32_t method_idx = it.GetMemberIndex();
1903    if (method_idx == previous_virtual_method_idx) {
1904      // smali can create dex files with two encoded_methods sharing the same method_idx
1905      // http://code.google.com/p/smali/issues/detail?id=119
1906      it.Next();
1907      continue;
1908    }
1909    previous_virtual_method_idx = method_idx;
1910    driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1911                          it.GetMethodInvokeType(class_def), class_def_index,
1912                          method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
1913    it.Next();
1914  }
1915  DCHECK(!it.HasNext());
1916}
1917
1918void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
1919                                    ThreadPool* thread_pool, TimingLogger* timings) {
1920  timings->NewSplit("Compile Dex File");
1921  ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
1922                                     &dex_file, thread_pool);
1923  context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
1924}
1925
1926void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1927                                   InvokeType invoke_type, uint16_t class_def_idx,
1928                                   uint32_t method_idx, jobject class_loader,
1929                                   const DexFile& dex_file,
1930                                   DexToDexCompilationLevel dex_to_dex_compilation_level) {
1931  CompiledMethod* compiled_method = NULL;
1932  uint64_t start_ns = NanoTime();
1933
1934  if ((access_flags & kAccNative) != 0) {
1935    compiled_method = compiler_backend_->JniCompile(*this, access_flags, method_idx, dex_file);
1936    CHECK(compiled_method != NULL);
1937  } else if ((access_flags & kAccAbstract) != 0) {
1938  } else {
1939    MethodReference method_ref(&dex_file, method_idx);
1940    bool compile = verification_results_->IsCandidateForCompilation(method_ref, access_flags);
1941
1942    if (compile) {
1943      // NOTE: if compiler declines to compile this method, it will return NULL.
1944      compiled_method = compiler_backend_->Compile(
1945          *this, code_item, access_flags, invoke_type, class_def_idx,
1946          method_idx, class_loader, dex_file);
1947    } else if (dex_to_dex_compilation_level != kDontDexToDexCompile) {
1948      // TODO: add a mode to disable DEX-to-DEX compilation ?
1949      (*dex_to_dex_compiler_)(*this, code_item, access_flags,
1950                              invoke_type, class_def_idx,
1951                              method_idx, class_loader, dex_file,
1952                              dex_to_dex_compilation_level);
1953    }
1954  }
1955  uint64_t duration_ns = NanoTime() - start_ns;
1956  if (duration_ns > MsToNs(compiler_backend_->GetMaximumCompilationTimeBeforeWarning())) {
1957    LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
1958                 << " took " << PrettyDuration(duration_ns);
1959  }
1960
1961  Thread* self = Thread::Current();
1962  if (compiled_method != NULL) {
1963    MethodReference ref(&dex_file, method_idx);
1964    DCHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
1965    {
1966      MutexLock mu(self, compiled_methods_lock_);
1967      compiled_methods_.Put(ref, compiled_method);
1968    }
1969    DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
1970  }
1971
1972  if (self->IsExceptionPending()) {
1973    ScopedObjectAccess soa(self);
1974    LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
1975        << self->GetException(NULL)->Dump();
1976  }
1977}
1978
1979CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
1980  MutexLock mu(Thread::Current(), compiled_classes_lock_);
1981  ClassTable::const_iterator it = compiled_classes_.find(ref);
1982  if (it == compiled_classes_.end()) {
1983    return NULL;
1984  }
1985  CHECK(it->second != NULL);
1986  return it->second;
1987}
1988
1989void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
1990  MutexLock mu(Thread::Current(), compiled_classes_lock_);
1991  auto it = compiled_classes_.find(ref);
1992  if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
1993    // An entry doesn't exist or the status is lower than the new status.
1994    if (it != compiled_classes_.end()) {
1995      CHECK_GT(status, it->second->GetStatus());
1996      delete it->second;
1997    }
1998    switch (status) {
1999      case mirror::Class::kStatusNotReady:
2000      case mirror::Class::kStatusError:
2001      case mirror::Class::kStatusRetryVerificationAtRuntime:
2002      case mirror::Class::kStatusVerified:
2003      case mirror::Class::kStatusInitialized:
2004        break;  // Expected states.
2005      default:
2006        LOG(FATAL) << "Unexpected class status for class "
2007            << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2008            << " of " << status;
2009    }
2010    CompiledClass* compiled_class = new CompiledClass(status);
2011    compiled_classes_.Overwrite(ref, compiled_class);
2012  }
2013}
2014
2015CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2016  MutexLock mu(Thread::Current(), compiled_methods_lock_);
2017  MethodTable::const_iterator it = compiled_methods_.find(ref);
2018  if (it == compiled_methods_.end()) {
2019    return NULL;
2020  }
2021  CHECK(it->second != NULL);
2022  return it->second;
2023}
2024
2025void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
2026                                                   uint16_t class_def_index) {
2027  WriterMutexLock mu(self, freezing_constructor_lock_);
2028  freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
2029}
2030
2031bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
2032                                                uint16_t class_def_index) {
2033  ReaderMutexLock mu(self, freezing_constructor_lock_);
2034  return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
2035}
2036
2037bool CompilerDriver::WriteElf(const std::string& android_root,
2038                              bool is_host,
2039                              const std::vector<const art::DexFile*>& dex_files,
2040                              OatWriter* oat_writer,
2041                              art::File* file)
2042    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2043  return compiler_backend_->WriteElf(file, oat_writer, dex_files, android_root, is_host, *this);
2044}
2045void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
2046                                                std::string* target_triple,
2047                                                std::string* target_cpu,
2048                                                std::string* target_attr) {
2049  switch (instruction_set) {
2050    case kThumb2:
2051      *target_triple = "thumb-none-linux-gnueabi";
2052      *target_cpu = "cortex-a9";
2053      *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
2054      break;
2055
2056    case kArm:
2057      *target_triple = "armv7-none-linux-gnueabi";
2058      // TODO: Fix for Nexus S.
2059      *target_cpu = "cortex-a9";
2060      // TODO: Fix for Xoom.
2061      *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
2062      break;
2063
2064    case kX86:
2065      *target_triple = "i386-pc-linux-gnu";
2066      *target_attr = "";
2067      break;
2068
2069    case kMips:
2070      *target_triple = "mipsel-unknown-linux";
2071      *target_attr = "mips32r2";
2072      break;
2073
2074    default:
2075      LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2076    }
2077  }
2078}  // namespace art
2079