blob: bc039f1df27f37cd36aa75ff4c32bafe090a13a1 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerValueBitMap.h - INTERNAL - Bit map -----------------*- C++ -* ===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
george.karpenkov29efa6d2017-08-21 23:25:50 +00006//
7//===----------------------------------------------------------------------===//
8// ValueBitMap.
9//===----------------------------------------------------------------------===//
10
11#ifndef LLVM_FUZZER_VALUE_BIT_MAP_H
12#define LLVM_FUZZER_VALUE_BIT_MAP_H
13
14#include "FuzzerDefs.h"
15
16namespace fuzzer {
17
18// A bit map containing kMapSizeInWords bits.
19struct ValueBitMap {
20 static const size_t kMapSizeInBits = 1 << 16;
21 static const size_t kMapPrimeMod = 65371; // Largest Prime < kMapSizeInBits;
22 static const size_t kBitsInWord = (sizeof(uintptr_t) * 8);
23 static const size_t kMapSizeInWords = kMapSizeInBits / kBitsInWord;
24 public:
25
26 // Clears all bits.
27 void Reset() { memset(Map, 0, sizeof(Map)); }
28
29 // Computes a hash function of Value and sets the corresponding bit.
30 // Returns true if the bit was changed from 0 to 1.
31 ATTRIBUTE_NO_SANITIZE_ALL
32 inline bool AddValue(uintptr_t Value) {
33 uintptr_t Idx = Value % kMapSizeInBits;
34 uintptr_t WordIdx = Idx / kBitsInWord;
35 uintptr_t BitIdx = Idx % kBitsInWord;
36 uintptr_t Old = Map[WordIdx];
metzman1c6a8592019-01-22 18:59:25 +000037 uintptr_t New = Old | (1ULL << BitIdx);
george.karpenkov29efa6d2017-08-21 23:25:50 +000038 Map[WordIdx] = New;
39 return New != Old;
40 }
41
42 ATTRIBUTE_NO_SANITIZE_ALL
43 inline bool AddValueModPrime(uintptr_t Value) {
44 return AddValue(Value % kMapPrimeMod);
45 }
46
47 inline bool Get(uintptr_t Idx) {
48 assert(Idx < kMapSizeInBits);
49 uintptr_t WordIdx = Idx / kBitsInWord;
50 uintptr_t BitIdx = Idx % kBitsInWord;
metzman1c6a8592019-01-22 18:59:25 +000051 return Map[WordIdx] & (1ULL << BitIdx);
george.karpenkov29efa6d2017-08-21 23:25:50 +000052 }
53
54 size_t SizeInBits() const { return kMapSizeInBits; }
55
56 template <class Callback>
57 ATTRIBUTE_NO_SANITIZE_ALL
58 void ForEach(Callback CB) const {
59 for (size_t i = 0; i < kMapSizeInWords; i++)
60 if (uintptr_t M = Map[i])
61 for (size_t j = 0; j < sizeof(M) * 8; j++)
62 if (M & ((uintptr_t)1 << j))
63 CB(i * sizeof(M) * 8 + j);
64 }
65
66 private:
metzman2fe66e62019-01-17 16:36:05 +000067 ATTRIBUTE_ALIGNED(512) uintptr_t Map[kMapSizeInWords];
george.karpenkov29efa6d2017-08-21 23:25:50 +000068};
69
70} // namespace fuzzer
71
72#endif // LLVM_FUZZER_VALUE_BIT_MAP_H