X-Git-Url: https://wimlib.net/git/?p=wimlib;a=blobdiff_plain;f=include%2Fwimlib%2Fhc_matchfinder.h;h=e1da62b5ca1a388566419f98030705971e9e31d3;hp=d880b2486d647ec40ec5b9d030826984e7b5eb4b;hb=e9a04c1cb384cf3cf23d70107e85f79c4ac0a555;hpb=1bba32f7f1068eaa0e8de77b8afa99af68bcb44d diff --git a/include/wimlib/hc_matchfinder.h b/include/wimlib/hc_matchfinder.h index d880b248..e1da62b5 100644 --- a/include/wimlib/hc_matchfinder.h +++ b/include/wimlib/hc_matchfinder.h @@ -1,176 +1,287 @@ /* * hc_matchfinder.h * - * Copyright (c) 2014 Eric Biggers. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * Author: Eric Biggers + * Year: 2014, 2015 + * + * The author dedicates this file to the public domain. + * You can do whatever you want with this file. + * + * --------------------------------------------------------------------------- + * + * Algorithm + * + * This is a Hash Chains (hc) based matchfinder. + * + * The main data structure is a hash table where each hash bucket contains a + * linked list (or "chain") of sequences whose first 4 bytes share the same hash + * code. Each sequence is identified by its starting position in the input + * buffer. + * + * The algorithm processes the input buffer sequentially. At each byte + * position, the hash code of the first 4 bytes of the sequence beginning at + * that position (the sequence being matched against) is computed. This + * identifies the hash bucket to use for that position. Then, this hash + * bucket's linked list is searched for matches. Then, a new linked list node + * is created to represent the current sequence and is prepended to the list. + * + * This algorithm has several useful properties: + * + * - It only finds true Lempel-Ziv matches; i.e., those where the matching + * sequence occurs prior to the sequence being matched against. + * + * - The sequences in each linked list are always sorted by decreasing starting + * position. Therefore, the closest (smallest offset) matches are found + * first, which in many compression formats tend to be the cheapest to encode. + * + * - Although fast running time is not guaranteed due to the possibility of the + * lists getting very long, the worst degenerate behavior can be easily + * prevented by capping the number of nodes searched at each position. + * + * - If the compressor decides not to search for matches at a certain position, + * then that position can be quickly inserted without searching the list. + * + * - The algorithm is adaptable to sliding windows: just store the positions + * relative to a "base" value that is updated from time to time, and stop + * searching each list when the sequences get too far away. + * + * --------------------------------------------------------------------------- + * + * Notes on usage + * + * Before including this header, you must define 'mf_pos_t' to an integer type + * that can represent all possible positions. This can be a 16-bit or 32-bit + * unsigned integer. When possible, the former should be used due to the + * reduced cache pressure. This header can be included multiple times in a + * single .c file with different 'mf_pos_t' definitions; however, you must + * define a different MF_SUFFIX each time to generate different names for the + * matchfinder structure and functions. + * + * The number of bytes that must be allocated for a given 'struct + * hc_matchfinder' must be gotten by calling hc_matchfinder_size(). + * + * ---------------------------------------------------------------------------- + * + * Optimizations + * + * The main hash table and chains handle length 4+ matches. Length 3 matches + * are handled by a separate hash table with no chains. This works well for + * typical "greedy" or "lazy"-style compressors, where length 3 matches are + * often only helpful if they have small offsets. Instead of searching a full + * chain for length 3+ matches, the algorithm just checks for one close length 3 + * match, then focuses on finding length 4+ matches. + * + * The longest_match() and skip_positions() functions are inlined into the + * compressors that use them. This isn't just about saving the overhead of a + * function call. These functions are intended to be called from the inner + * loops of compressors, where giving the compiler more control over register + * allocation is very helpful. There is also significant benefit to be gained + * from allowing the CPU to predict branches independently at each call site. + * For example, "lazy"-style compressors can be written with two calls to + * longest_match(), each of which starts with a different 'best_len' and + * therefore has significantly different performance characteristics. + * + * Although any hash function can be used, a multiplicative hash is fast and + * works well. + * + * On some processors, it is significantly faster to extend matches by whole + * words (32 or 64 bits) instead of by individual bytes. For this to be the + * case, the processor must implement unaligned memory accesses efficiently and + * must have either a fast "find first set bit" instruction or a fast "find last + * set bit" instruction, depending on the processor's endianness. + * + * The code uses one loop for finding the first match and one loop for finding a + * longer match. Each of these loops is tuned for its respective task and in + * combination are faster than a single generalized loop that handles both + * tasks. + * + * The code also uses a tight inner loop that only compares the last and first + * bytes of a potential match. It is only when these bytes match that a full + * match extension is attempted. + * + * ---------------------------------------------------------------------------- */ -#pragma once +#include #include "wimlib/lz_extend.h" -#include "wimlib/lz_hash3.h" -#include "wimlib/matchfinder_common.h" +#include "wimlib/lz_hash.h" #include "wimlib/unaligned.h" -#ifndef HC_MATCHFINDER_HASH_ORDER -# if MATCHFINDER_WINDOW_ORDER < 14 -# define HC_MATCHFINDER_HASH_ORDER 14 -# else -# define HC_MATCHFINDER_HASH_ORDER 15 -# endif -#endif - -#define HC_MATCHFINDER_HASH_LENGTH (1UL << HC_MATCHFINDER_HASH_ORDER) - -#define HC_MATCHFINDER_TOTAL_LENGTH \ - (HC_MATCHFINDER_HASH_LENGTH + MATCHFINDER_WINDOW_SIZE) - -struct hc_matchfinder { - union { - pos_t mf_data[HC_MATCHFINDER_TOTAL_LENGTH]; - struct { - pos_t hash_tab[HC_MATCHFINDER_HASH_LENGTH]; - pos_t child_tab[MATCHFINDER_WINDOW_SIZE]; - }; - }; -} _aligned_attribute(MATCHFINDER_ALIGNMENT); +#define HC_MATCHFINDER_HASH3_ORDER 14 +#define HC_MATCHFINDER_HASH4_ORDER 15 -/* - * Call before running the first byte through the matchfinder. - */ -static inline void -hc_matchfinder_init(struct hc_matchfinder *mf) +/* TEMPLATED functions and structures have MF_SUFFIX appended to their name. */ +#undef TEMPLATED +#define TEMPLATED(name) CONCAT(name, MF_SUFFIX) + +struct TEMPLATED(hc_matchfinder) { + + /* The hash table for finding length 3 matches */ + mf_pos_t hash3_tab[1UL << HC_MATCHFINDER_HASH3_ORDER]; + + /* The hash table which contains the first nodes of the linked lists for + * finding length 4+ matches */ + mf_pos_t hash4_tab[1UL << HC_MATCHFINDER_HASH4_ORDER]; + + /* The "next node" references for the linked lists. The "next node" of + * the node for the sequence with position 'pos' is 'next_tab[pos]'. */ + mf_pos_t next_tab[]; +}; + +/* Return the number of bytes that must be allocated for a 'hc_matchfinder' that + * can work with buffers up to the specified size. */ +static inline size_t +TEMPLATED(hc_matchfinder_size)(size_t max_bufsize) { - matchfinder_init(mf->hash_tab, HC_MATCHFINDER_HASH_LENGTH); + return sizeof(struct TEMPLATED(hc_matchfinder)) + + (max_bufsize * sizeof(mf_pos_t)); } -#if MATCHFINDER_IS_SLIDING +/* Prepare the matchfinder for a new input buffer. */ static inline void -hc_matchfinder_slide_window(struct hc_matchfinder *mf) +TEMPLATED(hc_matchfinder_init)(struct TEMPLATED(hc_matchfinder) *mf) { - matchfinder_rebase(mf->mf_data, HC_MATCHFINDER_TOTAL_LENGTH); + memset(mf, 0, sizeof(*mf)); } -#endif /* - * Find the longest match longer than 'best_len'. + * Find the longest match longer than 'best_len' bytes. * * @mf * The matchfinder structure. - * @in_base - * Pointer to the next byte in the input buffer to process _at the last - * time hc_matchfinder_init() or hc_matchfinder_slide_window() was called_. - * @in_next - * Pointer to the next byte in the input buffer to process. This is the - * pointer to the bytes being matched against. + * @in_begin + * Pointer to the beginning of the input buffer. + * @cur_pos + * The current position in the input buffer (the position of the sequence + * being matched against). * @best_len - * Require a match at least this long. + * Require a match longer than this length. * @max_len - * Maximum match length to return. + * The maximum permissible match length at this position. * @nice_len * Stop searching if a match of at least this length is found. + * Must be <= @max_len. * @max_search_depth - * Limit on the number of potential matches to consider. + * Limit on the number of potential matches to consider. Must be >= 1. + * @next_hashes + * The precomputed hash codes for the sequence beginning at @in_next. + * These will be used and then updated with the precomputed hashcodes for + * the sequence beginning at @in_next + 1. * @offset_ret - * The match offset is returned here. + * If a match is found, its offset is returned in this location. * * Return the length of the match found, or 'best_len' if no match longer than * 'best_len' was found. */ -static inline unsigned -hc_matchfinder_longest_match(struct hc_matchfinder * const restrict mf, - const u8 * const in_base, - const u8 * const in_next, - unsigned best_len, - const unsigned max_len, - const unsigned nice_len, - const unsigned max_search_depth, - unsigned *offset_ret) +static inline u32 +TEMPLATED(hc_matchfinder_longest_match)(struct TEMPLATED(hc_matchfinder) * const restrict mf, + const u8 * const restrict in_begin, + const ptrdiff_t cur_pos, + u32 best_len, + const u32 max_len, + const u32 nice_len, + const u32 max_search_depth, + u32 next_hashes[const restrict static 2], + u32 * const restrict offset_ret) { - unsigned depth_remaining = max_search_depth; + const u8 *in_next = in_begin + cur_pos; + u32 depth_remaining = max_search_depth; const u8 *best_matchptr = best_matchptr; /* uninitialized */ + mf_pos_t cur_node3, cur_node4; + u32 hash3, hash4; + u32 next_seq3, next_seq4; + u32 seq4; const u8 *matchptr; - unsigned len; - unsigned hash; - pos_t cur_match; - u32 first_3_bytes; + u32 len; - /* Insert the current sequence into the appropriate hash chain. */ - if (unlikely(max_len < LZ_HASH_REQUIRED_NBYTES)) + if (unlikely(max_len < 5)) /* can we read 4 bytes from 'in_next + 1'? */ goto out; - first_3_bytes = load_u24_unaligned(in_next); - hash = lz_hash_u24(first_3_bytes, HC_MATCHFINDER_HASH_ORDER); - cur_match = mf->hash_tab[hash]; - mf->child_tab[in_next - in_base] = cur_match; - mf->hash_tab[hash] = in_next - in_base; - if (unlikely(best_len >= max_len)) - goto out; + /* Get the precomputed hash codes. */ + hash3 = next_hashes[0]; + hash4 = next_hashes[1]; - /* Search the appropriate hash chain for matches. */ + /* From the hash buckets, get the first node of each linked list. */ + cur_node3 = mf->hash3_tab[hash3]; + cur_node4 = mf->hash4_tab[hash4]; - if (!(matchfinder_match_in_window(cur_match, in_base, in_next))) - goto out; + /* Update for length 3 matches. This replaces the singleton node in the + * 'hash3' bucket with the node for the current sequence. */ + mf->hash3_tab[hash3] = cur_pos; + + /* Update for length 4 matches. This prepends the node for the current + * sequence to the linked list in the 'hash4' bucket. */ + mf->hash4_tab[hash4] = cur_pos; + mf->next_tab[cur_pos] = cur_node4; + + /* Compute the next hash codes. */ + next_seq4 = load_u32_unaligned(in_next + 1); + next_seq3 = loaded_u32_to_u24(next_seq4); + next_hashes[0] = lz_hash(next_seq3, HC_MATCHFINDER_HASH3_ORDER); + next_hashes[1] = lz_hash(next_seq4, HC_MATCHFINDER_HASH4_ORDER); + prefetchw(&mf->hash3_tab[next_hashes[0]]); + prefetchw(&mf->hash4_tab[next_hashes[1]]); + + if (best_len < 4) { /* No match of length >= 4 found yet? */ + + /* Check for a length 3 match if needed. */ + + if (!cur_node3) + goto out; + + seq4 = load_u32_unaligned(in_next); + + if (best_len < 3) { + matchptr = &in_begin[cur_node3]; + if (load_u24_unaligned(matchptr) == loaded_u32_to_u24(seq4)) { + best_len = 3; + best_matchptr = matchptr; + } + } + + /* Check for a length 4 match. */ + + if (!cur_node4) + goto out; - if (best_len < 3) { for (;;) { - /* No length 3 match found yet. - * Check the first 3 bytes. */ - matchptr = &in_base[cur_match]; + /* No length 4 match found yet. Check the first 4 bytes. */ + matchptr = &in_begin[cur_node4]; - if (load_u24_unaligned(matchptr) == first_3_bytes) + if (load_u32_unaligned(matchptr) == seq4) break; - /* Not a match; keep trying. */ - cur_match = mf->child_tab[ - matchfinder_slot_for_match(cur_match)]; - if (!matchfinder_match_in_window(cur_match, - in_base, in_next)) - goto out; - if (!--depth_remaining) + /* The first 4 bytes did not match. Keep trying. */ + cur_node4 = mf->next_tab[cur_node4]; + if (!cur_node4 || !--depth_remaining) goto out; } - /* Found a length 3 match. */ + /* Found a match of length >= 4. Extend it to its full length. */ best_matchptr = matchptr; - best_len = lz_extend(in_next, best_matchptr, 3, max_len); + best_len = lz_extend(in_next, best_matchptr, 4, max_len); if (best_len >= nice_len) goto out; - cur_match = mf->child_tab[matchfinder_slot_for_match(cur_match)]; - if (!matchfinder_match_in_window(cur_match, in_base, in_next)) + cur_node4 = mf->next_tab[cur_node4]; + if (!cur_node4 || !--depth_remaining) goto out; - if (!--depth_remaining) + } else { + if (!cur_node4 || best_len >= nice_len) goto out; } + /* Check for matches of length >= 5. */ + for (;;) { for (;;) { - matchptr = &in_base[cur_match]; + matchptr = &in_begin[cur_node4]; - /* Already found a length 3 match. Try for a longer match; - * start by checking the last 2 bytes and the first 4 bytes. */ + /* Already found a length 4 match. Try for a longer + * match; start by checking either the last 4 bytes and + * the first 4 bytes, or the last byte. (The last byte, + * the one which would extend the match length by 1, is + * the most important.) */ #if UNALIGNED_ACCESS_IS_FAST if ((load_u32_unaligned(matchptr + best_len - 3) == load_u32_unaligned(in_next + best_len - 3)) && @@ -181,10 +292,9 @@ hc_matchfinder_longest_match(struct hc_matchfinder * const restrict mf, #endif break; - cur_match = mf->child_tab[matchfinder_slot_for_match(cur_match)]; - if (!matchfinder_match_in_window(cur_match, in_base, in_next)) - goto out; - if (!--depth_remaining) + /* Continue to the next node in the list. */ + cur_node4 = mf->next_tab[cur_node4]; + if (!cur_node4 || !--depth_remaining) goto out; } @@ -195,15 +305,16 @@ hc_matchfinder_longest_match(struct hc_matchfinder * const restrict mf, #endif len = lz_extend(in_next, matchptr, len, max_len); if (len > best_len) { + /* This is the new longest match. */ best_len = len; best_matchptr = matchptr; if (best_len >= nice_len) goto out; } - cur_match = mf->child_tab[matchfinder_slot_for_match(cur_match)]; - if (!matchfinder_match_in_window(cur_match, in_base, in_next)) - goto out; - if (!--depth_remaining) + + /* Continue to the next node in the list. */ + cur_node4 = mf->next_tab[cur_node4]; + if (!cur_node4 || !--depth_remaining) goto out; } out: @@ -212,36 +323,60 @@ out: } /* - * Advance the match-finder, but don't search for matches. + * Advance the matchfinder, but don't search for matches. * * @mf * The matchfinder structure. - * @in_base - * Pointer to the next byte in the input buffer to process _at the last - * time hc_matchfinder_init() or hc_matchfinder_slide_window() was called_. - * @in_next - * Pointer to the next byte in the input buffer to process. - * @in_end - * Pointer to the end of the input buffer. + * @in_begin + * Pointer to the beginning of the input buffer. + * @cur_pos + * The current position in the input buffer (the position of the sequence + * being matched against). + * @end_pos + * The length of the input buffer. + * @next_hashes + * The precomputed hash codes for the sequence beginning at @in_next. + * These will be used and then updated with the precomputed hashcodes for + * the sequence beginning at @in_next + @count. * @count - * Number of bytes to skip; must be > 0. + * The number of bytes to advance. Must be > 0. + * + * Returns @in_next + @count. */ -static inline void -hc_matchfinder_skip_positions(struct hc_matchfinder * restrict mf, - const u8 *in_base, - const u8 *in_next, - const u8 *in_end, - unsigned count) +static inline const u8 * +TEMPLATED(hc_matchfinder_skip_positions)(struct TEMPLATED(hc_matchfinder) * const restrict mf, + const u8 * const restrict in_begin, + const ptrdiff_t cur_pos, + const ptrdiff_t end_pos, + const u32 count, + u32 next_hashes[const restrict static 2]) { - unsigned hash; + const u8 *in_next = in_begin + cur_pos; + const u8 * const stop_ptr = in_next + count; + + if (likely(count + 5 <= end_pos - cur_pos)) { + u32 hash3, hash4; + u32 next_seq3, next_seq4; + + hash3 = next_hashes[0]; + hash4 = next_hashes[1]; + do { + mf->hash3_tab[hash3] = in_next - in_begin; + mf->next_tab[in_next - in_begin] = mf->hash4_tab[hash4]; + mf->hash4_tab[hash4] = in_next - in_begin; - if (unlikely(in_next + count >= in_end - LZ_HASH_REQUIRED_NBYTES)) - return; + next_seq4 = load_u32_unaligned(++in_next); + next_seq3 = loaded_u32_to_u24(next_seq4); + hash3 = lz_hash(next_seq3, HC_MATCHFINDER_HASH3_ORDER); + hash4 = lz_hash(next_seq4, HC_MATCHFINDER_HASH4_ORDER); + + } while (in_next != stop_ptr); + + prefetchw(&mf->hash3_tab[hash3]); + prefetchw(&mf->hash4_tab[hash4]); + next_hashes[0] = hash3; + next_hashes[1] = hash4; + } - do { - hash = lz_hash(in_next, HC_MATCHFINDER_HASH_ORDER); - mf->child_tab[in_next - in_base] = mf->hash_tab[hash]; - mf->hash_tab[hash] = in_next - in_base; - in_next++; - } while (--count); + return stop_ptr; }