compiler-dispatcher.h 6.96 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_
#define V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_

8
#include <cstdint>
9 10
#include <map>
#include <memory>
11
#include <unordered_set>
12 13
#include <utility>

14
#include "src/base/atomic-utils.h"
15
#include "src/base/macros.h"
16
#include "src/base/optional.h"
17 18
#include "src/base/platform/condition-variable.h"
#include "src/base/platform/mutex.h"
19
#include "src/base/platform/semaphore.h"
20
#include "src/common/globals.h"
21
#include "src/handles/maybe-handles.h"
22
#include "src/utils/identity-map.h"
23
#include "testing/gtest/include/gtest/gtest_prod.h"  // nogncheck
24 25

namespace v8 {
26 27

class Platform;
28
enum class MemoryPressureLevel;
29

30 31
namespace internal {

32
class AstRawString;
33
class AstValueFactory;
34
class BackgroundCompileTask;
35
class CancelableTaskManager;
36
class UnoptimizedCompileJob;
37
class CompilerDispatcherTracer;
38
class FunctionLiteral;
39
class Isolate;
40
class ParseInfo;
41
class SharedFunctionInfo;
42
class TimedHistogram;
43
class WorkerThreadRuntimeCallStats;
44
class Zone;
45 46 47 48

template <typename T>
class Handle;

49 50
// The CompilerDispatcher uses a combination of idle tasks and background tasks
// to parse and compile lazily parsed functions.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
//
// As both parsing and compilation currently requires a preparation and
// finalization step that happens on the main thread, every task has to be
// advanced during idle time first. Depending on the properties of the task, it
// can then be parsed or compiled on either background threads, or during idle
// time. Last, it has to be finalized during idle time again.
//
// CompilerDispatcher::jobs_ maintains the list of all CompilerDispatcherJobs
// the CompilerDispatcher knows about.
//
// CompilerDispatcher::pending_background_jobs_ contains the set of
// CompilerDispatcherJobs that can be processed on a background thread.
//
// CompilerDispatcher::running_background_jobs_ contains the set of
// CompilerDispatcherJobs that are currently being processed on a background
// thread.
//
// CompilerDispatcher::DoIdleWork tries to advance as many jobs out of jobs_ as
// possible during idle time. If a job can't be advanced, but is suitable for
// background processing, it fires off background threads.
//
// CompilerDispatcher::DoBackgroundWork advances one of the pending jobs, and
// then spins of another idle task to potentially do the final step on the main
// thread.
75 76
class V8_EXPORT_PRIVATE CompilerDispatcher {
 public:
77
  using JobId = uintptr_t;
78

79 80
  CompilerDispatcher(Isolate* isolate, Platform* platform,
                     size_t max_stack_size);
81 82
  ~CompilerDispatcher();

83 84 85
  // Returns true if the compiler dispatcher is enabled.
  bool IsEnabled() const;

86 87 88
  base::Optional<JobId> Enqueue(const ParseInfo* outer_parse_info,
                                const AstRawString* function_name,
                                const FunctionLiteral* function_literal);
89

90
  // Registers the given |function| with the compilation job |job_id|.
91
  void RegisterSharedFunctionInfo(JobId job_id, SharedFunctionInfo function);
92

93 94 95 96
  // Returns true if there is a pending job with the given id.
  bool IsEnqueued(JobId job_id) const;

  // Returns true if there is a pending job registered for the given function.
97 98 99
  bool IsEnqueued(Handle<SharedFunctionInfo> function) const;

  // Blocks until the given function is compiled (and does so as fast as
100
  // possible). Returns true if the compile job was successful.
101 102
  bool FinishNow(Handle<SharedFunctionInfo> function);

103 104 105
  // Aborts compilation job |job_id|.
  void AbortJob(JobId job_id);

106 107
  // Aborts all jobs, blocking until all jobs are aborted.
  void AbortAll();
108

109
 private:
110
  FRIEND_TEST(CompilerDispatcherTest, IdleTaskNoIdleTime);
111
  FRIEND_TEST(CompilerDispatcherTest, IdleTaskSmallIdleTime);
112
  FRIEND_TEST(CompilerDispatcherTest, FinishNowWithWorkerTask);
113 114
  FRIEND_TEST(CompilerDispatcherTest, AbortJobNotStarted);
  FRIEND_TEST(CompilerDispatcherTest, AbortJobAlreadyStarted);
115 116
  FRIEND_TEST(CompilerDispatcherTest, AsyncAbortAllPendingWorkerTask);
  FRIEND_TEST(CompilerDispatcherTest, AsyncAbortAllRunningWorkerTask);
117
  FRIEND_TEST(CompilerDispatcherTest, CompileMultipleOnBackgroundThread);
118

119 120 121 122
  struct Job {
    explicit Job(BackgroundCompileTask* task_arg);
    ~Job();

123
    bool IsReadyToFinalize(const base::MutexGuard&) {
124
      return has_run && (!function.is_null() || aborted);
125 126 127
    }

    bool IsReadyToFinalize(base::Mutex* mutex) {
128
      base::MutexGuard lock(mutex);
129 130 131 132 133 134
      return IsReadyToFinalize(lock);
    }

    std::unique_ptr<BackgroundCompileTask> task;
    MaybeHandle<SharedFunctionInfo> function;
    bool has_run;
135
    bool aborted;
136 137
  };

138 139
  using JobMap = std::map<JobId, std::unique_ptr<Job>>;
  using SharedToJobIdMap = IdentityMap<JobId, FreeStoreAllocationPolicy>;
140 141

  void WaitForJobIfRunningOnBackground(Job* job);
142
  JobMap::const_iterator GetJobFor(Handle<SharedFunctionInfo> shared) const;
143
  void ScheduleMoreWorkerTasksIfNeeded();
144
  void ScheduleIdleTaskFromAnyThread(const base::MutexGuard&);
145
  void DoBackgroundWork();
146
  void DoIdleWork(double deadline_in_seconds);
147
  // Returns iterator to the inserted job.
148
  JobMap::const_iterator InsertJob(std::unique_ptr<Job> job);
149 150
  // Returns iterator following the removed job.
  JobMap::const_iterator RemoveJob(JobMap::const_iterator job);
151 152

  Isolate* isolate_;
153
  WorkerThreadRuntimeCallStats* worker_thread_runtime_call_stats_;
154
  TimedHistogram* background_compile_timer_;
155
  std::shared_ptr<v8::TaskRunner> taskrunner_;
156
  Platform* platform_;
157
  size_t max_stack_size_;
158 159 160 161

  // Copy of FLAG_trace_compiler_dispatcher to allow for access from any thread.
  bool trace_compiler_dispatcher_;

162
  std::unique_ptr<CancelableTaskManager> task_manager_;
163

164 165 166 167
  // Id for next job to be added
  JobId next_job_id_;

  // Mapping from job_id to job.
168
  JobMap jobs_;
169

170 171 172
  // Mapping from SharedFunctionInfo to the corresponding unoptimized
  // compilation's JobId;
  SharedToJobIdMap shared_to_unoptimized_job_id_;
173

174 175 176 177
  // The following members can be accessed from any thread. Methods need to hold
  // the mutex |mutex_| while accessing them.
  base::Mutex mutex_;

178
  // True if an idle task is scheduled to be run.
179 180
  bool idle_task_scheduled_;

181 182
  // Number of scheduled or running WorkerTask objects.
  int num_worker_tasks_;
183

184 185
  // The set of jobs that can be run on a background thread.
  std::unordered_set<Job*> pending_background_jobs_;
186

187 188
  // The set of jobs currently being run on background threads.
  std::unordered_set<Job*> running_background_jobs_;
189 190 191

  // If not nullptr, then the main thread waits for the task processing
  // this job, and blocks on the ConditionVariable main_thread_blocking_signal_.
192
  Job* main_thread_blocking_on_job_;
193 194
  base::ConditionVariable main_thread_blocking_signal_;

195 196 197 198
  // Test support.
  base::AtomicValue<bool> block_for_testing_;
  base::Semaphore semaphore_for_testing_;

199 200 201 202 203 204 205
  DISALLOW_COPY_AND_ASSIGN(CompilerDispatcher);
};

}  // namespace internal
}  // namespace v8

#endif  // V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_