]> wimlib.net Git - wimlib/blob - include/wimlib/hc_matchfinder.h
Use MIT license instead of CC0
[wimlib] / include / wimlib / hc_matchfinder.h
1 /*
2  * hc_matchfinder.h - Lempel-Ziv matchfinding with a hash table of linked lists
3  *
4  * Copyright 2022 Eric Biggers
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use,
10  * copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following
13  * conditions:
14  *
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  *
27  * ---------------------------------------------------------------------------
28  *
29  *                                 Algorithm
30  *
31  * This is a Hash Chains (hc) based matchfinder.
32  *
33  * The main data structure is a hash table where each hash bucket contains a
34  * linked list (or "chain") of sequences whose first 4 bytes share the same hash
35  * code.  Each sequence is identified by its starting position in the input
36  * buffer.
37  *
38  * The algorithm processes the input buffer sequentially.  At each byte
39  * position, the hash code of the first 4 bytes of the sequence beginning at
40  * that position (the sequence being matched against) is computed.  This
41  * identifies the hash bucket to use for that position.  Then, this hash
42  * bucket's linked list is searched for matches.  Then, a new linked list node
43  * is created to represent the current sequence and is prepended to the list.
44  *
45  * This algorithm has several useful properties:
46  *
47  * - It only finds true Lempel-Ziv matches; i.e., those where the matching
48  *   sequence occurs prior to the sequence being matched against.
49  *
50  * - The sequences in each linked list are always sorted by decreasing starting
51  *   position.  Therefore, the closest (smallest offset) matches are found
52  *   first, which in many compression formats tend to be the cheapest to encode.
53  *
54  * - Although fast running time is not guaranteed due to the possibility of the
55  *   lists getting very long, the worst degenerate behavior can be easily
56  *   prevented by capping the number of nodes searched at each position.
57  *
58  * - If the compressor decides not to search for matches at a certain position,
59  *   then that position can be quickly inserted without searching the list.
60  *
61  * - The algorithm is adaptable to sliding windows: just store the positions
62  *   relative to a "base" value that is updated from time to time, and stop
63  *   searching each list when the sequences get too far away.
64  *
65  * ---------------------------------------------------------------------------
66  *
67  *                              Notes on usage
68  *
69  * Before including this header, you must define 'mf_pos_t' to an integer type
70  * that can represent all possible positions.  This can be a 16-bit or 32-bit
71  * unsigned integer.  When possible, the former should be used due to the
72  * reduced cache pressure.  This header can be included multiple times in a
73  * single .c file with different 'mf_pos_t' definitions; however, you must
74  * define a different MF_SUFFIX each time to generate different names for the
75  * matchfinder structure and functions.
76  *
77  * The number of bytes that must be allocated for a given 'struct
78  * hc_matchfinder' must be gotten by calling hc_matchfinder_size().
79  *
80  * ----------------------------------------------------------------------------
81  *
82  *                               Optimizations
83  *
84  * The main hash table and chains handle length 4+ matches.  Length 3 matches
85  * are handled by a separate hash table with no chains.  This works well for
86  * typical "greedy" or "lazy"-style compressors, where length 3 matches are
87  * often only helpful if they have small offsets.  Instead of searching a full
88  * chain for length 3+ matches, the algorithm just checks for one close length 3
89  * match, then focuses on finding length 4+ matches.
90  *
91  * The longest_match() and skip_positions() functions are inlined into the
92  * compressors that use them.  This isn't just about saving the overhead of a
93  * function call.  These functions are intended to be called from the inner
94  * loops of compressors, where giving the compiler more control over register
95  * allocation is very helpful.  There is also significant benefit to be gained
96  * from allowing the CPU to predict branches independently at each call site.
97  * For example, "lazy"-style compressors can be written with two calls to
98  * longest_match(), each of which starts with a different 'best_len' and
99  * therefore has significantly different performance characteristics.
100  *
101  * Although any hash function can be used, a multiplicative hash is fast and
102  * works well.
103  *
104  * On some processors, it is significantly faster to extend matches by whole
105  * words (32 or 64 bits) instead of by individual bytes.  For this to be the
106  * case, the processor must implement unaligned memory accesses efficiently and
107  * must have either a fast "find first set bit" instruction or a fast "find last
108  * set bit" instruction, depending on the processor's endianness.
109  *
110  * The code uses one loop for finding the first match and one loop for finding a
111  * longer match.  Each of these loops is tuned for its respective task and in
112  * combination are faster than a single generalized loop that handles both
113  * tasks.
114  *
115  * The code also uses a tight inner loop that only compares the last and first
116  * bytes of a potential match.  It is only when these bytes match that a full
117  * match extension is attempted.
118  *
119  * ----------------------------------------------------------------------------
120  */
121
122 #include <string.h>
123
124 #include "wimlib/lz_extend.h"
125 #include "wimlib/lz_hash.h"
126 #include "wimlib/unaligned.h"
127
128 #define HC_MATCHFINDER_HASH3_ORDER      14
129 #define HC_MATCHFINDER_HASH4_ORDER      15
130
131 /* TEMPLATED functions and structures have MF_SUFFIX appended to their name.  */
132 #undef TEMPLATED
133 #define TEMPLATED(name)         CONCAT(name, MF_SUFFIX)
134
135 struct TEMPLATED(hc_matchfinder) {
136
137         /* The hash table for finding length 3 matches  */
138         mf_pos_t hash3_tab[1UL << HC_MATCHFINDER_HASH3_ORDER];
139
140         /* The hash table which contains the first nodes of the linked lists for
141          * finding length 4+ matches  */
142         mf_pos_t hash4_tab[1UL << HC_MATCHFINDER_HASH4_ORDER];
143
144         /* The "next node" references for the linked lists.  The "next node" of
145          * the node for the sequence with position 'pos' is 'next_tab[pos]'.  */
146         mf_pos_t next_tab[];
147 };
148
149 /* Return the number of bytes that must be allocated for a 'hc_matchfinder' that
150  * can work with buffers up to the specified size.  */
151 static forceinline size_t
152 TEMPLATED(hc_matchfinder_size)(size_t max_bufsize)
153 {
154         return sizeof(struct TEMPLATED(hc_matchfinder)) +
155                 (max_bufsize * sizeof(mf_pos_t));
156 }
157
158 /* Prepare the matchfinder for a new input buffer.  */
159 static forceinline void
160 TEMPLATED(hc_matchfinder_init)(struct TEMPLATED(hc_matchfinder) *mf)
161 {
162         memset(mf, 0, sizeof(*mf));
163 }
164
165 /*
166  * Find the longest match longer than 'best_len' bytes.
167  *
168  * @mf
169  *      The matchfinder structure.
170  * @in_begin
171  *      Pointer to the beginning of the input buffer.
172  * @cur_pos
173  *      The current position in the input buffer (the position of the sequence
174  *      being matched against).
175  * @best_len
176  *      Require a match longer than this length.
177  * @max_len
178  *      The maximum permissible match length at this position.
179  * @nice_len
180  *      Stop searching if a match of at least this length is found.
181  *      Must be <= @max_len.
182  * @max_search_depth
183  *      Limit on the number of potential matches to consider.  Must be >= 1.
184  * @next_hashes
185  *      The precomputed hash codes for the sequence beginning at @in_next.
186  *      These will be used and then updated with the precomputed hashcodes for
187  *      the sequence beginning at @in_next + 1.
188  * @offset_ret
189  *      If a match is found, its offset is returned in this location.
190  *
191  * Return the length of the match found, or 'best_len' if no match longer than
192  * 'best_len' was found.
193  */
194 static forceinline u32
195 TEMPLATED(hc_matchfinder_longest_match)(struct TEMPLATED(hc_matchfinder) * const restrict mf,
196                                         const u8 * const restrict in_begin,
197                                         const ptrdiff_t cur_pos,
198                                         u32 best_len,
199                                         const u32 max_len,
200                                         const u32 nice_len,
201                                         const u32 max_search_depth,
202                                         u32 next_hashes[const restrict static 2],
203                                         u32 * const restrict offset_ret)
204 {
205         const u8 *in_next = in_begin + cur_pos;
206         u32 depth_remaining = max_search_depth;
207         const u8 *best_matchptr = in_next;
208         mf_pos_t cur_node3, cur_node4;
209         u32 hash3, hash4;
210         u32 next_seq3, next_seq4;
211         u32 seq4;
212         const u8 *matchptr;
213         u32 len;
214
215         if (unlikely(max_len < 5)) /* can we read 4 bytes from 'in_next + 1'? */
216                 goto out;
217
218         /* Get the precomputed hash codes.  */
219         hash3 = next_hashes[0];
220         hash4 = next_hashes[1];
221
222         /* From the hash buckets, get the first node of each linked list.  */
223         cur_node3 = mf->hash3_tab[hash3];
224         cur_node4 = mf->hash4_tab[hash4];
225
226         /* Update for length 3 matches.  This replaces the singleton node in the
227          * 'hash3' bucket with the node for the current sequence.  */
228         mf->hash3_tab[hash3] = cur_pos;
229
230         /* Update for length 4 matches.  This prepends the node for the current
231          * sequence to the linked list in the 'hash4' bucket.  */
232         mf->hash4_tab[hash4] = cur_pos;
233         mf->next_tab[cur_pos] = cur_node4;
234
235         /* Compute the next hash codes.  */
236         next_seq4 = load_u32_unaligned(in_next + 1);
237         next_seq3 = loaded_u32_to_u24(next_seq4);
238         next_hashes[0] = lz_hash(next_seq3, HC_MATCHFINDER_HASH3_ORDER);
239         next_hashes[1] = lz_hash(next_seq4, HC_MATCHFINDER_HASH4_ORDER);
240         prefetchw(&mf->hash3_tab[next_hashes[0]]);
241         prefetchw(&mf->hash4_tab[next_hashes[1]]);
242
243         if (best_len < 4) {  /* No match of length >= 4 found yet?  */
244
245                 /* Check for a length 3 match if needed.  */
246
247                 if (!cur_node3)
248                         goto out;
249
250                 seq4 = load_u32_unaligned(in_next);
251
252                 if (best_len < 3) {
253                         matchptr = &in_begin[cur_node3];
254                         if (load_u24_unaligned(matchptr) == loaded_u32_to_u24(seq4)) {
255                                 best_len = 3;
256                                 best_matchptr = matchptr;
257                         }
258                 }
259
260                 /* Check for a length 4 match.  */
261
262                 if (!cur_node4)
263                         goto out;
264
265                 for (;;) {
266                         /* No length 4 match found yet.  Check the first 4 bytes.  */
267                         matchptr = &in_begin[cur_node4];
268
269                         if (load_u32_unaligned(matchptr) == seq4)
270                                 break;
271
272                         /* The first 4 bytes did not match.  Keep trying.  */
273                         cur_node4 = mf->next_tab[cur_node4];
274                         if (!cur_node4 || !--depth_remaining)
275                                 goto out;
276                 }
277
278                 /* Found a match of length >= 4.  Extend it to its full length.  */
279                 best_matchptr = matchptr;
280                 best_len = lz_extend(in_next, best_matchptr, 4, max_len);
281                 if (best_len >= nice_len)
282                         goto out;
283                 cur_node4 = mf->next_tab[cur_node4];
284                 if (!cur_node4 || !--depth_remaining)
285                         goto out;
286         } else {
287                 if (!cur_node4 || best_len >= nice_len)
288                         goto out;
289         }
290
291         /* Check for matches of length >= 5.  */
292
293         for (;;) {
294                 for (;;) {
295                         matchptr = &in_begin[cur_node4];
296
297                         /* Already found a length 4 match.  Try for a longer
298                          * match; start by checking either the last 4 bytes and
299                          * the first 4 bytes, or the last byte.  (The last byte,
300                          * the one which would extend the match length by 1, is
301                          * the most important.)  */
302                 #if UNALIGNED_ACCESS_IS_FAST
303                         if ((load_u32_unaligned(matchptr + best_len - 3) ==
304                              load_u32_unaligned(in_next + best_len - 3)) &&
305                             (load_u32_unaligned(matchptr) ==
306                              load_u32_unaligned(in_next)))
307                 #else
308                         if (matchptr[best_len] == in_next[best_len])
309                 #endif
310                                 break;
311
312                         /* Continue to the next node in the list.  */
313                         cur_node4 = mf->next_tab[cur_node4];
314                         if (!cur_node4 || !--depth_remaining)
315                                 goto out;
316                 }
317
318         #if UNALIGNED_ACCESS_IS_FAST
319                 len = 4;
320         #else
321                 len = 0;
322         #endif
323                 len = lz_extend(in_next, matchptr, len, max_len);
324                 if (len > best_len) {
325                         /* This is the new longest match.  */
326                         best_len = len;
327                         best_matchptr = matchptr;
328                         if (best_len >= nice_len)
329                                 goto out;
330                 }
331
332                 /* Continue to the next node in the list.  */
333                 cur_node4 = mf->next_tab[cur_node4];
334                 if (!cur_node4 || !--depth_remaining)
335                         goto out;
336         }
337 out:
338         *offset_ret = in_next - best_matchptr;
339         return best_len;
340 }
341
342 /*
343  * Advance the matchfinder, but don't search for matches.
344  *
345  * @mf
346  *      The matchfinder structure.
347  * @in_begin
348  *      Pointer to the beginning of the input buffer.
349  * @cur_pos
350  *      The current position in the input buffer (the position of the sequence
351  *      being matched against).
352  * @end_pos
353  *      The length of the input buffer.
354  * @next_hashes
355  *      The precomputed hash codes for the sequence beginning at @in_next.
356  *      These will be used and then updated with the precomputed hashcodes for
357  *      the sequence beginning at @in_next + @count.
358  * @count
359  *      The number of bytes to advance.  Must be > 0.
360  *
361  * Returns @in_next + @count.
362  */
363 static forceinline const u8 *
364 TEMPLATED(hc_matchfinder_skip_positions)(struct TEMPLATED(hc_matchfinder) * const restrict mf,
365                                          const u8 * const restrict in_begin,
366                                          const ptrdiff_t cur_pos,
367                                          const ptrdiff_t end_pos,
368                                          const u32 count,
369                                          u32 next_hashes[const restrict static 2])
370 {
371         const u8 *in_next = in_begin + cur_pos;
372         const u8 * const stop_ptr = in_next + count;
373
374         if (likely(count + 5 <= end_pos - cur_pos)) {
375                 u32 hash3, hash4;
376                 u32 next_seq3, next_seq4;
377
378                 hash3 = next_hashes[0];
379                 hash4 = next_hashes[1];
380                 do {
381                         mf->hash3_tab[hash3] = in_next - in_begin;
382                         mf->next_tab[in_next - in_begin] = mf->hash4_tab[hash4];
383                         mf->hash4_tab[hash4] = in_next - in_begin;
384
385                         next_seq4 = load_u32_unaligned(++in_next);
386                         next_seq3 = loaded_u32_to_u24(next_seq4);
387                         hash3 = lz_hash(next_seq3, HC_MATCHFINDER_HASH3_ORDER);
388                         hash4 = lz_hash(next_seq4, HC_MATCHFINDER_HASH4_ORDER);
389
390                 } while (in_next != stop_ptr);
391
392                 prefetchw(&mf->hash3_tab[hash3]);
393                 prefetchw(&mf->hash4_tab[hash4]);
394                 next_hashes[0] = hash3;
395                 next_hashes[1] = hash4;
396         }
397
398         return stop_ptr;
399 }