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