compiler_driver.h revision d582fa4ea62083a7598dded5b82dc2198b3daac7
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 <set>
21#include <string>
22#include <vector>
23
24#include "arch/instruction_set.h"
25#include "base/mutex.h"
26#include "base/timing_logger.h"
27#include "class_reference.h"
28#include "compiled_method.h"
29#include "compiler.h"
30#include "dex_file.h"
31#include "driver/compiler_options.h"
32#include "invoke_type.h"
33#include "method_reference.h"
34#include "mirror/class.h"  // For mirror::Class::Status.
35#include "os.h"
36#include "profiler.h"
37#include "runtime.h"
38#include "safe_map.h"
39#include "thread_pool.h"
40#include "utils/arena_allocator.h"
41#include "utils/dedupe_set.h"
42
43namespace art {
44
45namespace verifier {
46class MethodVerifier;
47}  // namespace verifier
48
49class CompiledClass;
50class CompilerOptions;
51class DexCompilationUnit;
52class DexFileToMethodInlinerMap;
53struct InlineIGetIPutData;
54class InstructionSetFeatures;
55class OatWriter;
56class ParallelCompilationManager;
57class ScopedObjectAccess;
58template<class T> class Handle;
59class TimingLogger;
60class VerificationResults;
61class VerifiedMethod;
62
63enum EntryPointCallingConvention {
64  // ABI of invocations to a method's interpreter entry point.
65  kInterpreterAbi,
66  // ABI of calls to a method's native code, only used for native methods.
67  kJniAbi,
68  // ABI of calls to a method's portable code entry point.
69  kPortableAbi,
70  // ABI of calls to a method's quick code entry point.
71  kQuickAbi
72};
73
74enum DexToDexCompilationLevel {
75  kDontDexToDexCompile,   // Only meaning wrt image time interpretation.
76  kRequired,              // Dex-to-dex compilation required for correctness.
77  kOptimize               // Perform required transformation and peep-hole optimizations.
78};
79std::ostream& operator<<(std::ostream& os, const DexToDexCompilationLevel& rhs);
80
81class CompilerDriver {
82 public:
83  // Create a compiler targeting the requested "instruction_set".
84  // "image" should be true if image specific optimizations should be
85  // enabled.  "image_classes" lets the compiler know what classes it
86  // can assume will be in the image, with nullptr implying all available
87  // classes.
88  explicit CompilerDriver(const CompilerOptions* compiler_options,
89                          VerificationResults* verification_results,
90                          DexFileToMethodInlinerMap* method_inliner_map,
91                          Compiler::Kind compiler_kind,
92                          InstructionSet instruction_set,
93                          const InstructionSetFeatures* instruction_set_features,
94                          bool image, std::set<std::string>* image_classes,
95                          std::set<std::string>* compiled_classes,
96                          size_t thread_count, bool dump_stats, bool dump_passes,
97                          CumulativeLogger* timer, const std::string& profile_file);
98
99  ~CompilerDriver();
100
101  void CompileAll(jobject class_loader, const std::vector<const DexFile*>& dex_files,
102                  TimingLogger* timings)
103      LOCKS_EXCLUDED(Locks::mutator_lock_);
104
105  // Compile a single Method.
106  void CompileOne(mirror::ArtMethod* method, TimingLogger* timings)
107      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
108
109  VerificationResults* GetVerificationResults() const {
110    return verification_results_;
111  }
112
113  DexFileToMethodInlinerMap* GetMethodInlinerMap() const {
114    return method_inliner_map_;
115  }
116
117  InstructionSet GetInstructionSet() const {
118    return instruction_set_;
119  }
120
121  const InstructionSetFeatures* GetInstructionSetFeatures() const {
122    return instruction_set_features_;
123  }
124
125  const CompilerOptions& GetCompilerOptions() const {
126    return *compiler_options_;
127  }
128
129  Compiler* GetCompiler() const {
130    return compiler_.get();
131  }
132
133  bool ProfilePresent() const {
134    return profile_present_;
135  }
136
137  // Are we compiling and creating an image file?
138  bool IsImage() const {
139    return image_;
140  }
141
142  const std::set<std::string>* GetImageClasses() const {
143    return image_classes_.get();
144  }
145
146  CompilerTls* GetTls();
147
148  // Generate the trampolines that are invoked by unresolved direct methods.
149  const std::vector<uint8_t>* CreateInterpreterToInterpreterBridge() const
150      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
151  const std::vector<uint8_t>* CreateInterpreterToCompiledCodeBridge() const
152      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
153  const std::vector<uint8_t>* CreateJniDlsymLookup() const
154      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
155  const std::vector<uint8_t>* CreatePortableImtConflictTrampoline() const
156      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
157  const std::vector<uint8_t>* CreatePortableResolutionTrampoline() const
158      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
159  const std::vector<uint8_t>* CreatePortableToInterpreterBridge() const
160      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
161  const std::vector<uint8_t>* CreateQuickGenericJniTrampoline() const
162      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
163  const std::vector<uint8_t>* CreateQuickImtConflictTrampoline() const
164      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
165  const std::vector<uint8_t>* CreateQuickResolutionTrampoline() const
166      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
167  const std::vector<uint8_t>* CreateQuickToInterpreterBridge() const
168      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
169
170  CompiledClass* GetCompiledClass(ClassReference ref) const
171      LOCKS_EXCLUDED(compiled_classes_lock_);
172
173  CompiledMethod* GetCompiledMethod(MethodReference ref) const
174      LOCKS_EXCLUDED(compiled_methods_lock_);
175  size_t GetNonRelativeLinkerPatchCount() const
176      LOCKS_EXCLUDED(compiled_methods_lock_);
177
178  void AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
179                                     uint16_t class_def_index);
180  bool RequiresConstructorBarrier(Thread* self, const DexFile* dex_file, uint16_t class_def_index);
181
182  // Callbacks from compiler to see what runtime checks must be generated.
183
184  bool CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx);
185
186  bool CanAssumeStringIsPresentInDexCache(const DexFile& dex_file, uint32_t string_idx)
187      LOCKS_EXCLUDED(Locks::mutator_lock_);
188
189  // Are runtime access checks necessary in the compiled code?
190  bool CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
191                                  uint32_t type_idx, bool* type_known_final = nullptr,
192                                  bool* type_known_abstract = nullptr,
193                                  bool* equals_referrers_class = nullptr)
194      LOCKS_EXCLUDED(Locks::mutator_lock_);
195
196  // Are runtime access and instantiable checks necessary in the code?
197  bool CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
198                                              uint32_t type_idx)
199     LOCKS_EXCLUDED(Locks::mutator_lock_);
200
201  bool CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
202                          bool* is_type_initialized, bool* use_direct_type_ptr,
203                          uintptr_t* direct_type_ptr, bool* out_is_finalizable);
204
205  // Query methods for the java.lang.ref.Reference class.
206  bool CanEmbedReferenceTypeInCode(ClassReference* ref,
207                                   bool* use_direct_type_ptr, uintptr_t* direct_type_ptr);
208  uint32_t GetReferenceSlowFlagOffset() const;
209  uint32_t GetReferenceDisableFlagOffset() const;
210
211  // Get the DexCache for the
212  mirror::DexCache* GetDexCache(const DexCompilationUnit* mUnit)
213    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
214
215  mirror::ClassLoader* GetClassLoader(ScopedObjectAccess& soa, const DexCompilationUnit* mUnit)
216    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
217
218  // Resolve compiling method's class. Returns nullptr on failure.
219  mirror::Class* ResolveCompilingMethodsClass(
220      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
221      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit)
222    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
223
224  // Resolve a field. Returns nullptr on failure, including incompatible class change.
225  // NOTE: Unlike ClassLinker's ResolveField(), this method enforces is_static.
226  mirror::ArtField* ResolveField(
227      const ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
228      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
229      uint32_t field_idx, bool is_static)
230    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
231
232  // Get declaration location of a resolved field.
233  void GetResolvedFieldDexFileLocation(
234      mirror::ArtField* resolved_field, const DexFile** declaring_dex_file,
235      uint16_t* declaring_class_idx, uint16_t* declaring_field_idx)
236    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
237
238  bool IsFieldVolatile(mirror::ArtField* field) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
239  MemberOffset GetFieldOffset(mirror::ArtField* field) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
240
241  // Can we fast-path an IGET/IPUT access to an instance field? If yes, compute the field offset.
242  std::pair<bool, bool> IsFastInstanceField(
243      mirror::DexCache* dex_cache, mirror::Class* referrer_class,
244      mirror::ArtField* resolved_field, uint16_t field_idx)
245    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
246
247  // Can we fast-path an SGET/SPUT access to a static field? If yes, compute the type index
248  // of the declaring class in the referrer's dex file.
249  std::pair<bool, bool> IsFastStaticField(
250      mirror::DexCache* dex_cache, mirror::Class* referrer_class,
251      mirror::ArtField* resolved_field, uint16_t field_idx, uint32_t* storage_index)
252    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
253
254  // Is static field's in referrer's class?
255  bool IsStaticFieldInReferrerClass(mirror::Class* referrer_class, mirror::ArtField* resolved_field)
256    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
257
258  // Is static field's class initialized?
259  bool IsStaticFieldsClassInitialized(mirror::Class* referrer_class,
260                                      mirror::ArtField* resolved_field)
261    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
262
263  // Resolve a method. Returns nullptr on failure, including incompatible class change.
264  mirror::ArtMethod* ResolveMethod(
265      ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
266      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
267      uint32_t method_idx, InvokeType invoke_type)
268    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
269
270  // Get declaration location of a resolved field.
271  void GetResolvedMethodDexFileLocation(
272      mirror::ArtMethod* resolved_method, const DexFile** declaring_dex_file,
273      uint16_t* declaring_class_idx, uint16_t* declaring_method_idx)
274    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
275
276  // Get the index in the vtable of the method.
277  uint16_t GetResolvedMethodVTableIndex(
278      mirror::ArtMethod* resolved_method, InvokeType type)
279    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
280
281  // Can we fast-path an INVOKE? If no, returns 0. If yes, returns a non-zero opaque flags value
282  // for ProcessedInvoke() and computes the necessary lowering info.
283  int IsFastInvoke(
284      ScopedObjectAccess& soa, Handle<mirror::DexCache> dex_cache,
285      Handle<mirror::ClassLoader> class_loader, const DexCompilationUnit* mUnit,
286      mirror::Class* referrer_class, mirror::ArtMethod* resolved_method, InvokeType* invoke_type,
287      MethodReference* target_method, const MethodReference* devirt_target,
288      uintptr_t* direct_code, uintptr_t* direct_method)
289    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
290
291  // Is method's class initialized for an invoke?
292  // For static invokes to determine whether we need to consider potential call to <clinit>().
293  // For non-static invokes, assuming a non-null reference, the class is always initialized.
294  bool IsMethodsClassInitialized(mirror::Class* referrer_class, mirror::ArtMethod* resolved_method)
295    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
296
297  void ProcessedInstanceField(bool resolved);
298  void ProcessedStaticField(bool resolved, bool local);
299  void ProcessedInvoke(InvokeType invoke_type, int flags);
300
301  // Can we fast path instance field access? Computes field's offset and volatility.
302  bool ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit, bool is_put,
303                                MemberOffset* field_offset, bool* is_volatile)
304      LOCKS_EXCLUDED(Locks::mutator_lock_);
305
306  mirror::ArtField* ComputeInstanceFieldInfo(uint32_t field_idx,
307                                             const DexCompilationUnit* mUnit,
308                                             bool is_put,
309                                             const ScopedObjectAccess& soa)
310      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
311
312
313  // Can we fastpath static field access? Computes field's offset, volatility and whether the
314  // field is within the referrer (which can avoid checking class initialization).
315  bool ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit, bool is_put,
316                              MemberOffset* field_offset, uint32_t* storage_index,
317                              bool* is_referrers_class, bool* is_volatile, bool* is_initialized,
318                              Primitive::Type* type)
319      LOCKS_EXCLUDED(Locks::mutator_lock_);
320
321  // Can we fastpath a interface, super class or virtual method call? Computes method's vtable
322  // index.
323  bool ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
324                         bool update_stats, bool enable_devirtualization,
325                         InvokeType* type, MethodReference* target_method, int* vtable_idx,
326                         uintptr_t* direct_code, uintptr_t* direct_method)
327      LOCKS_EXCLUDED(Locks::mutator_lock_);
328
329  const VerifiedMethod* GetVerifiedMethod(const DexFile* dex_file, uint32_t method_idx) const;
330  bool IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc);
331
332  bool GetSupportBootImageFixup() const {
333    return support_boot_image_fixup_;
334  }
335
336  void SetSupportBootImageFixup(bool support_boot_image_fixup) {
337    support_boot_image_fixup_ = support_boot_image_fixup;
338  }
339
340  ArenaPool* GetArenaPool() {
341    return &arena_pool_;
342  }
343
344  bool WriteElf(const std::string& android_root,
345                bool is_host,
346                const std::vector<const DexFile*>& dex_files,
347                OatWriter* oat_writer,
348                File* file);
349
350  // TODO: move to a common home for llvm helpers once quick/portable are merged.
351  static void InstructionSetToLLVMTarget(InstructionSet instruction_set,
352                                         std::string* target_triple,
353                                         std::string* target_cpu,
354                                         std::string* target_attr);
355
356  void SetCompilerContext(void* compiler_context) {
357    compiler_context_ = compiler_context;
358  }
359
360  void* GetCompilerContext() const {
361    return compiler_context_;
362  }
363
364  size_t GetThreadCount() const {
365    return thread_count_;
366  }
367
368  bool GetDumpPasses() const {
369    return dump_passes_;
370  }
371
372  CumulativeLogger* GetTimingsLogger() const {
373    return timings_logger_;
374  }
375
376  // Checks if class specified by type_idx is one of the image_classes_
377  bool IsImageClass(const char* descriptor) const;
378
379  // Checks if the provided class should be compiled, i.e., is in classes_to_compile_.
380  bool IsClassToCompile(const char* descriptor) const;
381
382  void RecordClassStatus(ClassReference ref, mirror::Class::Status status)
383      LOCKS_EXCLUDED(compiled_classes_lock_);
384
385  std::vector<uint8_t>* DeduplicateCode(const std::vector<uint8_t>& code);
386  SrcMap* DeduplicateSrcMappingTable(const SrcMap& src_map);
387  std::vector<uint8_t>* DeduplicateMappingTable(const std::vector<uint8_t>& code);
388  std::vector<uint8_t>* DeduplicateVMapTable(const std::vector<uint8_t>& code);
389  std::vector<uint8_t>* DeduplicateGCMap(const std::vector<uint8_t>& code);
390  std::vector<uint8_t>* DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info);
391
392  ProfileFile profile_file_;
393  bool profile_present_;
394
395  // Should the compiler run on this method given profile information?
396  bool SkipCompilation(const std::string& method_name);
397
398 private:
399  // These flags are internal to CompilerDriver for collecting INVOKE resolution statistics.
400  // The only external contract is that unresolved method has flags 0 and resolved non-0.
401  enum {
402    kBitMethodResolved = 0,
403    kBitVirtualMadeDirect,
404    kBitPreciseTypeDevirtualization,
405    kBitDirectCallToBoot,
406    kBitDirectMethodToBoot
407  };
408  static constexpr int kFlagMethodResolved              = 1 << kBitMethodResolved;
409  static constexpr int kFlagVirtualMadeDirect           = 1 << kBitVirtualMadeDirect;
410  static constexpr int kFlagPreciseTypeDevirtualization = 1 << kBitPreciseTypeDevirtualization;
411  static constexpr int kFlagDirectCallToBoot            = 1 << kBitDirectCallToBoot;
412  static constexpr int kFlagDirectMethodToBoot          = 1 << kBitDirectMethodToBoot;
413  static constexpr int kFlagsMethodResolvedVirtualMadeDirect =
414      kFlagMethodResolved | kFlagVirtualMadeDirect;
415  static constexpr int kFlagsMethodResolvedPreciseTypeDevirtualization =
416      kFlagsMethodResolvedVirtualMadeDirect | kFlagPreciseTypeDevirtualization;
417
418 public:  // TODO make private or eliminate.
419  // Compute constant code and method pointers when possible.
420  void GetCodeAndMethodForDirectCall(/*out*/InvokeType* type,
421                                     InvokeType sharp_type,
422                                     bool no_guarantee_of_dex_cache_entry,
423                                     const mirror::Class* referrer_class,
424                                     mirror::ArtMethod* method,
425                                     /*out*/int* stats_flags,
426                                     MethodReference* target_method,
427                                     uintptr_t* direct_code, uintptr_t* direct_method)
428      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
429
430 private:
431  void PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
432                  ThreadPool* thread_pool, TimingLogger* timings)
433      LOCKS_EXCLUDED(Locks::mutator_lock_);
434
435  void LoadImageClasses(TimingLogger* timings);
436
437  // Attempt to resolve all type, methods, fields, and strings
438  // referenced from code in the dex file following PathClassLoader
439  // ordering semantics.
440  void Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
441               ThreadPool* thread_pool, TimingLogger* timings)
442      LOCKS_EXCLUDED(Locks::mutator_lock_);
443  void ResolveDexFile(jobject class_loader, const DexFile& dex_file,
444                      const std::vector<const DexFile*>& dex_files,
445                      ThreadPool* thread_pool, TimingLogger* timings)
446      LOCKS_EXCLUDED(Locks::mutator_lock_);
447
448  void Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
449              ThreadPool* thread_pool, TimingLogger* timings);
450  void VerifyDexFile(jobject class_loader, const DexFile& dex_file,
451                     const std::vector<const DexFile*>& dex_files,
452                     ThreadPool* thread_pool, TimingLogger* timings)
453      LOCKS_EXCLUDED(Locks::mutator_lock_);
454
455  void SetVerified(jobject class_loader, const std::vector<const DexFile*>& dex_files,
456                   ThreadPool* thread_pool, TimingLogger* timings);
457  void SetVerifiedDexFile(jobject class_loader, const DexFile& dex_file,
458                          const std::vector<const DexFile*>& dex_files,
459                          ThreadPool* thread_pool, TimingLogger* timings)
460      LOCKS_EXCLUDED(Locks::mutator_lock_);
461
462  void InitializeClasses(jobject class_loader, const std::vector<const DexFile*>& dex_files,
463                         ThreadPool* thread_pool, TimingLogger* timings)
464      LOCKS_EXCLUDED(Locks::mutator_lock_);
465  void InitializeClasses(jobject class_loader, const DexFile& dex_file,
466                         const std::vector<const DexFile*>& dex_files,
467                         ThreadPool* thread_pool, TimingLogger* timings)
468      LOCKS_EXCLUDED(Locks::mutator_lock_, compiled_classes_lock_);
469
470  void UpdateImageClasses(TimingLogger* timings) LOCKS_EXCLUDED(Locks::mutator_lock_);
471  static void FindClinitImageClassesCallback(mirror::Object* object, void* arg)
472      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
473
474  void Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
475               ThreadPool* thread_pool, TimingLogger* timings);
476  void CompileDexFile(jobject class_loader, const DexFile& dex_file,
477                      const std::vector<const DexFile*>& dex_files,
478                      ThreadPool* thread_pool, TimingLogger* timings)
479      LOCKS_EXCLUDED(Locks::mutator_lock_);
480  void CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
481                     InvokeType invoke_type, uint16_t class_def_idx, uint32_t method_idx,
482                     jobject class_loader, const DexFile& dex_file,
483                     DexToDexCompilationLevel dex_to_dex_compilation_level,
484                     bool compilation_enabled)
485      LOCKS_EXCLUDED(compiled_methods_lock_);
486
487  static void CompileClass(const ParallelCompilationManager* context, size_t class_def_index)
488      LOCKS_EXCLUDED(Locks::mutator_lock_);
489
490  const CompilerOptions* const compiler_options_;
491  VerificationResults* const verification_results_;
492  DexFileToMethodInlinerMap* const method_inliner_map_;
493
494  std::unique_ptr<Compiler> compiler_;
495
496  const InstructionSet instruction_set_;
497  const InstructionSetFeatures* const instruction_set_features_;
498
499  // All class references that require
500  mutable ReaderWriterMutex freezing_constructor_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
501  std::set<ClassReference> freezing_constructor_classes_ GUARDED_BY(freezing_constructor_lock_);
502
503  typedef SafeMap<const ClassReference, CompiledClass*> ClassTable;
504  // All class references that this compiler has compiled.
505  mutable Mutex compiled_classes_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
506  ClassTable compiled_classes_ GUARDED_BY(compiled_classes_lock_);
507
508  typedef SafeMap<const MethodReference, CompiledMethod*, MethodReferenceComparator> MethodTable;
509  // All method references that this compiler has compiled.
510  mutable Mutex compiled_methods_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
511  MethodTable compiled_methods_ GUARDED_BY(compiled_methods_lock_);
512  // Number of non-relative patches in all compiled methods. These patches need space
513  // in the .oat_patches ELF section if requested in the compiler options.
514  size_t non_relative_linker_patch_count_ GUARDED_BY(compiled_methods_lock_);
515
516  const bool image_;
517
518  // If image_ is true, specifies the classes that will be included in
519  // the image. Note if image_classes_ is nullptr, all classes are
520  // included in the image.
521  std::unique_ptr<std::set<std::string>> image_classes_;
522
523  // If image_ is true, specifies the classes that will be compiled in
524  // the image. Note if classes_to_compile_ is nullptr, all classes are
525  // included in the image.
526  std::unique_ptr<std::set<std::string>> classes_to_compile_;
527
528  size_t thread_count_;
529
530  class AOTCompilationStats;
531  std::unique_ptr<AOTCompilationStats> stats_;
532
533  bool dump_stats_;
534  const bool dump_passes_;
535
536  CumulativeLogger* const timings_logger_;
537
538  typedef void (*CompilerCallbackFn)(CompilerDriver& driver);
539  typedef MutexLock* (*CompilerMutexLockFn)(CompilerDriver& driver);
540
541  typedef void (*DexToDexCompilerFn)(CompilerDriver& driver,
542                                     const DexFile::CodeItem* code_item,
543                                     uint32_t access_flags, InvokeType invoke_type,
544                                     uint32_t class_dex_idx, uint32_t method_idx,
545                                     jobject class_loader, const DexFile& dex_file,
546                                     DexToDexCompilationLevel dex_to_dex_compilation_level);
547  DexToDexCompilerFn dex_to_dex_compiler_;
548
549  void* compiler_context_;
550
551  pthread_key_t tls_key_;
552
553  // Arena pool used by the compiler.
554  ArenaPool arena_pool_;
555
556  bool support_boot_image_fixup_;
557
558  // DeDuplication data structures, these own the corresponding byte arrays.
559  template <typename ByteArray>
560  class DedupeHashFunc {
561   public:
562    size_t operator()(const ByteArray& array) const {
563      // For small arrays compute a hash using every byte.
564      static const size_t kSmallArrayThreshold = 16;
565      size_t hash = 0x811c9dc5;
566      if (array.size() <= kSmallArrayThreshold) {
567        for (auto b : array) {
568          hash = (hash * 16777619) ^ static_cast<uint8_t>(b);
569        }
570      } else {
571        // For larger arrays use the 2 bytes at 6 bytes (the location of a push registers
572        // instruction field for quick generated code on ARM) and then select a number of other
573        // values at random.
574        static const size_t kRandomHashCount = 16;
575        for (size_t i = 0; i < 2; ++i) {
576          uint8_t b = static_cast<uint8_t>(array[i + 6]);
577          hash = (hash * 16777619) ^ b;
578        }
579        for (size_t i = 2; i < kRandomHashCount; ++i) {
580          size_t r = i * 1103515245 + 12345;
581          uint8_t b = static_cast<uint8_t>(array[r % array.size()]);
582          hash = (hash * 16777619) ^ b;
583        }
584      }
585      hash += hash << 13;
586      hash ^= hash >> 7;
587      hash += hash << 3;
588      hash ^= hash >> 17;
589      hash += hash << 5;
590      return hash;
591    }
592  };
593
594  DedupeSet<std::vector<uint8_t>, size_t, DedupeHashFunc<std::vector<uint8_t>>, 4> dedupe_code_;
595  DedupeSet<SrcMap, size_t, DedupeHashFunc<SrcMap>, 4> dedupe_src_mapping_table_;
596  DedupeSet<std::vector<uint8_t>, size_t, DedupeHashFunc<std::vector<uint8_t>>, 4> dedupe_mapping_table_;
597  DedupeSet<std::vector<uint8_t>, size_t, DedupeHashFunc<std::vector<uint8_t>>, 4> dedupe_vmap_table_;
598  DedupeSet<std::vector<uint8_t>, size_t, DedupeHashFunc<std::vector<uint8_t>>, 4> dedupe_gc_map_;
599  DedupeSet<std::vector<uint8_t>, size_t, DedupeHashFunc<std::vector<uint8_t>>, 4> dedupe_cfi_info_;
600
601  DISALLOW_COPY_AND_ASSIGN(CompilerDriver);
602};
603
604}  // namespace art
605
606#endif  // ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
607