Home | History | Annotate | Download | only in driver
      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 #ifndef ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
     18 #define ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
     19 
     20 #include <atomic>
     21 #include <set>
     22 #include <string>
     23 #include <unordered_set>
     24 #include <vector>
     25 
     26 #include "android-base/strings.h"
     27 
     28 #include "arch/instruction_set.h"
     29 #include "base/array_ref.h"
     30 #include "base/bit_utils.h"
     31 #include "base/mutex.h"
     32 #include "base/os.h"
     33 #include "base/quasi_atomic.h"
     34 #include "base/safe_map.h"
     35 #include "base/timing_logger.h"
     36 #include "class_status.h"
     37 #include "compiler.h"
     38 #include "dex/class_reference.h"
     39 #include "dex/dex_file.h"
     40 #include "dex/dex_file_types.h"
     41 #include "dex/dex_to_dex_compiler.h"
     42 #include "dex/method_reference.h"
     43 #include "driver/compiled_method_storage.h"
     44 #include "thread_pool.h"
     45 #include "utils/atomic_dex_ref_map.h"
     46 #include "utils/dex_cache_arrays_layout.h"
     47 
     48 namespace art {
     49 
     50 namespace mirror {
     51 class Class;
     52 class DexCache;
     53 }  // namespace mirror
     54 
     55 namespace verifier {
     56 class MethodVerifier;
     57 class VerifierDepsTest;
     58 }  // namespace verifier
     59 
     60 class ArtField;
     61 class BitVector;
     62 class CompiledMethod;
     63 class CompilerOptions;
     64 class DexCompilationUnit;
     65 template<class T> class Handle;
     66 struct InlineIGetIPutData;
     67 class InstructionSetFeatures;
     68 class InternTable;
     69 enum InvokeType : uint32_t;
     70 class MemberOffset;
     71 template<class MirrorType> class ObjPtr;
     72 class ParallelCompilationManager;
     73 class ProfileCompilationInfo;
     74 class ScopedObjectAccess;
     75 template <class Allocator> class SrcMap;
     76 class TimingLogger;
     77 class VdexFile;
     78 class VerificationResults;
     79 class VerifiedMethod;
     80 
     81 enum EntryPointCallingConvention {
     82   // ABI of invocations to a method's interpreter entry point.
     83   kInterpreterAbi,
     84   // ABI of calls to a method's native code, only used for native methods.
     85   kJniAbi,
     86   // ABI of calls to a method's quick code entry point.
     87   kQuickAbi
     88 };
     89 
     90 class CompilerDriver {
     91  public:
     92   // Create a compiler targeting the requested "instruction_set".
     93   // "image" should be true if image specific optimizations should be
     94   // enabled.  "image_classes" lets the compiler know what classes it
     95   // can assume will be in the image, with null implying all available
     96   // classes.
     97   CompilerDriver(const CompilerOptions* compiler_options,
     98                  VerificationResults* verification_results,
     99                  Compiler::Kind compiler_kind,
    100                  InstructionSet instruction_set,
    101                  const InstructionSetFeatures* instruction_set_features,
    102                  std::unordered_set<std::string>* image_classes,
    103                  std::unordered_set<std::string>* compiled_classes,
    104                  std::unordered_set<std::string>* compiled_methods,
    105                  size_t thread_count,
    106                  int swap_fd,
    107                  const ProfileCompilationInfo* profile_compilation_info);
    108 
    109   ~CompilerDriver();
    110 
    111   // Set dex files associated with the oat file being compiled.
    112   void SetDexFilesForOatFile(const std::vector<const DexFile*>& dex_files);
    113 
    114   // Set dex files classpath.
    115   void SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files);
    116 
    117   // Get dex files associated with the the oat file being compiled.
    118   ArrayRef<const DexFile* const> GetDexFilesForOatFile() const {
    119     return ArrayRef<const DexFile* const>(dex_files_for_oat_file_);
    120   }
    121 
    122   void CompileAll(jobject class_loader,
    123                   const std::vector<const DexFile*>& dex_files,
    124                   TimingLogger* timings)
    125       REQUIRES(!Locks::mutator_lock_);
    126 
    127   // Compile a single Method.
    128   void CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings)
    129       REQUIRES_SHARED(Locks::mutator_lock_);
    130 
    131   VerificationResults* GetVerificationResults() const;
    132 
    133   InstructionSet GetInstructionSet() const {
    134     return instruction_set_;
    135   }
    136 
    137   const InstructionSetFeatures* GetInstructionSetFeatures() const {
    138     return instruction_set_features_;
    139   }
    140 
    141   const CompilerOptions& GetCompilerOptions() const {
    142     return *compiler_options_;
    143   }
    144 
    145   Compiler* GetCompiler() const {
    146     return compiler_.get();
    147   }
    148 
    149   const std::unordered_set<std::string>* GetImageClasses() const {
    150     return image_classes_.get();
    151   }
    152 
    153   // Generate the trampolines that are invoked by unresolved direct methods.
    154   std::unique_ptr<const std::vector<uint8_t>> CreateJniDlsymLookup() const;
    155   std::unique_ptr<const std::vector<uint8_t>> CreateQuickGenericJniTrampoline() const;
    156   std::unique_ptr<const std::vector<uint8_t>> CreateQuickImtConflictTrampoline() const;
    157   std::unique_ptr<const std::vector<uint8_t>> CreateQuickResolutionTrampoline() const;
    158   std::unique_ptr<const std::vector<uint8_t>> CreateQuickToInterpreterBridge() const;
    159 
    160   ClassStatus GetClassStatus(const ClassReference& ref) const;
    161   bool GetCompiledClass(const ClassReference& ref, ClassStatus* status) const;
    162 
    163   CompiledMethod* GetCompiledMethod(MethodReference ref) const;
    164   size_t GetNonRelativeLinkerPatchCount() const;
    165   // Add a compiled method.
    166   void AddCompiledMethod(const MethodReference& method_ref,
    167                          CompiledMethod* const compiled_method,
    168                          size_t non_relative_linker_patch_count);
    169   CompiledMethod* RemoveCompiledMethod(const MethodReference& method_ref);
    170 
    171   void SetRequiresConstructorBarrier(Thread* self,
    172                                      const DexFile* dex_file,
    173                                      uint16_t class_def_index,
    174                                      bool requires)
    175       REQUIRES(!requires_constructor_barrier_lock_);
    176 
    177   // Do the <init> methods for this class require a constructor barrier (prior to the return)?
    178   // The answer is "yes", if and only if this class has any instance final fields.
    179   // (This must not be called for any non-<init> methods; the answer would be "no").
    180   //
    181   // ---
    182   //
    183   // JLS 17.5.1 "Semantics of final fields" mandates that all final fields are frozen at the end
    184   // of the invoked constructor. The constructor barrier is a conservative implementation means of
    185   // enforcing the freezes happen-before the object being constructed is observable by another
    186   // thread.
    187   //
    188   // Note: This question only makes sense for instance constructors;
    189   // static constructors (despite possibly having finals) never need
    190   // a barrier.
    191   //
    192   // JLS 12.4.2 "Detailed Initialization Procedure" approximately describes
    193   // class initialization as:
    194   //
    195   //   lock(class.lock)
    196   //     class.state = initializing
    197   //   unlock(class.lock)
    198   //
    199   //   invoke <clinit>
    200   //
    201   //   lock(class.lock)
    202   //     class.state = initialized
    203   //   unlock(class.lock)              <-- acts as a release
    204   //
    205   // The last operation in the above example acts as an atomic release
    206   // for any stores in <clinit>, which ends up being stricter
    207   // than what a constructor barrier needs.
    208   //
    209   // See also QuasiAtomic::ThreadFenceForConstructor().
    210   bool RequiresConstructorBarrier(Thread* self,
    211                                   const DexFile* dex_file,
    212                                   uint16_t class_def_index)
    213       REQUIRES(!requires_constructor_barrier_lock_);
    214 
    215   // Are runtime access checks necessary in the compiled code?
    216   bool CanAccessTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
    217                                   ObjPtr<mirror::Class> resolved_class)
    218       REQUIRES_SHARED(Locks::mutator_lock_);
    219 
    220   // Are runtime access and instantiable checks necessary in the code?
    221   // out_is_finalizable is set to whether the type is finalizable.
    222   bool CanAccessInstantiableTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
    223                                               ObjPtr<mirror::Class> resolved_class,
    224                                               bool* out_is_finalizable)
    225       REQUIRES_SHARED(Locks::mutator_lock_);
    226 
    227   // Resolve compiling method's class. Returns null on failure.
    228   ObjPtr<mirror::Class> ResolveCompilingMethodsClass(const ScopedObjectAccess& soa,
    229                                                      Handle<mirror::DexCache> dex_cache,
    230                                                      Handle<mirror::ClassLoader> class_loader,
    231                                                      const DexCompilationUnit* mUnit)
    232       REQUIRES_SHARED(Locks::mutator_lock_);
    233 
    234   ObjPtr<mirror::Class> ResolveClass(const ScopedObjectAccess& soa,
    235                                      Handle<mirror::DexCache> dex_cache,
    236                                      Handle<mirror::ClassLoader> class_loader,
    237                                      dex::TypeIndex type_index,
    238                                      const DexCompilationUnit* mUnit)
    239       REQUIRES_SHARED(Locks::mutator_lock_);
    240 
    241   // Resolve a field. Returns null on failure, including incompatible class change.
    242   // NOTE: Unlike ClassLinker's ResolveField(), this method enforces is_static.
    243   ArtField* ResolveField(const ScopedObjectAccess& soa,
    244                          Handle<mirror::DexCache> dex_cache,
    245                          Handle<mirror::ClassLoader> class_loader,
    246                          uint32_t field_idx,
    247                          bool is_static)
    248       REQUIRES_SHARED(Locks::mutator_lock_);
    249 
    250   // Can we fast-path an IGET/IPUT access to an instance field? If yes, compute the field offset.
    251   std::pair<bool, bool> IsFastInstanceField(ObjPtr<mirror::DexCache> dex_cache,
    252                                             ObjPtr<mirror::Class> referrer_class,
    253                                             ArtField* resolved_field,
    254                                             uint16_t field_idx)
    255       REQUIRES_SHARED(Locks::mutator_lock_);
    256 
    257   // Resolve a method. Returns null on failure, including incompatible class change.
    258   ArtMethod* ResolveMethod(
    259       ScopedObjectAccess& soa,
    260       Handle<mirror::DexCache> dex_cache,
    261       Handle<mirror::ClassLoader> class_loader,
    262       const DexCompilationUnit* mUnit,
    263       uint32_t method_idx,
    264       InvokeType invoke_type)
    265       REQUIRES_SHARED(Locks::mutator_lock_);
    266 
    267   void ProcessedInstanceField(bool resolved);
    268   void ProcessedStaticField(bool resolved, bool local);
    269 
    270   // Can we fast path instance field access? Computes field's offset and volatility.
    271   bool ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit, bool is_put,
    272                                 MemberOffset* field_offset, bool* is_volatile)
    273       REQUIRES(!Locks::mutator_lock_);
    274 
    275   ArtField* ComputeInstanceFieldInfo(uint32_t field_idx,
    276                                      const DexCompilationUnit* mUnit,
    277                                      bool is_put,
    278                                      const ScopedObjectAccess& soa)
    279       REQUIRES_SHARED(Locks::mutator_lock_);
    280 
    281 
    282   const VerifiedMethod* GetVerifiedMethod(const DexFile* dex_file, uint32_t method_idx) const;
    283   bool IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc);
    284 
    285   bool GetSupportBootImageFixup() const {
    286     return support_boot_image_fixup_;
    287   }
    288 
    289   void SetSupportBootImageFixup(bool support_boot_image_fixup) {
    290     support_boot_image_fixup_ = support_boot_image_fixup;
    291   }
    292 
    293   void SetCompilerContext(void* compiler_context) {
    294     compiler_context_ = compiler_context;
    295   }
    296 
    297   void* GetCompilerContext() const {
    298     return compiler_context_;
    299   }
    300 
    301   size_t GetThreadCount() const {
    302     return parallel_thread_count_;
    303   }
    304 
    305   void SetDedupeEnabled(bool dedupe_enabled) {
    306     compiled_method_storage_.SetDedupeEnabled(dedupe_enabled);
    307   }
    308 
    309   bool DedupeEnabled() const {
    310     return compiled_method_storage_.DedupeEnabled();
    311   }
    312 
    313   // Checks if class specified by type_idx is one of the image_classes_
    314   bool IsImageClass(const char* descriptor) const;
    315 
    316   // Checks whether the provided class should be compiled, i.e., is in classes_to_compile_.
    317   bool IsClassToCompile(const char* descriptor) const;
    318 
    319   // Checks whether the provided method should be compiled, i.e., is in method_to_compile_.
    320   bool IsMethodToCompile(const MethodReference& method_ref) const;
    321 
    322   // Checks whether profile guided compilation is enabled and if the method should be compiled
    323   // according to the profile file.
    324   bool ShouldCompileBasedOnProfile(const MethodReference& method_ref) const;
    325 
    326   // Checks whether profile guided verification is enabled and if the method should be verified
    327   // according to the profile file.
    328   bool ShouldVerifyClassBasedOnProfile(const DexFile& dex_file, uint16_t class_idx) const;
    329 
    330   void RecordClassStatus(const ClassReference& ref, ClassStatus status);
    331 
    332   // Checks if the specified method has been verified without failures. Returns
    333   // false if the method is not in the verification results (GetVerificationResults).
    334   bool IsMethodVerifiedWithoutFailures(uint32_t method_idx,
    335                                        uint16_t class_def_idx,
    336                                        const DexFile& dex_file) const;
    337 
    338   // Get memory usage during compilation.
    339   std::string GetMemoryUsageString(bool extended) const;
    340 
    341   void SetHadHardVerifierFailure() {
    342     had_hard_verifier_failure_ = true;
    343   }
    344   void AddSoftVerifierFailure() {
    345     number_of_soft_verifier_failures_++;
    346   }
    347 
    348   Compiler::Kind GetCompilerKind() {
    349     return compiler_kind_;
    350   }
    351 
    352   CompiledMethodStorage* GetCompiledMethodStorage() {
    353     return &compiled_method_storage_;
    354   }
    355 
    356   // Can we assume that the klass is loaded?
    357   bool CanAssumeClassIsLoaded(mirror::Class* klass)
    358       REQUIRES_SHARED(Locks::mutator_lock_);
    359 
    360   bool MayInline(const DexFile* inlined_from, const DexFile* inlined_into) const {
    361     if (!kIsTargetBuild) {
    362       return MayInlineInternal(inlined_from, inlined_into);
    363     }
    364     return true;
    365   }
    366 
    367   const ProfileCompilationInfo* GetProfileCompilationInfo() const {
    368     return profile_compilation_info_;
    369   }
    370 
    371   // Is `boot_image_filename` the name of a core image (small boot
    372   // image used for ART testing only)?
    373   static bool IsCoreImageFilename(const std::string& boot_image_filename) {
    374     // Look for "core.art" or "core-*.art".
    375     if (android::base::EndsWith(boot_image_filename, "core.art")) {
    376       return true;
    377     }
    378     if (!android::base::EndsWith(boot_image_filename, ".art")) {
    379       return false;
    380     }
    381     size_t slash_pos = boot_image_filename.rfind('/');
    382     if (slash_pos == std::string::npos) {
    383       return android::base::StartsWith(boot_image_filename, "core-");
    384     }
    385     return boot_image_filename.compare(slash_pos + 1, 5u, "core-") == 0;
    386   }
    387 
    388   optimizer::DexToDexCompiler& GetDexToDexCompiler() {
    389     return dex_to_dex_compiler_;
    390   }
    391 
    392  private:
    393   void PreCompile(jobject class_loader,
    394                   const std::vector<const DexFile*>& dex_files,
    395                   TimingLogger* timings)
    396       REQUIRES(!Locks::mutator_lock_);
    397 
    398   void LoadImageClasses(TimingLogger* timings) REQUIRES(!Locks::mutator_lock_);
    399 
    400   // Attempt to resolve all type, methods, fields, and strings
    401   // referenced from code in the dex file following PathClassLoader
    402   // ordering semantics.
    403   void Resolve(jobject class_loader,
    404                const std::vector<const DexFile*>& dex_files,
    405                TimingLogger* timings)
    406       REQUIRES(!Locks::mutator_lock_);
    407   void ResolveDexFile(jobject class_loader,
    408                       const DexFile& dex_file,
    409                       const std::vector<const DexFile*>& dex_files,
    410                       ThreadPool* thread_pool,
    411                       size_t thread_count,
    412                       TimingLogger* timings)
    413       REQUIRES(!Locks::mutator_lock_);
    414 
    415   // Do fast verification through VerifierDeps if possible. Return whether
    416   // verification was successful.
    417   bool FastVerify(jobject class_loader,
    418                   const std::vector<const DexFile*>& dex_files,
    419                   TimingLogger* timings);
    420 
    421   void Verify(jobject class_loader,
    422               const std::vector<const DexFile*>& dex_files,
    423               TimingLogger* timings);
    424 
    425   void VerifyDexFile(jobject class_loader,
    426                      const DexFile& dex_file,
    427                      const std::vector<const DexFile*>& dex_files,
    428                      ThreadPool* thread_pool,
    429                      size_t thread_count,
    430                      TimingLogger* timings)
    431       REQUIRES(!Locks::mutator_lock_);
    432 
    433   void SetVerified(jobject class_loader,
    434                    const std::vector<const DexFile*>& dex_files,
    435                    TimingLogger* timings);
    436   void SetVerifiedDexFile(jobject class_loader,
    437                           const DexFile& dex_file,
    438                           const std::vector<const DexFile*>& dex_files,
    439                           ThreadPool* thread_pool,
    440                           size_t thread_count,
    441                           TimingLogger* timings)
    442       REQUIRES(!Locks::mutator_lock_);
    443 
    444   void InitializeClasses(jobject class_loader,
    445                          const std::vector<const DexFile*>& dex_files,
    446                          TimingLogger* timings)
    447       REQUIRES(!Locks::mutator_lock_);
    448   void InitializeClasses(jobject class_loader,
    449                          const DexFile& dex_file,
    450                          const std::vector<const DexFile*>& dex_files,
    451                          TimingLogger* timings)
    452       REQUIRES(!Locks::mutator_lock_);
    453 
    454   void UpdateImageClasses(TimingLogger* timings) REQUIRES(!Locks::mutator_lock_);
    455 
    456   void Compile(jobject class_loader,
    457                const std::vector<const DexFile*>& dex_files,
    458                TimingLogger* timings);
    459 
    460   bool MayInlineInternal(const DexFile* inlined_from, const DexFile* inlined_into) const;
    461 
    462   void InitializeThreadPools();
    463   void FreeThreadPools();
    464   void CheckThreadPools();
    465 
    466   bool RequiresConstructorBarrier(const DexFile& dex_file, uint16_t class_def_idx) const;
    467 
    468   const CompilerOptions* const compiler_options_;
    469   VerificationResults* const verification_results_;
    470 
    471   std::unique_ptr<Compiler> compiler_;
    472   Compiler::Kind compiler_kind_;
    473 
    474   const InstructionSet instruction_set_;
    475   const InstructionSetFeatures* const instruction_set_features_;
    476 
    477   // All class references that require constructor barriers. If the class reference is not in the
    478   // set then the result has not yet been computed.
    479   mutable ReaderWriterMutex requires_constructor_barrier_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
    480   std::map<ClassReference, bool> requires_constructor_barrier_
    481       GUARDED_BY(requires_constructor_barrier_lock_);
    482 
    483   // All class references that this compiler has compiled. Indexed by class defs.
    484   using ClassStateTable = AtomicDexRefMap<ClassReference, ClassStatus>;
    485   ClassStateTable compiled_classes_;
    486   // All class references that are in the classpath. Indexed by class defs.
    487   ClassStateTable classpath_classes_;
    488 
    489   typedef AtomicDexRefMap<MethodReference, CompiledMethod*> MethodTable;
    490 
    491  private:
    492   // All method references that this compiler has compiled.
    493   MethodTable compiled_methods_;
    494 
    495   // Number of non-relative patches in all compiled methods. These patches need space
    496   // in the .oat_patches ELF section if requested in the compiler options.
    497   Atomic<size_t> non_relative_linker_patch_count_;
    498 
    499   // If image_ is true, specifies the classes that will be included in the image.
    500   // Note if image_classes_ is null, all classes are included in the image.
    501   std::unique_ptr<std::unordered_set<std::string>> image_classes_;
    502 
    503   // Specifies the classes that will be compiled. Note that if classes_to_compile_ is null,
    504   // all classes are eligible for compilation (duplication filters etc. will still apply).
    505   // This option may be restricted to the boot image, depending on a flag in the implementation.
    506   std::unique_ptr<std::unordered_set<std::string>> classes_to_compile_;
    507 
    508   // Specifies the methods that will be compiled. Note that if methods_to_compile_ is null,
    509   // all methods are eligible for compilation (compilation filters etc. will still apply).
    510   // This option may be restricted to the boot image, depending on a flag in the implementation.
    511   std::unique_ptr<std::unordered_set<std::string>> methods_to_compile_;
    512 
    513   std::atomic<uint32_t> number_of_soft_verifier_failures_;
    514   bool had_hard_verifier_failure_;
    515 
    516   // A thread pool that can (potentially) run tasks in parallel.
    517   std::unique_ptr<ThreadPool> parallel_thread_pool_;
    518   size_t parallel_thread_count_;
    519 
    520   // A thread pool that guarantees running single-threaded on the main thread.
    521   std::unique_ptr<ThreadPool> single_thread_pool_;
    522 
    523   class AOTCompilationStats;
    524   std::unique_ptr<AOTCompilationStats> stats_;
    525 
    526   typedef void (*CompilerCallbackFn)(CompilerDriver& driver);
    527   typedef MutexLock* (*CompilerMutexLockFn)(CompilerDriver& driver);
    528 
    529   void* compiler_context_;
    530 
    531   bool support_boot_image_fixup_;
    532 
    533   // List of dex files associates with the oat file.
    534   std::vector<const DexFile*> dex_files_for_oat_file_;
    535 
    536   CompiledMethodStorage compiled_method_storage_;
    537 
    538   // Info for profile guided compilation.
    539   const ProfileCompilationInfo* const profile_compilation_info_;
    540 
    541   size_t max_arena_alloc_;
    542 
    543   // Compiler for dex to dex (quickening).
    544   optimizer::DexToDexCompiler dex_to_dex_compiler_;
    545 
    546   friend class CompileClassVisitor;
    547   friend class DexToDexDecompilerTest;
    548   friend class verifier::VerifierDepsTest;
    549   DISALLOW_COPY_AND_ASSIGN(CompilerDriver);
    550 };
    551 
    552 }  // namespace art
    553 
    554 #endif  // ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
    555