compiler_driver.h revision 75021222d9c03a80fa5c136db0d5fb8d82d04031
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 "base/mutex.h"
25#include "class_reference.h"
26#include "compiled_class.h"
27#include "compiled_method.h"
28#include "dex_file.h"
29#include "instruction_set.h"
30#include "invoke_type.h"
31#include "method_reference.h"
32#include "os.h"
33#include "runtime.h"
34#include "safe_map.h"
35#include "thread_pool.h"
36
37namespace art {
38
39class AOTCompilationStats;
40class ParallelCompilationManager;
41class DexCompilationUnit;
42class OatWriter;
43class TimingLogger;
44
45enum CompilerBackend {
46  kQuick,
47  kPortable,
48  kNoBackend
49};
50
51enum DexToDexCompilationLevel {
52  kDontDexToDexCompile,   // Only meaning wrt image time interpretation.
53  kRequired,              // Dex-to-dex compilation required for correctness.
54  kOptimize               // Perform required transformation and peep-hole optimizations.
55};
56
57// Thread-local storage compiler worker threads
58class CompilerTls {
59  public:
60    CompilerTls() : llvm_info_(NULL) {}
61    ~CompilerTls() {}
62
63    void* GetLLVMInfo() { return llvm_info_; }
64
65    void SetLLVMInfo(void* llvm_info) { llvm_info_ = llvm_info; }
66
67  private:
68    void* llvm_info_;
69};
70
71class CompilerDriver {
72 public:
73  typedef std::set<std::string> DescriptorSet;
74
75  // Create a compiler targeting the requested "instruction_set".
76  // "image" should be true if image specific optimizations should be
77  // enabled.  "image_classes" lets the compiler know what classes it
78  // can assume will be in the image, with NULL implying all available
79  // classes.
80  explicit CompilerDriver(CompilerBackend compiler_backend, InstructionSet instruction_set,
81                          bool image, DescriptorSet* image_classes,
82                          size_t thread_count, bool dump_stats);
83
84  ~CompilerDriver();
85
86  void CompileAll(jobject class_loader, const std::vector<const DexFile*>& dex_files,
87                  base::TimingLogger& timings)
88      LOCKS_EXCLUDED(Locks::mutator_lock_);
89
90  // Compile a single Method
91  void CompileOne(const mirror::AbstractMethod* method, base::TimingLogger& timings)
92      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
93
94  InstructionSet GetInstructionSet() const {
95    return instruction_set_;
96  }
97
98  CompilerBackend GetCompilerBackend() const {
99    return compiler_backend_;
100  }
101
102  bool IsImage() const {
103    return image_;
104  }
105
106  DescriptorSet* GetImageClasses() const {
107    return image_classes_.get();
108  }
109
110  CompilerTls* GetTls();
111
112  // Generate the trampolines that are invoked by unresolved direct methods.
113  const std::vector<uint8_t>* CreatePortableResolutionTrampoline() const
114      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
115  const std::vector<uint8_t>* CreateQuickResolutionTrampoline() const
116      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
117  const std::vector<uint8_t>* CreateInterpreterToInterpreterEntry() const
118      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
119  const std::vector<uint8_t>* CreateInterpreterToQuickEntry() const
120      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
121
122  CompiledClass* GetCompiledClass(ClassReference ref) const
123      LOCKS_EXCLUDED(compiled_classes_lock_);
124
125  CompiledMethod* GetCompiledMethod(MethodReference ref) const
126      LOCKS_EXCLUDED(compiled_methods_lock_);
127
128  void AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file, size_t class_def_index);
129  bool RequiresConstructorBarrier(Thread* self, const DexFile* dex_file, size_t class_def_index);
130
131  // Callbacks from compiler to see what runtime checks must be generated.
132
133  bool CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx)
134      LOCKS_EXCLUDED(Locks::mutator_lock_);
135
136  bool CanAssumeStringIsPresentInDexCache(const DexFile& dex_file, uint32_t string_idx)
137      LOCKS_EXCLUDED(Locks::mutator_lock_);
138
139  // Are runtime access checks necessary in the compiled code?
140  bool CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
141                                  uint32_t type_idx, bool* type_known_final = NULL,
142                                  bool* type_known_abstract = NULL,
143                                  bool* equals_referrers_class = NULL)
144      LOCKS_EXCLUDED(Locks::mutator_lock_);
145
146  // Are runtime access and instantiable checks necessary in the code?
147  bool CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
148                                              uint32_t type_idx)
149     LOCKS_EXCLUDED(Locks::mutator_lock_);
150
151  // Can we fast path instance field access? Computes field's offset and volatility.
152  bool ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
153                                int& field_offset, bool& is_volatile, bool is_put)
154      LOCKS_EXCLUDED(Locks::mutator_lock_);
155
156  // Can we fastpath static field access? Computes field's offset, volatility and whether the
157  // field is within the referrer (which can avoid checking class initialization).
158  bool ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
159                              int& field_offset, int& ssb_index,
160                              bool& is_referrers_class, bool& is_volatile, bool is_put)
161      LOCKS_EXCLUDED(Locks::mutator_lock_);
162
163  // Can we fastpath a interface, super class or virtual method call? Computes method's vtable
164  // index.
165  bool ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
166                         InvokeType& type, MethodReference& target_method, int& vtable_idx,
167                         uintptr_t& direct_code, uintptr_t& direct_method, bool update_stats)
168      LOCKS_EXCLUDED(Locks::mutator_lock_);
169
170  bool IsSafeCast(const MethodReference& mr, uint32_t dex_pc);
171
172  // Record patch information for later fix up.
173  void AddCodePatch(const DexFile* dex_file,
174                    uint32_t referrer_method_idx,
175                    InvokeType referrer_invoke_type,
176                    uint32_t target_method_idx,
177                    InvokeType target_invoke_type,
178                    size_t literal_offset)
179      LOCKS_EXCLUDED(compiled_methods_lock_);
180  void AddMethodPatch(const DexFile* dex_file,
181                      uint32_t referrer_method_idx,
182                      InvokeType referrer_invoke_type,
183                      uint32_t target_method_idx,
184                      InvokeType target_invoke_type,
185                      size_t literal_offset)
186      LOCKS_EXCLUDED(compiled_methods_lock_);
187
188  void SetBitcodeFileName(std::string const& filename);
189
190  bool GetSupportBootImageFixup() const {
191    return support_boot_image_fixup_;
192  }
193
194  void SetSupportBootImageFixup(bool support_boot_image_fixup) {
195    support_boot_image_fixup_ = support_boot_image_fixup;
196  }
197
198
199  bool WriteElf(const std::string& android_root,
200                bool is_host,
201                const std::vector<const DexFile*>& dex_files,
202                OatWriter& oat_writer,
203                File* file);
204
205  // TODO: move to a common home for llvm helpers once quick/portable are merged
206  static void InstructionSetToLLVMTarget(InstructionSet instruction_set,
207                                         std::string& target_triple,
208                                         std::string& target_cpu,
209                                         std::string& target_attr);
210
211  void SetCompilerContext(void* compiler_context) {
212    compiler_context_ = compiler_context;
213  }
214
215  void* GetCompilerContext() const {
216    return compiler_context_;
217  }
218
219  size_t GetThreadCount() const {
220    return thread_count_;
221  }
222
223  class PatchInformation {
224   public:
225    const DexFile& GetDexFile() const {
226      return *dex_file_;
227    }
228    uint32_t GetReferrerMethodIdx() const {
229      return referrer_method_idx_;
230    }
231    InvokeType GetReferrerInvokeType() const {
232      return referrer_invoke_type_;
233    }
234    uint32_t GetTargetMethodIdx() const {
235      return target_method_idx_;
236    }
237    InvokeType GetTargetInvokeType() const {
238      return target_invoke_type_;
239    }
240    size_t GetLiteralOffset() const {;
241      return literal_offset_;
242    }
243
244   private:
245    PatchInformation(const DexFile* dex_file,
246                     uint32_t referrer_method_idx,
247                     InvokeType referrer_invoke_type,
248                     uint32_t target_method_idx,
249                     InvokeType target_invoke_type,
250                     size_t literal_offset)
251      : dex_file_(dex_file),
252        referrer_method_idx_(referrer_method_idx),
253        referrer_invoke_type_(referrer_invoke_type),
254        target_method_idx_(target_method_idx),
255        target_invoke_type_(target_invoke_type),
256        literal_offset_(literal_offset) {
257      CHECK(dex_file_ != NULL);
258    }
259
260    const DexFile* dex_file_;
261    uint32_t referrer_method_idx_;
262    InvokeType referrer_invoke_type_;
263    uint32_t target_method_idx_;
264    InvokeType target_invoke_type_;
265    size_t literal_offset_;
266
267    friend class CompilerDriver;
268    DISALLOW_COPY_AND_ASSIGN(PatchInformation);
269  };
270
271  const std::vector<const PatchInformation*>& GetCodeToPatch() const {
272    return code_to_patch_;
273  }
274  const std::vector<const PatchInformation*>& GetMethodsToPatch() const {
275    return methods_to_patch_;
276  }
277
278  // Checks if class specified by type_idx is one of the image_classes_
279  bool IsImageClass(const char* descriptor) const;
280
281  void RecordClassStatus(ClassReference ref, CompiledClass* compiled_class);
282
283 private:
284  // Compute constant code and method pointers when possible
285  void GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type,
286                                     mirror::Class* referrer_class,
287                                     mirror::AbstractMethod* method,
288                                     uintptr_t& direct_code, uintptr_t& direct_method,
289                                     bool update_stats)
290      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
291
292  void PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
293                  ThreadPool& thread_pool, base::TimingLogger& timings)
294      LOCKS_EXCLUDED(Locks::mutator_lock_);
295
296  void LoadImageClasses(base::TimingLogger& timings);
297
298  // Attempt to resolve all type, methods, fields, and strings
299  // referenced from code in the dex file following PathClassLoader
300  // ordering semantics.
301  void Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
302               ThreadPool& thread_pool, base::TimingLogger& timings)
303      LOCKS_EXCLUDED(Locks::mutator_lock_);
304  void ResolveDexFile(jobject class_loader, const DexFile& dex_file,
305                      ThreadPool& thread_pool, base::TimingLogger& timings)
306      LOCKS_EXCLUDED(Locks::mutator_lock_);
307
308  void Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
309              ThreadPool& thread_pool, base::TimingLogger& timings);
310  void VerifyDexFile(jobject class_loader, const DexFile& dex_file,
311                     ThreadPool& thread_pool, base::TimingLogger& timings)
312      LOCKS_EXCLUDED(Locks::mutator_lock_);
313
314  void InitializeClasses(jobject class_loader, const std::vector<const DexFile*>& dex_files,
315                         ThreadPool& thread_pool, base::TimingLogger& timings)
316      LOCKS_EXCLUDED(Locks::mutator_lock_);
317  void InitializeClasses(jobject class_loader, const DexFile& dex_file,
318                         ThreadPool& thread_pool, base::TimingLogger& timings)
319      LOCKS_EXCLUDED(Locks::mutator_lock_, compiled_classes_lock_);
320
321  void UpdateImageClasses(base::TimingLogger& timings);
322  static void FindClinitImageClassesCallback(mirror::Object* object, void* arg)
323      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
324
325  void Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
326               ThreadPool& thread_pool, base::TimingLogger& timings);
327  void CompileDexFile(jobject class_loader, const DexFile& dex_file,
328                      ThreadPool& thread_pool, base::TimingLogger& timings)
329      LOCKS_EXCLUDED(Locks::mutator_lock_);
330  void CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
331                     InvokeType invoke_type, uint32_t class_def_idx, uint32_t method_idx,
332                     jobject class_loader, const DexFile& dex_file,
333                     DexToDexCompilationLevel dex_to_dex_compilation_level)
334      LOCKS_EXCLUDED(compiled_methods_lock_);
335
336  static void CompileClass(const ParallelCompilationManager* context, size_t class_def_index)
337      LOCKS_EXCLUDED(Locks::mutator_lock_);
338
339  std::vector<const PatchInformation*> code_to_patch_;
340  std::vector<const PatchInformation*> methods_to_patch_;
341
342  CompilerBackend compiler_backend_;
343
344  InstructionSet instruction_set_;
345
346  // All class references that require
347  mutable Mutex freezing_constructor_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
348  std::set<ClassReference> freezing_constructor_classes_ GUARDED_BY(freezing_constructor_lock_);
349
350  typedef SafeMap<const ClassReference, CompiledClass*> ClassTable;
351  // All class references that this compiler has compiled.
352  mutable Mutex compiled_classes_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
353  ClassTable compiled_classes_ GUARDED_BY(compiled_classes_lock_);
354
355  typedef SafeMap<const MethodReference, CompiledMethod*, MethodReferenceComparator> MethodTable;
356  // All method references that this compiler has compiled.
357  mutable Mutex compiled_methods_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
358  MethodTable compiled_methods_ GUARDED_BY(compiled_methods_lock_);
359
360  const bool image_;
361
362  // If image_ is true, specifies the classes that will be included in
363  // the image. Note if image_classes_ is NULL, all classes are
364  // included in the image.
365  UniquePtr<DescriptorSet> image_classes_;
366
367  size_t thread_count_;
368  uint64_t start_ns_;
369
370  UniquePtr<AOTCompilationStats> stats_;
371
372  bool dump_stats_;
373
374  typedef void (*CompilerCallbackFn)(CompilerDriver& driver);
375  typedef MutexLock* (*CompilerMutexLockFn)(CompilerDriver& driver);
376
377  void* compiler_library_;
378
379  typedef CompiledMethod* (*CompilerFn)(CompilerDriver& driver,
380                                        const DexFile::CodeItem* code_item,
381                                        uint32_t access_flags, InvokeType invoke_type,
382                                        uint32_t class_dex_idx, uint32_t method_idx,
383                                        jobject class_loader, const DexFile& dex_file);
384
385  typedef void (*DexToDexCompilerFn)(CompilerDriver& driver,
386                                     const DexFile::CodeItem* code_item,
387                                     uint32_t access_flags, InvokeType invoke_type,
388                                     uint32_t class_dex_idx, uint32_t method_idx,
389                                     jobject class_loader, const DexFile& dex_file,
390                                     DexToDexCompilationLevel dex_to_dex_compilation_level);
391  CompilerFn compiler_;
392#ifdef ART_SEA_IR_MODE
393  CompilerFn sea_ir_compiler_;
394#endif
395
396  DexToDexCompilerFn dex_to_dex_compiler_;
397
398  void* compiler_context_;
399
400  typedef CompiledMethod* (*JniCompilerFn)(CompilerDriver& driver,
401                                           uint32_t access_flags, uint32_t method_idx,
402                                           const DexFile& dex_file);
403  JniCompilerFn jni_compiler_;
404
405  pthread_key_t tls_key_;
406
407  typedef void (*CompilerEnableAutoElfLoadingFn)(CompilerDriver& driver);
408  CompilerEnableAutoElfLoadingFn compiler_enable_auto_elf_loading_;
409
410  typedef const void* (*CompilerGetMethodCodeAddrFn)
411      (const CompilerDriver& driver, const CompiledMethod* cm, const mirror::AbstractMethod* method);
412  CompilerGetMethodCodeAddrFn compiler_get_method_code_addr_;
413
414  bool support_boot_image_fixup_;
415
416  DISALLOW_COPY_AND_ASSIGN(CompilerDriver);
417};
418
419}  // namespace art
420
421#endif  // ART_COMPILER_DRIVER_COMPILER_DRIVER_H_
422