wasm-import-wrapper-cache.h 2.39 KB
Newer Older
1 2 3 4
// Copyright 2018 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.

5 6
#ifndef V8_WASM_WASM_IMPORT_WRAPPER_CACHE_H_
#define V8_WASM_WASM_IMPORT_WRAPPER_CACHE_H_
7

8
#include "src/base/platform/mutex.h"
9 10 11 12
#include "src/compiler/wasm-compiler.h"

namespace v8 {
namespace internal {
13 14 15

class Counters;

16 17
namespace wasm {

18 19 20 21 22
class WasmCode;
class WasmEngine;

using FunctionSig = Signature<ValueType>;

23 24 25
// Implements a cache for import wrappers.
class WasmImportWrapperCache {
 public:
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  struct CacheKey {
    CacheKey(const compiler::WasmImportCallKind& _kind, const FunctionSig* _sig,
             int _expected_arity)
        : kind(_kind),
          signature(_sig),
          expected_arity(_expected_arity == kDontAdaptArgumentsSentinel
                             ? 0
                             : _expected_arity) {}

    bool operator==(const CacheKey& rhs) const {
      return kind == rhs.kind && signature == rhs.signature &&
             expected_arity == rhs.expected_arity;
    }

    compiler::WasmImportCallKind kind;
    const FunctionSig* signature;
    int expected_arity;
  };
44

45 46 47
  class CacheKeyHash {
   public:
    size_t operator()(const CacheKey& key) const {
48 49
      return base::hash_combine(static_cast<uint8_t>(key.kind), key.signature,
                                key.expected_arity);
50 51
    }
  };
52

53
  // Helper class to modify the cache under a lock.
54
  class V8_NODISCARD ModificationScope {
55 56 57 58 59 60 61 62 63 64
   public:
    explicit ModificationScope(WasmImportWrapperCache* cache)
        : cache_(cache), guard_(&cache->mutex_) {}

    V8_EXPORT_PRIVATE WasmCode*& operator[](const CacheKey& key);

   private:
    WasmImportWrapperCache* const cache_;
    base::MutexGuard guard_;
  };
65

66 67 68 69
  // Not thread-safe, use ModificationScope to get exclusive write access to the
  // cache.
  V8_EXPORT_PRIVATE WasmCode*& operator[](const CacheKey& key);

70
  // Thread-safe. Assumes the key exists in the map.
71
  V8_EXPORT_PRIVATE WasmCode* Get(compiler::WasmImportCallKind kind,
72 73
                                  const FunctionSig* sig,
                                  int expected_arity) const;
74

75 76 77
  ~WasmImportWrapperCache();

 private:
78
  mutable base::Mutex mutex_;
79
  std::unordered_map<CacheKey, WasmCode*, CacheKeyHash> entry_map_;
80 81 82 83 84 85
};

}  // namespace wasm
}  // namespace internal
}  // namespace v8

86
#endif  // V8_WASM_WASM_IMPORT_WRAPPER_CACHE_H_