]> wimlib.net Git - wimlib/blob - src/decompress_common.c
Replace BUILD_BUG_ON() with STATIC_ASSERT()
[wimlib] / src / decompress_common.c
1 /*
2  * decompress_common.c
3  *
4  * Code for decompression shared among multiple compression formats.
5  *
6  * Author:  Eric Biggers
7  * Year:    2012 - 2014
8  *
9  * The author dedicates this file to the public domain.
10  * You can do whatever you want with this file.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 #  include "config.h"
15 #endif
16
17 #include "wimlib/decompress_common.h"
18
19 #include <string.h>
20
21 #define USE_WORD_FILL
22
23 #ifdef __GNUC__
24 #  ifdef __SSE2__
25 #    undef USE_WORD_FILL
26 #    define USE_SSE2_FILL
27 #    include <emmintrin.h>
28 #  endif
29 #endif
30
31 /* Construct a direct mapping entry in the lookup table.  */
32 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
33
34 /*
35  * make_huffman_decode_table() -
36  *
37  * Build a decoding table for a canonical prefix code, or "Huffman code".
38  *
39  * This takes as input the length of the codeword for each symbol in the
40  * alphabet and produces as output a table that can be used for fast
41  * decoding of prefix-encoded symbols using read_huffsym().
42  *
43  * Strictly speaking, a canonical prefix code might not be a Huffman
44  * code.  But this algorithm will work either way; and in fact, since
45  * Huffman codes are defined in terms of symbol frequencies, there is no
46  * way for the decompressor to know whether the code is a true Huffman
47  * code or not until all symbols have been decoded.
48  *
49  * Because the prefix code is assumed to be "canonical", it can be
50  * reconstructed directly from the codeword lengths.  A prefix code is
51  * canonical if and only if a longer codeword never lexicographically
52  * precedes a shorter codeword, and the lexicographic ordering of
53  * codewords of the same length is the same as the lexicographic ordering
54  * of the corresponding symbols.  Consequently, we can sort the symbols
55  * primarily by codeword length and secondarily by symbol value, then
56  * reconstruct the prefix code by generating codewords lexicographically
57  * in that order.
58  *
59  * This function does not, however, generate the prefix code explicitly.
60  * Instead, it directly builds a table for decoding symbols using the
61  * code.  The basic idea is this: given the next 'max_codeword_len' bits
62  * in the input, we can look up the decoded symbol by indexing a table
63  * containing 2**max_codeword_len entries.  A codeword with length
64  * 'max_codeword_len' will have exactly one entry in this table, whereas
65  * a codeword shorter than 'max_codeword_len' will have multiple entries
66  * in this table.  Precisely, a codeword of length n will be represented
67  * by 2**(max_codeword_len - n) entries in this table.  The 0-based index
68  * of each such entry will contain the corresponding codeword as a prefix
69  * when zero-padded on the left to 'max_codeword_len' binary digits.
70  *
71  * That's the basic idea, but we implement two optimizations regarding
72  * the format of the decode table itself:
73  *
74  * - For many compression formats, the maximum codeword length is too
75  *   long for it to be efficient to build the full decoding table
76  *   whenever a new prefix code is used.  Instead, we can build the table
77  *   using only 2**table_bits entries, where 'table_bits' is some number
78  *   less than or equal to 'max_codeword_len'.  Then, only codewords of
79  *   length 'table_bits' and shorter can be directly looked up.  For
80  *   longer codewords, the direct lookup instead produces the root of a
81  *   binary tree.  Using this tree, the decoder can do traditional
82  *   bit-by-bit decoding of the remainder of the codeword.  Child nodes
83  *   are allocated in extra entries at the end of the table; leaf nodes
84  *   contain symbols.  Note that the long-codeword case is, in general,
85  *   not performance critical, since in Huffman codes the most frequently
86  *   used symbols are assigned the shortest codeword lengths.
87  *
88  * - When we decode a symbol using a direct lookup of the table, we still
89  *   need to know its length so that the bitstream can be advanced by the
90  *   appropriate number of bits.  The simple solution is to simply retain
91  *   the 'lens' array and use the decoded symbol as an index into it.
92  *   However, this requires two separate array accesses in the fast path.
93  *   The optimization is to store the length directly in the decode
94  *   table.  We use the bottom 11 bits for the symbol and the top 5 bits
95  *   for the length.  In addition, to combine this optimization with the
96  *   previous one, we introduce a special case where the top 2 bits of
97  *   the length are both set if the entry is actually the root of a
98  *   binary tree.
99  *
100  * @decode_table:
101  *      The array in which to create the decoding table.  This must be
102  *      16-byte aligned and must have a length of at least
103  *      ((2**table_bits) + 2 * num_syms) entries.  This is permitted to
104  *      alias @lens, since all information from @lens is consumed before
105 *       anything is written to @decode_table.
106  *
107  * @num_syms:
108  *      The number of symbols in the alphabet; also, the length of the
109  *      'lens' array.  Must be less than or equal to
110  *      DECODE_TABLE_MAX_SYMBOLS.
111  *
112  * @table_bits:
113  *      The order of the decode table size, as explained above.  Must be
114  *      less than or equal to DECODE_TABLE_MAX_TABLE_BITS.
115  *
116  * @lens:
117  *      An array of length @num_syms, indexable by symbol, that gives the
118  *      length of the codeword, in bits, for that symbol.  The length can
119  *      be 0, which means that the symbol does not have a codeword
120  *      assigned.  This is permitted to alias @decode_table, since all
121  *      information from @lens is consumed before anything is written to
122  *      @decode_table.
123  *
124  * @max_codeword_len:
125  *      The longest codeword length allowed in the compression format.
126  *      All entries in 'lens' must be less than or equal to this value.
127  *      This must be less than or equal to DECODE_TABLE_MAX_CODEWORD_LEN.
128  *
129  * Returns 0 on success, or -1 if the lengths do not form a valid prefix
130  * code.
131  */
132 int
133 make_huffman_decode_table(u16 decode_table[const],
134                           const unsigned num_syms,
135                           const unsigned table_bits,
136                           const u8 lens[const],
137                           const unsigned max_codeword_len)
138 {
139         const unsigned table_num_entries = 1 << table_bits;
140         unsigned len_counts[max_codeword_len + 1];
141         u16 sorted_syms[num_syms];
142         int left;
143         void *decode_table_ptr;
144         unsigned sym_idx;
145         unsigned codeword_len;
146         unsigned stores_per_loop;
147         unsigned decode_table_pos;
148
149 #ifdef USE_WORD_FILL
150         const unsigned entries_per_word = WORDSIZE / sizeof(decode_table[0]);
151 #endif
152
153 #ifdef USE_SSE2_FILL
154         const unsigned entries_per_xmm = sizeof(__m128i) / sizeof(decode_table[0]);
155 #endif
156
157         /* Count how many symbols have each possible codeword length.
158          * Note that a length of 0 indicates the corresponding symbol is not
159          * used in the code and therefore does not have a codeword.  */
160         for (unsigned len = 0; len <= max_codeword_len; len++)
161                 len_counts[len] = 0;
162         for (unsigned sym = 0; sym < num_syms; sym++)
163                 len_counts[lens[sym]]++;
164
165         /* We can assume all lengths are <= max_codeword_len, but we
166          * cannot assume they form a valid prefix code.  A codeword of
167          * length n should require a proportion of the codespace equaling
168          * (1/2)^n.  The code is valid if and only if the codespace is
169          * exactly filled by the lengths, by this measure.  */
170         left = 1;
171         for (unsigned len = 1; len <= max_codeword_len; len++) {
172                 left <<= 1;
173                 left -= len_counts[len];
174                 if (unlikely(left < 0)) {
175                         /* The lengths overflow the codespace; that is, the code
176                          * is over-subscribed.  */
177                         return -1;
178                 }
179         }
180
181         if (unlikely(left != 0)) {
182                 /* The lengths do not fill the codespace; that is, they form an
183                  * incomplete set.  */
184                 if (left == (1 << max_codeword_len)) {
185                         /* The code is completely empty.  This is arguably
186                          * invalid, but in fact it is valid in LZX and XPRESS,
187                          * so we must allow it.  By definition, no symbols can
188                          * be decoded with an empty code.  Consequently, we
189                          * technically don't even need to fill in the decode
190                          * table.  However, to avoid accessing uninitialized
191                          * memory if the algorithm nevertheless attempts to
192                          * decode symbols using such a code, we zero out the
193                          * decode table.  */
194                         memset(decode_table, 0,
195                                table_num_entries * sizeof(decode_table[0]));
196                         return 0;
197                 }
198                 return -1;
199         }
200
201         /* Sort the symbols primarily by length and secondarily by symbol order.
202          */
203         {
204                 unsigned offsets[max_codeword_len + 1];
205
206                 /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
207                  * max_codeword_len is the number of codewords shorter than
208                  * 'len' bits.  */
209                 offsets[1] = 0;
210                 for (unsigned len = 1; len < max_codeword_len; len++)
211                         offsets[len + 1] = offsets[len] + len_counts[len];
212
213                 /* Use the 'offsets' array to sort the symbols.
214                  * Note that we do not include symbols that are not used in the
215                  * code.  Consequently, fewer than 'num_syms' entries in
216                  * 'sorted_syms' may be filled.  */
217                 for (unsigned sym = 0; sym < num_syms; sym++)
218                         if (lens[sym] != 0)
219                                 sorted_syms[offsets[lens[sym]]++] = sym;
220         }
221
222         /* Fill entries for codewords with length <= table_bits
223          * --- that is, those short enough for a direct mapping.
224          *
225          * The table will start with entries for the shortest codeword(s), which
226          * have the most entries.  From there, the number of entries per
227          * codeword will decrease.  As an optimization, we may begin filling
228          * entries with SSE2 vector accesses (8 entries/store), then change to
229          * 'machine_word_t' accesses (2 or 4 entries/store), then change to
230          * 16-bit accesses (1 entry/store).  */
231         decode_table_ptr = decode_table;
232         sym_idx = 0;
233         codeword_len = 1;
234 #ifdef USE_SSE2_FILL
235         /* Fill the entries one 128-bit vector at a time.
236          * This is 8 entries per store.  */
237         stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_xmm;
238         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
239                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
240                 for (; sym_idx < end_sym_idx; sym_idx++) {
241                         /* Note: unlike in the machine_word_t version below, the
242                          * __m128i type already has __attribute__((may_alias)),
243                          * so using it to access the decode table, which is an
244                          * array of unsigned shorts, will not violate strict
245                          * aliasing.  */
246                         u16 entry;
247                         __m128i v;
248                         __m128i *p;
249                         unsigned n;
250
251                         entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
252
253                         v = _mm_set1_epi16(entry);
254                         p = (__m128i*)decode_table_ptr;
255                         n = stores_per_loop;
256                         do {
257                                 *p++ = v;
258                         } while (--n);
259                         decode_table_ptr = p;
260                 }
261         }
262 #endif /* USE_SSE2_FILL */
263
264 #ifdef USE_WORD_FILL
265         /* Fill the entries one machine word at a time.
266          * On 32-bit systems this is 2 entries per store, while on 64-bit
267          * systems this is 4 entries per store.  */
268         stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_word;
269         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
270                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
271                 for (; sym_idx < end_sym_idx; sym_idx++) {
272
273                         /* Accessing the array of u16 as u32 or u64 would
274                          * violate strict aliasing and would require compiling
275                          * the code with -fno-strict-aliasing to guarantee
276                          * correctness.  To work around this problem, use the
277                          * gcc 'may_alias' extension.  */
278                         typedef machine_word_t _may_alias_attribute aliased_word_t;
279
280                         machine_word_t v;
281                         aliased_word_t *p;
282                         unsigned n;
283
284                         STATIC_ASSERT(WORDSIZE == 4 || WORDSIZE == 8);
285
286                         v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
287                         v |= v << 16;
288                         v |= v << (WORDSIZE == 8 ? 32 : 0);
289
290                         p = (aliased_word_t *)decode_table_ptr;
291                         n = stores_per_loop;
292
293                         do {
294                                 *p++ = v;
295                         } while (--n);
296                         decode_table_ptr = p;
297                 }
298         }
299 #endif /* USE_WORD_FILL */
300
301         /* Fill the entries one 16-bit integer at a time.  */
302         stores_per_loop = (1 << (table_bits - codeword_len));
303         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
304                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
305                 for (; sym_idx < end_sym_idx; sym_idx++) {
306                         u16 entry;
307                         u16 *p;
308                         unsigned n;
309
310                         entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
311
312                         p = (u16*)decode_table_ptr;
313                         n = stores_per_loop;
314
315                         do {
316                                 *p++ = entry;
317                         } while (--n);
318
319                         decode_table_ptr = p;
320                 }
321         }
322
323         /* If we've filled in the entire table, we are done.  Otherwise,
324          * there are codewords longer than table_bits for which we must
325          * generate binary trees.  */
326
327         decode_table_pos = (u16*)decode_table_ptr - decode_table;
328         if (decode_table_pos != table_num_entries) {
329                 unsigned j;
330                 unsigned next_free_tree_slot;
331                 unsigned cur_codeword;
332
333                 /* First, zero out the remaining entries.  This is
334                  * necessary so that these entries appear as
335                  * "unallocated" in the next part.  Each of these entries
336                  * will eventually be filled with the representation of
337                  * the root node of a binary tree.  */
338                 j = decode_table_pos;
339                 do {
340                         decode_table[j] = 0;
341                 } while (++j != table_num_entries);
342
343                 /* We allocate child nodes starting at the end of the
344                  * direct lookup table.  Note that there should be
345                  * 2*num_syms extra entries for this purpose, although
346                  * fewer than this may actually be needed.  */
347                 next_free_tree_slot = table_num_entries;
348
349                 /* Iterate through each codeword with length greater than
350                  * 'table_bits', primarily in order of codeword length
351                  * and secondarily in order of symbol.  */
352                 for (cur_codeword = decode_table_pos << 1;
353                      codeword_len <= max_codeword_len;
354                      codeword_len++, cur_codeword <<= 1)
355                 {
356                         unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
357                         for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
358                         {
359                                 /* 'sym' is the symbol represented by the
360                                  * codeword.  */
361                                 unsigned sym = sorted_syms[sym_idx];
362
363                                 unsigned extra_bits = codeword_len - table_bits;
364
365                                 unsigned node_idx = cur_codeword >> extra_bits;
366
367                                 /* Go through each bit of the current codeword
368                                  * beyond the prefix of length @table_bits and
369                                  * walk the appropriate binary tree, allocating
370                                  * any slots that have not yet been allocated.
371                                  *
372                                  * Note that the 'pointer' entry to the binary
373                                  * tree, which is stored in the direct lookup
374                                  * portion of the table, is represented
375                                  * identically to other internal (non-leaf)
376                                  * nodes of the binary tree; it can be thought
377                                  * of as simply the root of the tree.  The
378                                  * representation of these internal nodes is
379                                  * simply the index of the left child combined
380                                  * with the special bits 0xC000 to distingush
381                                  * the entry from direct mapping and leaf node
382                                  * entries.  */
383                                 do {
384
385                                         /* At least one bit remains in the
386                                          * codeword, but the current node is an
387                                          * unallocated leaf.  Change it to an
388                                          * internal node.  */
389                                         if (decode_table[node_idx] == 0) {
390                                                 decode_table[node_idx] =
391                                                         next_free_tree_slot | 0xC000;
392                                                 decode_table[next_free_tree_slot++] = 0;
393                                                 decode_table[next_free_tree_slot++] = 0;
394                                         }
395
396                                         /* Go to the left child if the next bit
397                                          * in the codeword is 0; otherwise go to
398                                          * the right child.  */
399                                         node_idx = decode_table[node_idx] & 0x3FFF;
400                                         --extra_bits;
401                                         node_idx += (cur_codeword >> extra_bits) & 1;
402                                 } while (extra_bits != 0);
403
404                                 /* We've traversed the tree using the entire
405                                  * codeword, and we're now at the entry where
406                                  * the actual symbol will be stored.  This is
407                                  * distinguished from internal nodes by not
408                                  * having its high two bits set.  */
409                                 decode_table[node_idx] = sym;
410                         }
411                 }
412         }
413         return 0;
414 }