2 * Copyright (c) 2018-2020 Inria
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * Definition of a dictionary based cache compressor. Each entry is compared
31 * against a dictionary to search for matches.
33 * The dictionary is composed of 32-bit entries, and the comparison is done
36 * The patterns are implemented as individual classes that have a checking
37 * function isPattern(), to determine if the data fits the pattern, and a
38 * decompress() function, which decompresses the contents of a pattern.
39 * Every new pattern must inherit from the Pattern class and be added to the
43 #ifndef __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_HH__
44 #define __MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_HH__
51 #include <type_traits>
54 #include "base/statistics.hh"
55 #include "base/types.hh"
56 #include "mem/cache/compressors/base.hh"
58 struct BaseDictionaryCompressorParams;
60 namespace Compressor {
62 class BaseDictionaryCompressor : public Base
65 /** Dictionary size. */
66 const std::size_t dictionarySize;
68 /** Number of valid entries in the dictionary. */
69 std::size_t numEntries;
71 struct DictionaryStats : public Stats::Group
73 const BaseDictionaryCompressor& compressor;
75 DictionaryStats(BaseStats &base_group,
76 BaseDictionaryCompressor& _compressor);
78 void regStats() override;
80 /** Number of data entries that were compressed to each pattern. */
81 Stats::Vector patterns;
85 * Trick function to get the number of patterns.
87 * @return The number of defined patterns.
89 virtual uint64_t getNumPatterns() const = 0;
92 * Get meta-name assigned to the given pattern.
94 * @param number The number of the pattern.
95 * @return The meta-name of the pattern.
97 virtual std::string getName(int number) const = 0;
100 typedef BaseDictionaryCompressorParams Params;
101 BaseDictionaryCompressor(const Params *p);
102 ~BaseDictionaryCompressor() = default;
106 * A template version of the dictionary compressor that allows to choose the
109 * @tparam The type of a dictionary entry (e.g., uint16_t, uint32_t, etc).
112 class DictionaryCompressor : public BaseDictionaryCompressor
115 /** Convenience typedef for a dictionary entry. */
116 typedef std::array<uint8_t, sizeof(T)> DictionaryEntry;
119 * Compression data for the dictionary compressor. It consists of a vector
124 // Forward declaration of a pattern
126 class UncompressedPattern;
129 template <T value, T mask>
130 class MaskedValuePattern;
131 template <T mask, int location>
132 class LocatedMaskedPattern;
133 template <class RepT>
134 class RepeatedValuePattern;
135 template <std::size_t DeltaSizeBits>
139 * Create a factory to determine if input matches a pattern. The if else
140 * chains are constructed by recursion. The patterns should be explored
141 * sorted by size for correct behaviour.
143 template <class Head, class... Tail>
146 static std::unique_ptr<Pattern> getPattern(
147 const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
148 const int match_location)
150 // If match this pattern, instantiate it. If a negative match
151 // location is used, the patterns that use the dictionary bytes
152 // must return false. This is used when there are no dictionary
154 if (Head::isPattern(bytes, dict_bytes, match_location)) {
155 return std::unique_ptr<Pattern>(
156 new Head(bytes, match_location));
157 // Otherwise, go for next pattern
159 return Factory<Tail...>::getPattern(bytes, dict_bytes,
166 * Specialization to end the recursion. This must be called when all
167 * other patterns failed, and there is no choice but to leave data
168 * uncompressed. As such, this pattern must inherit from the uncompressed
171 template <class Head>
174 static_assert(std::is_base_of<UncompressedPattern, Head>::value,
175 "The last pattern must always be derived from the uncompressed "
178 static std::unique_ptr<Pattern>
179 getPattern(const DictionaryEntry& bytes,
180 const DictionaryEntry& dict_bytes, const int match_location)
182 return std::unique_ptr<Pattern>(new Head(bytes, match_location));
186 /** The dictionary. */
187 std::vector<DictionaryEntry> dictionary;
190 * Since the factory cannot be instantiated here, classes that inherit
191 * from this base class have to implement the call to their factory's
194 virtual std::unique_ptr<Pattern>
195 getPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
196 const int match_location) const = 0;
201 * @param data Data to be compressed.
202 * @return The pattern this data matches.
204 std::unique_ptr<Pattern> compressValue(const T data);
207 * Decompress a pattern into a value that fits in a dictionary entry.
209 * @param pattern The pattern to be decompressed.
210 * @return The decompressed word.
212 T decompressValue(const Pattern* pattern);
214 /** Clear all dictionary entries. */
215 virtual void resetDictionary();
218 * Add an entry to the dictionary.
220 * @param data The new entry.
222 virtual void addToDictionary(const DictionaryEntry data) = 0;
227 * @param data The cache line to be compressed.
228 * @return Cache line after compression.
230 std::unique_ptr<Base::CompressionData> compress(const uint64_t* data);
232 using BaseDictionaryCompressor::compress;
237 * @param comp_data Compressed cache line.
238 * @param data The cache line to be decompressed.
240 void decompress(const CompressionData* comp_data, uint64_t* data) override;
243 * Turn a value into a dictionary entry.
245 * @param value The value to turn.
246 * @return A dictionary entry containing the value.
248 static DictionaryEntry toDictionaryEntry(T value);
251 * Turn a dictionary entry into a value.
253 * @param The dictionary entry to turn.
254 * @return The value that the dictionary entry contained.
256 static T fromDictionaryEntry(const DictionaryEntry& entry);
259 typedef BaseDictionaryCompressorParams Params;
260 DictionaryCompressor(const Params *p);
261 ~DictionaryCompressor() = default;
265 * The compressed data is composed of multiple pattern entries. To add a new
266 * pattern one should inherit from this class and implement isPattern() and
267 * decompress(). Then the new pattern must be added to the PatternFactory
268 * declaration in crescent order of size (in the DictionaryCompressor class).
271 class DictionaryCompressor<T>::Pattern
274 /** Pattern enum number. */
275 const int patternNumber;
277 /** Code associated to the pattern. */
280 /** Length, in bits, of the code and match location. */
281 const uint8_t length;
283 /** Number of unmatched bits. */
284 const uint8_t numUnmatchedBits;
286 /** Index representing the the match location. */
287 const int matchLocation;
289 /** Wether the pattern allocates a dictionary entry or not. */
294 * Default constructor.
296 * @param number Pattern number.
297 * @param code Code associated to this pattern.
298 * @param metadata_length Length, in bits, of the code and match location.
299 * @param num_unmatched_bits Number of unmatched bits.
300 * @param match_location Index of the match location.
302 Pattern(const int number, const uint64_t code,
303 const uint64_t metadata_length, const uint64_t num_unmatched_bits,
304 const int match_location, const bool allocate = true)
305 : patternNumber(number), code(code), length(metadata_length),
306 numUnmatchedBits(num_unmatched_bits),
307 matchLocation(match_location), allocate(allocate)
311 /** Default destructor. */
312 virtual ~Pattern() = default;
315 * Get enum number associated to this pattern.
317 * @return The pattern enum number.
319 int getPatternNumber() const { return patternNumber; };
322 * Get code of this pattern.
326 uint8_t getCode() const { return code; }
329 * Get the index of the dictionary match location.
331 * @return The index of the match location.
333 uint8_t getMatchLocation() const { return matchLocation; }
336 * Get size, in bits, of the pattern (excluding prefix). Corresponds to
337 * unmatched_data_size + code_length.
344 return numUnmatchedBits + length;
348 * Determine if pattern allocates a dictionary entry.
350 * @return True if should allocate a dictionary entry.
352 bool shouldAllocate() const { return allocate; }
355 * Extract pattern's information to a string.
357 * @return A string containing the relevant pattern metadata.
362 return csprintf("pattern %s (encoding %x, size %u bits)",
363 getPatternNumber(), getCode(), getSizeBits());
367 * Decompress the pattern. Each pattern has its own way of interpreting
370 * @param dict_bytes The bytes in the corresponding matching entry.
371 * @return The decompressed pattern.
373 virtual DictionaryEntry decompress(
374 const DictionaryEntry dict_bytes) const = 0;
378 class DictionaryCompressor<T>::CompData : public CompressionData
381 /** The patterns matched in the original line. */
382 std::vector<std::unique_ptr<Pattern>> entries;
385 ~CompData() = default;
388 * Add a pattern entry to the list of patterns.
390 * @param entry The new pattern entry.
392 virtual void addEntry(std::unique_ptr<Pattern>);
396 * A pattern containing the original uncompressed data. This should be the
397 * worst case of every pattern factory, where if all other patterns fail,
398 * an instance of this pattern is created.
401 class DictionaryCompressor<T>::UncompressedPattern
402 : public DictionaryCompressor<T>::Pattern
405 /** A copy of the original data. */
406 const DictionaryEntry data;
409 UncompressedPattern(const int number,
411 const uint64_t metadata_length,
412 const int match_location,
413 const DictionaryEntry bytes)
414 : DictionaryCompressor<T>::Pattern(number, code, metadata_length,
415 sizeof(T) * 8, match_location, true),
421 isPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
422 const int match_location)
424 // An entry can always be uncompressed
429 decompress(const DictionaryEntry dict_bytes) const override
436 * A pattern that compares masked values against dictionary entries. If
437 * the masked dictionary entry matches perfectly the masked value to be
438 * compressed, there is a pattern match.
440 * For example, if the mask is 0xFF00 (that is, this pattern matches the MSB),
441 * the value (V) 0xFF20 is being compressed, and the dictionary contains
442 * the value (D) 0xFF03, this is a match (V & mask == 0xFF00 == D & mask),
443 * and 0x0020 is added to the list of unmatched bits.
445 * @tparam mask A mask containing the bits that must match.
449 class DictionaryCompressor<T>::MaskedPattern
450 : public DictionaryCompressor<T>::Pattern
453 static_assert(mask != 0, "The pattern's value mask must not be zero. Use "
454 "the uncompressed pattern instead.");
456 /** A copy of the bits that do not belong to the mask. */
460 MaskedPattern(const int number,
462 const uint64_t metadata_length,
463 const int match_location,
464 const DictionaryEntry bytes,
465 const bool allocate = true)
466 : DictionaryCompressor<T>::Pattern(number, code, metadata_length,
467 popCount(static_cast<T>(~mask)), match_location, allocate),
468 bits(DictionaryCompressor<T>::fromDictionaryEntry(bytes) & ~mask)
473 isPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
474 const int match_location)
476 const T masked_bytes =
477 DictionaryCompressor<T>::fromDictionaryEntry(bytes) & mask;
478 const T masked_dict_bytes =
479 DictionaryCompressor<T>::fromDictionaryEntry(dict_bytes) & mask;
480 return (match_location >= 0) && (masked_bytes == masked_dict_bytes);
484 decompress(const DictionaryEntry dict_bytes) const override
486 const T masked_dict_bytes =
487 DictionaryCompressor<T>::fromDictionaryEntry(dict_bytes) & mask;
488 return DictionaryCompressor<T>::toDictionaryEntry(
489 bits | masked_dict_bytes);
494 * A pattern that compares masked values to a masked portion of a fixed value.
495 * If all the masked bits match the provided non-dictionary value, there is a
498 * For example, assume the mask is 0xFF00 (that is, this pattern matches the
499 * MSB), and we are searching for data containing only ones (i.e., the fixed
501 * If the value (V) 0xFF20 is being compressed, this is a match (V & mask ==
502 * 0xFF00 == 0xFFFF & mask), and 0x20 is added to the list of unmatched bits.
503 * If the value (V2) 0x0120 is being compressed, this is not a match
504 * ((V2 & mask == 0x0100) != (0xFF00 == 0xFFFF & mask).
506 * @tparam value The value that is being matched against.
507 * @tparam mask A mask containing the bits that must match the given value.
510 template <T value, T mask>
511 class DictionaryCompressor<T>::MaskedValuePattern
512 : public MaskedPattern<mask>
515 static_assert(mask != 0, "The pattern's value mask must not be zero.");
518 MaskedValuePattern(const int number,
520 const uint64_t metadata_length,
521 const int match_location,
522 const DictionaryEntry bytes,
523 const bool allocate = false)
524 : MaskedPattern<mask>(number, code, metadata_length, match_location,
530 isPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
531 const int match_location)
533 // Compare the masked fixed value to the value being checked for
534 // patterns. Since the dictionary is not being used the match_location
536 const T masked_bytes =
537 DictionaryCompressor<T>::fromDictionaryEntry(bytes) & mask;
538 return ((value & mask) == masked_bytes);
542 decompress(const DictionaryEntry dict_bytes) const override
544 return MaskedPattern<mask>::decompress(
545 DictionaryCompressor<T>::toDictionaryEntry(value));
550 * A pattern that narrows the MaskedPattern by allowing a only single possible
551 * dictionary entry to be matched against.
553 * @tparam mask A mask containing the bits that must match.
554 * @tparam location The index of the single entry allowed to match.
557 template <T mask, int location>
558 class DictionaryCompressor<T>::LocatedMaskedPattern
559 : public MaskedPattern<mask>
562 LocatedMaskedPattern(const int number,
564 const uint64_t metadata_length,
565 const int match_location,
566 const DictionaryEntry bytes,
567 const bool allocate = true)
568 : MaskedPattern<mask>(number, code, metadata_length, match_location,
574 isPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
575 const int match_location)
577 // Besides doing the regular masked pattern matching, the match
578 // location must match perfectly with this instance's
579 return (match_location == location) &&
580 MaskedPattern<mask>::isPattern(bytes, dict_bytes, match_location);
585 * A pattern that checks if dictionary entry sized values are solely composed
586 * of multiple copies of a single value.
588 * For example, if we are looking for repeated bytes in a 1-byte granularity
589 * (RepT is uint8_t), the value 0x3232 would match, however 0x3332 wouldn't.
591 * @tparam RepT The type of the repeated value, which must fit in a dictionary
595 template <class RepT>
596 class DictionaryCompressor<T>::RepeatedValuePattern
597 : public DictionaryCompressor<T>::Pattern
600 static_assert(sizeof(T) > sizeof(RepT), "The repeated value's type must "
601 "be smaller than the dictionary entry's type.");
603 /** The repeated value. */
607 RepeatedValuePattern(const int number,
609 const uint64_t metadata_length,
610 const int match_location,
611 const DictionaryEntry bytes,
612 const bool allocate = true)
613 : DictionaryCompressor<T>::Pattern(number, code, metadata_length,
614 8 * sizeof(RepT), match_location, allocate),
615 value(DictionaryCompressor<T>::fromDictionaryEntry(bytes))
620 isPattern(const DictionaryEntry& bytes, const DictionaryEntry& dict_bytes,
621 const int match_location)
623 // Parse the dictionary entry in a RepT granularity, and if all values
624 // are equal, this is a repeated value pattern. Since the dictionary
625 // is not being used, the match_location is irrelevant
626 T bytes_value = DictionaryCompressor<T>::fromDictionaryEntry(bytes);
627 const RepT rep_value = bytes_value;
628 for (int i = 0; i < (sizeof(T) / sizeof(RepT)); i++) {
629 RepT cur_value = bytes_value;
630 if (cur_value != rep_value) {
633 bytes_value >>= 8 * sizeof(RepT);
639 decompress(const DictionaryEntry dict_bytes) const override
641 // The decompressed value is just multiple consecutive instances of
644 for (int i = 0; i < (sizeof(T) / sizeof(RepT)); i++) {
645 decomp_value <<= 8 * sizeof(RepT);
646 decomp_value |= value;
648 return DictionaryCompressor<T>::toDictionaryEntry(decomp_value);
653 * A pattern that checks whether the difference of the value and the dictionary
654 * entries' is below a certain threshold. If so, the pattern is successful,
655 * and only the delta bits need to be stored.
657 * For example, if the delta can only contain up to 4 bits, and the dictionary
658 * contains the entry 0xA231, the value 0xA232 would be compressible, and
659 * the delta 0x1 would be stored. The value 0xA249, on the other hand, would
660 * not be compressible, since its delta (0x18) needs 5 bits to be stored.
662 * @tparam DeltaSizeBits Size of a delta entry, in number of bits, which
663 * determines the threshold. Must always be smaller
664 * than the dictionary entry type's size.
667 template <std::size_t DeltaSizeBits>
668 class DictionaryCompressor<T>::DeltaPattern
669 : public DictionaryCompressor<T>::Pattern
672 static_assert(DeltaSizeBits < (sizeof(T) * 8),
673 "Delta size must be smaller than base size");
676 * The original value. In theory we should keep only the deltas, but
677 * the dictionary entry is not inserted in the dictionary before the
678 * call to the constructor, so the delta cannot be calculated then.
680 const DictionaryEntry bytes;
683 DeltaPattern(const int number,
685 const uint64_t metadata_length,
686 const int match_location,
687 const DictionaryEntry bytes)
688 : DictionaryCompressor<T>::Pattern(number, code, metadata_length,
689 DeltaSizeBits, match_location, false),
695 * Compares a given value against a base to calculate their delta, and
696 * then determines whether it fits a limited sized container.
698 * @param bytes Value to be compared against base.
699 * @param base_bytes Base value.
700 * @return Whether the value fits in the container.
703 isValidDelta(const DictionaryEntry& bytes,
704 const DictionaryEntry& base_bytes)
706 const typename std::make_signed<T>::type limit = DeltaSizeBits ?
707 mask(DeltaSizeBits - 1) : 0;
709 DictionaryCompressor<T>::fromDictionaryEntry(bytes);
711 DictionaryCompressor<T>::fromDictionaryEntry(base_bytes);
712 const typename std::make_signed<T>::type delta = value - base;
713 return (delta >= -limit) && (delta <= limit);
717 isPattern(const DictionaryEntry& bytes,
718 const DictionaryEntry& dict_bytes, const int match_location)
720 return (match_location >= 0) && isValidDelta(bytes, dict_bytes);
724 decompress(const DictionaryEntry dict_bytes) const override
730 } // namespace Compressor
732 #endif //__MEM_CACHE_COMPRESSORS_DICTIONARY_COMPRESSOR_HH__