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