Path: blob/master/Utilities/cmzstd/lib/compress/zstd_opt.c
3158 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910#include "zstd_compress_internal.h"11#include "hist.h"12#include "zstd_opt.h"131415#define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */16#define ZSTD_MAX_PRICE (1<<30)1718#define ZSTD_PREDEF_THRESHOLD 8 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */192021/*-*************************************22* Price functions for optimal parser23***************************************/2425#if 0 /* approximation at bit level (for tests) */26# define BITCOST_ACCURACY 027# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)28# define WEIGHT(stat, opt) ((void)(opt), ZSTD_bitWeight(stat))29#elif 0 /* fractional bit accuracy (for tests) */30# define BITCOST_ACCURACY 831# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)32# define WEIGHT(stat,opt) ((void)(opt), ZSTD_fracWeight(stat))33#else /* opt==approx, ultra==accurate */34# define BITCOST_ACCURACY 835# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)36# define WEIGHT(stat,opt) ((opt) ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))37#endif3839/* ZSTD_bitWeight() :40* provide estimated "cost" of a stat in full bits only */41MEM_STATIC U32 ZSTD_bitWeight(U32 stat)42{43return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);44}4546/* ZSTD_fracWeight() :47* provide fractional-bit "cost" of a stat,48* using linear interpolation approximation */49MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)50{51U32 const stat = rawStat + 1;52U32 const hb = ZSTD_highbit32(stat);53U32 const BWeight = hb * BITCOST_MULTIPLIER;54/* Fweight was meant for "Fractional weight"55* but it's effectively a value between 1 and 256* using fixed point arithmetic */57U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;58U32 const weight = BWeight + FWeight;59assert(hb + BITCOST_ACCURACY < 31);60return weight;61}6263#if (DEBUGLEVEL>=2)64/* debugging function,65* @return price in bytes as fractional value66* for debug messages only */67MEM_STATIC double ZSTD_fCost(int price)68{69return (double)price / (BITCOST_MULTIPLIER*8);70}71#endif7273static int ZSTD_compressedLiterals(optState_t const* const optPtr)74{75return optPtr->literalCompressionMode != ZSTD_ps_disable;76}7778static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)79{80if (ZSTD_compressedLiterals(optPtr))81optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);82optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);83optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);84optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);85}868788static U32 sum_u32(const unsigned table[], size_t nbElts)89{90size_t n;91U32 total = 0;92for (n=0; n<nbElts; n++) {93total += table[n];94}95return total;96}9798typedef enum { base_0possible=0, base_1guaranteed=1 } base_directive_e;99100static U32101ZSTD_downscaleStats(unsigned* table, U32 lastEltIndex, U32 shift, base_directive_e base1)102{103U32 s, sum=0;104DEBUGLOG(5, "ZSTD_downscaleStats (nbElts=%u, shift=%u)",105(unsigned)lastEltIndex+1, (unsigned)shift );106assert(shift < 30);107for (s=0; s<lastEltIndex+1; s++) {108unsigned const base = base1 ? 1 : (table[s]>0);109unsigned const newStat = base + (table[s] >> shift);110sum += newStat;111table[s] = newStat;112}113return sum;114}115116/* ZSTD_scaleStats() :117* reduce all elt frequencies in table if sum too large118* return the resulting sum of elements */119static U32 ZSTD_scaleStats(unsigned* table, U32 lastEltIndex, U32 logTarget)120{121U32 const prevsum = sum_u32(table, lastEltIndex+1);122U32 const factor = prevsum >> logTarget;123DEBUGLOG(5, "ZSTD_scaleStats (nbElts=%u, target=%u)", (unsigned)lastEltIndex+1, (unsigned)logTarget);124assert(logTarget < 30);125if (factor <= 1) return prevsum;126return ZSTD_downscaleStats(table, lastEltIndex, ZSTD_highbit32(factor), base_1guaranteed);127}128129/* ZSTD_rescaleFreqs() :130* if first block (detected by optPtr->litLengthSum == 0) : init statistics131* take hints from dictionary if there is one132* and init from zero if there is none,133* using src for literals stats, and baseline stats for sequence symbols134* otherwise downscale existing stats, to be used as seed for next block.135*/136static void137ZSTD_rescaleFreqs(optState_t* const optPtr,138const BYTE* const src, size_t const srcSize,139int const optLevel)140{141int const compressedLiterals = ZSTD_compressedLiterals(optPtr);142DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);143optPtr->priceType = zop_dynamic;144145if (optPtr->litLengthSum == 0) { /* no literals stats collected -> first block assumed -> init */146147/* heuristic: use pre-defined stats for too small inputs */148if (srcSize <= ZSTD_PREDEF_THRESHOLD) {149DEBUGLOG(5, "srcSize <= %i : use predefined stats", ZSTD_PREDEF_THRESHOLD);150optPtr->priceType = zop_predef;151}152153assert(optPtr->symbolCosts != NULL);154if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {155156/* huffman stats covering the full value set : table presumed generated by dictionary */157optPtr->priceType = zop_dynamic;158159if (compressedLiterals) {160/* generate literals statistics from huffman table */161unsigned lit;162assert(optPtr->litFreq != NULL);163optPtr->litSum = 0;164for (lit=0; lit<=MaxLit; lit++) {165U32 const scaleLog = 11; /* scale to 2K */166U32 const bitCost = HUF_getNbBitsFromCTable(optPtr->symbolCosts->huf.CTable, lit);167assert(bitCost <= scaleLog);168optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;169optPtr->litSum += optPtr->litFreq[lit];170} }171172{ unsigned ll;173FSE_CState_t llstate;174FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);175optPtr->litLengthSum = 0;176for (ll=0; ll<=MaxLL; ll++) {177U32 const scaleLog = 10; /* scale to 1K */178U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);179assert(bitCost < scaleLog);180optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;181optPtr->litLengthSum += optPtr->litLengthFreq[ll];182} }183184{ unsigned ml;185FSE_CState_t mlstate;186FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);187optPtr->matchLengthSum = 0;188for (ml=0; ml<=MaxML; ml++) {189U32 const scaleLog = 10;190U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);191assert(bitCost < scaleLog);192optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;193optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];194} }195196{ unsigned of;197FSE_CState_t ofstate;198FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);199optPtr->offCodeSum = 0;200for (of=0; of<=MaxOff; of++) {201U32 const scaleLog = 10;202U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);203assert(bitCost < scaleLog);204optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;205optPtr->offCodeSum += optPtr->offCodeFreq[of];206} }207208} else { /* first block, no dictionary */209210assert(optPtr->litFreq != NULL);211if (compressedLiterals) {212/* base initial cost of literals on direct frequency within src */213unsigned lit = MaxLit;214HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */215optPtr->litSum = ZSTD_downscaleStats(optPtr->litFreq, MaxLit, 8, base_0possible);216}217218{ unsigned const baseLLfreqs[MaxLL+1] = {2194, 2, 1, 1, 1, 1, 1, 1,2201, 1, 1, 1, 1, 1, 1, 1,2211, 1, 1, 1, 1, 1, 1, 1,2221, 1, 1, 1, 1, 1, 1, 1,2231, 1, 1, 1224};225ZSTD_memcpy(optPtr->litLengthFreq, baseLLfreqs, sizeof(baseLLfreqs));226optPtr->litLengthSum = sum_u32(baseLLfreqs, MaxLL+1);227}228229{ unsigned ml;230for (ml=0; ml<=MaxML; ml++)231optPtr->matchLengthFreq[ml] = 1;232}233optPtr->matchLengthSum = MaxML+1;234235{ unsigned const baseOFCfreqs[MaxOff+1] = {2366, 2, 1, 1, 2, 3, 4, 4,2374, 3, 2, 1, 1, 1, 1, 1,2381, 1, 1, 1, 1, 1, 1, 1,2391, 1, 1, 1, 1, 1, 1, 1240};241ZSTD_memcpy(optPtr->offCodeFreq, baseOFCfreqs, sizeof(baseOFCfreqs));242optPtr->offCodeSum = sum_u32(baseOFCfreqs, MaxOff+1);243}244245}246247} else { /* new block : scale down accumulated statistics */248249if (compressedLiterals)250optPtr->litSum = ZSTD_scaleStats(optPtr->litFreq, MaxLit, 12);251optPtr->litLengthSum = ZSTD_scaleStats(optPtr->litLengthFreq, MaxLL, 11);252optPtr->matchLengthSum = ZSTD_scaleStats(optPtr->matchLengthFreq, MaxML, 11);253optPtr->offCodeSum = ZSTD_scaleStats(optPtr->offCodeFreq, MaxOff, 11);254}255256ZSTD_setBasePrices(optPtr, optLevel);257}258259/* ZSTD_rawLiteralsCost() :260* price of literals (only) in specified segment (which length can be 0).261* does not include price of literalLength symbol */262static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,263const optState_t* const optPtr,264int optLevel)265{266if (litLength == 0) return 0;267268if (!ZSTD_compressedLiterals(optPtr))269return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */270271if (optPtr->priceType == zop_predef)272return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */273274/* dynamic statistics */275{ U32 price = optPtr->litSumBasePrice * litLength;276U32 const litPriceMax = optPtr->litSumBasePrice - BITCOST_MULTIPLIER;277U32 u;278assert(optPtr->litSumBasePrice >= BITCOST_MULTIPLIER);279for (u=0; u < litLength; u++) {280U32 litPrice = WEIGHT(optPtr->litFreq[literals[u]], optLevel);281if (UNLIKELY(litPrice > litPriceMax)) litPrice = litPriceMax;282price -= litPrice;283}284return price;285}286}287288/* ZSTD_litLengthPrice() :289* cost of literalLength symbol */290static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)291{292assert(litLength <= ZSTD_BLOCKSIZE_MAX);293if (optPtr->priceType == zop_predef)294return WEIGHT(litLength, optLevel);295296/* ZSTD_LLcode() can't compute litLength price for sizes >= ZSTD_BLOCKSIZE_MAX297* because it isn't representable in the zstd format.298* So instead just pretend it would cost 1 bit more than ZSTD_BLOCKSIZE_MAX - 1.299* In such a case, the block would be all literals.300*/301if (litLength == ZSTD_BLOCKSIZE_MAX)302return BITCOST_MULTIPLIER + ZSTD_litLengthPrice(ZSTD_BLOCKSIZE_MAX - 1, optPtr, optLevel);303304/* dynamic statistics */305{ U32 const llCode = ZSTD_LLcode(litLength);306return (LL_bits[llCode] * BITCOST_MULTIPLIER)307+ optPtr->litLengthSumBasePrice308- WEIGHT(optPtr->litLengthFreq[llCode], optLevel);309}310}311312/* ZSTD_getMatchPrice() :313* Provides the cost of the match part (offset + matchLength) of a sequence.314* Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.315* @offBase : sumtype, representing an offset or a repcode, and using numeric representation of ZSTD_storeSeq()316* @optLevel: when <2, favors small offset for decompression speed (improved cache efficiency)317*/318FORCE_INLINE_TEMPLATE U32319ZSTD_getMatchPrice(U32 const offBase,320U32 const matchLength,321const optState_t* const optPtr,322int const optLevel)323{324U32 price;325U32 const offCode = ZSTD_highbit32(offBase);326U32 const mlBase = matchLength - MINMATCH;327assert(matchLength >= MINMATCH);328329if (optPtr->priceType == zop_predef) /* fixed scheme, does not use statistics */330return WEIGHT(mlBase, optLevel)331+ ((16 + offCode) * BITCOST_MULTIPLIER); /* emulated offset cost */332333/* dynamic statistics */334price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));335if ((optLevel<2) /*static*/ && offCode >= 20)336price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */337338/* match Length */339{ U32 const mlCode = ZSTD_MLcode(mlBase);340price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));341}342343price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */344345DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);346return price;347}348349/* ZSTD_updateStats() :350* assumption : literals + litLength <= iend */351static void ZSTD_updateStats(optState_t* const optPtr,352U32 litLength, const BYTE* literals,353U32 offBase, U32 matchLength)354{355/* literals */356if (ZSTD_compressedLiterals(optPtr)) {357U32 u;358for (u=0; u < litLength; u++)359optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;360optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;361}362363/* literal Length */364{ U32 const llCode = ZSTD_LLcode(litLength);365optPtr->litLengthFreq[llCode]++;366optPtr->litLengthSum++;367}368369/* offset code : follows storeSeq() numeric representation */370{ U32 const offCode = ZSTD_highbit32(offBase);371assert(offCode <= MaxOff);372optPtr->offCodeFreq[offCode]++;373optPtr->offCodeSum++;374}375376/* match Length */377{ U32 const mlBase = matchLength - MINMATCH;378U32 const mlCode = ZSTD_MLcode(mlBase);379optPtr->matchLengthFreq[mlCode]++;380optPtr->matchLengthSum++;381}382}383384385/* ZSTD_readMINMATCH() :386* function safe only for comparisons387* assumption : memPtr must be at least 4 bytes before end of buffer */388MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)389{390switch (length)391{392default :393case 4 : return MEM_read32(memPtr);394case 3 : if (MEM_isLittleEndian())395return MEM_read32(memPtr)<<8;396else397return MEM_read32(memPtr)>>8;398}399}400401402/* Update hashTable3 up to ip (excluded)403Assumption : always within prefix (i.e. not within extDict) */404static U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms,405U32* nextToUpdate3,406const BYTE* const ip)407{408U32* const hashTable3 = ms->hashTable3;409U32 const hashLog3 = ms->hashLog3;410const BYTE* const base = ms->window.base;411U32 idx = *nextToUpdate3;412U32 const target = (U32)(ip - base);413size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);414assert(hashLog3 > 0);415416while(idx < target) {417hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;418idx++;419}420421*nextToUpdate3 = target;422return hashTable3[hash3];423}424425426/*-*************************************427* Binary Tree search428***************************************/429/** ZSTD_insertBt1() : add one or multiple positions to tree.430* @param ip assumed <= iend-8 .431* @param target The target of ZSTD_updateTree_internal() - we are filling to this position432* @return : nb of positions added */433static U32 ZSTD_insertBt1(434const ZSTD_matchState_t* ms,435const BYTE* const ip, const BYTE* const iend,436U32 const target,437U32 const mls, const int extDict)438{439const ZSTD_compressionParameters* const cParams = &ms->cParams;440U32* const hashTable = ms->hashTable;441U32 const hashLog = cParams->hashLog;442size_t const h = ZSTD_hashPtr(ip, hashLog, mls);443U32* const bt = ms->chainTable;444U32 const btLog = cParams->chainLog - 1;445U32 const btMask = (1 << btLog) - 1;446U32 matchIndex = hashTable[h];447size_t commonLengthSmaller=0, commonLengthLarger=0;448const BYTE* const base = ms->window.base;449const BYTE* const dictBase = ms->window.dictBase;450const U32 dictLimit = ms->window.dictLimit;451const BYTE* const dictEnd = dictBase + dictLimit;452const BYTE* const prefixStart = base + dictLimit;453const BYTE* match;454const U32 curr = (U32)(ip-base);455const U32 btLow = btMask >= curr ? 0 : curr - btMask;456U32* smallerPtr = bt + 2*(curr&btMask);457U32* largerPtr = smallerPtr + 1;458U32 dummy32; /* to be nullified at the end */459/* windowLow is based on target because460* we only need positions that will be in the window at the end of the tree update.461*/462U32 const windowLow = ZSTD_getLowestMatchIndex(ms, target, cParams->windowLog);463U32 matchEndIdx = curr+8+1;464size_t bestLength = 8;465U32 nbCompares = 1U << cParams->searchLog;466#ifdef ZSTD_C_PREDICT467U32 predictedSmall = *(bt + 2*((curr-1)&btMask) + 0);468U32 predictedLarge = *(bt + 2*((curr-1)&btMask) + 1);469predictedSmall += (predictedSmall>0);470predictedLarge += (predictedLarge>0);471#endif /* ZSTD_C_PREDICT */472473DEBUGLOG(8, "ZSTD_insertBt1 (%u)", curr);474475assert(curr <= target);476assert(ip <= iend-8); /* required for h calculation */477hashTable[h] = curr; /* Update Hash Table */478479assert(windowLow > 0);480for (; nbCompares && (matchIndex >= windowLow); --nbCompares) {481U32* const nextPtr = bt + 2*(matchIndex & btMask);482size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */483assert(matchIndex < curr);484485#ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */486const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */487if (matchIndex == predictedSmall) {488/* no need to check length, result known */489*smallerPtr = matchIndex;490if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */491smallerPtr = nextPtr+1; /* new "smaller" => larger of match */492matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */493predictedSmall = predictPtr[1] + (predictPtr[1]>0);494continue;495}496if (matchIndex == predictedLarge) {497*largerPtr = matchIndex;498if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */499largerPtr = nextPtr;500matchIndex = nextPtr[0];501predictedLarge = predictPtr[0] + (predictPtr[0]>0);502continue;503}504#endif505506if (!extDict || (matchIndex+matchLength >= dictLimit)) {507assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */508match = base + matchIndex;509matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);510} else {511match = dictBase + matchIndex;512matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);513if (matchIndex+matchLength >= dictLimit)514match = base + matchIndex; /* to prepare for next usage of match[matchLength] */515}516517if (matchLength > bestLength) {518bestLength = matchLength;519if (matchLength > matchEndIdx - matchIndex)520matchEndIdx = matchIndex + (U32)matchLength;521}522523if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */524break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */525}526527if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */528/* match is smaller than current */529*smallerPtr = matchIndex; /* update smaller idx */530commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */531if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */532smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */533matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */534} else {535/* match is larger than current */536*largerPtr = matchIndex;537commonLengthLarger = matchLength;538if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */539largerPtr = nextPtr;540matchIndex = nextPtr[0];541} }542543*smallerPtr = *largerPtr = 0;544{ U32 positions = 0;545if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384)); /* speed optimization */546assert(matchEndIdx > curr + 8);547return MAX(positions, matchEndIdx - (curr + 8));548}549}550551FORCE_INLINE_TEMPLATE552void ZSTD_updateTree_internal(553ZSTD_matchState_t* ms,554const BYTE* const ip, const BYTE* const iend,555const U32 mls, const ZSTD_dictMode_e dictMode)556{557const BYTE* const base = ms->window.base;558U32 const target = (U32)(ip - base);559U32 idx = ms->nextToUpdate;560DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",561idx, target, dictMode);562563while(idx < target) {564U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, target, mls, dictMode == ZSTD_extDict);565assert(idx < (U32)(idx + forward));566idx += forward;567}568assert((size_t)(ip - base) <= (size_t)(U32)(-1));569assert((size_t)(iend - base) <= (size_t)(U32)(-1));570ms->nextToUpdate = target;571}572573void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {574ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);575}576577FORCE_INLINE_TEMPLATE U32578ZSTD_insertBtAndGetAllMatches (579ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */580ZSTD_matchState_t* ms,581U32* nextToUpdate3,582const BYTE* const ip, const BYTE* const iLimit,583const ZSTD_dictMode_e dictMode,584const U32 rep[ZSTD_REP_NUM],585const U32 ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */586const U32 lengthToBeat,587const U32 mls /* template */)588{589const ZSTD_compressionParameters* const cParams = &ms->cParams;590U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);591const BYTE* const base = ms->window.base;592U32 const curr = (U32)(ip-base);593U32 const hashLog = cParams->hashLog;594U32 const minMatch = (mls==3) ? 3 : 4;595U32* const hashTable = ms->hashTable;596size_t const h = ZSTD_hashPtr(ip, hashLog, mls);597U32 matchIndex = hashTable[h];598U32* const bt = ms->chainTable;599U32 const btLog = cParams->chainLog - 1;600U32 const btMask= (1U << btLog) - 1;601size_t commonLengthSmaller=0, commonLengthLarger=0;602const BYTE* const dictBase = ms->window.dictBase;603U32 const dictLimit = ms->window.dictLimit;604const BYTE* const dictEnd = dictBase + dictLimit;605const BYTE* const prefixStart = base + dictLimit;606U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;607U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);608U32 const matchLow = windowLow ? windowLow : 1;609U32* smallerPtr = bt + 2*(curr&btMask);610U32* largerPtr = bt + 2*(curr&btMask) + 1;611U32 matchEndIdx = curr+8+1; /* farthest referenced position of any match => detects repetitive patterns */612U32 dummy32; /* to be nullified at the end */613U32 mnum = 0;614U32 nbCompares = 1U << cParams->searchLog;615616const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;617const ZSTD_compressionParameters* const dmsCParams =618dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;619const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;620const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;621U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;622U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;623U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;624U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;625U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;626U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;627U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;628629size_t bestLength = lengthToBeat-1;630DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", curr);631632/* check repCode */633assert(ll0 <= 1); /* necessarily 1 or 0 */634{ U32 const lastR = ZSTD_REP_NUM + ll0;635U32 repCode;636for (repCode = ll0; repCode < lastR; repCode++) {637U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];638U32 const repIndex = curr - repOffset;639U32 repLen = 0;640assert(curr >= dictLimit);641if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < curr-dictLimit) { /* equivalent to `curr > repIndex >= dictLimit` */642/* We must validate the repcode offset because when we're using a dictionary the643* valid offset range shrinks when the dictionary goes out of bounds.644*/645if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {646repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;647}648} else { /* repIndex < dictLimit || repIndex >= curr */649const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?650dmsBase + repIndex - dmsIndexDelta :651dictBase + repIndex;652assert(curr >= windowLow);653if ( dictMode == ZSTD_extDict654&& ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow) /* equivalent to `curr > repIndex >= windowLow` */655& (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)656&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {657repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;658}659if (dictMode == ZSTD_dictMatchState660&& ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `curr > repIndex >= dmsLowLimit` */661& ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */662&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {663repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;664} }665/* save longer solution */666if (repLen > bestLength) {667DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",668repCode, ll0, repOffset, repLen);669bestLength = repLen;670matches[mnum].off = REPCODE_TO_OFFBASE(repCode - ll0 + 1); /* expect value between 1 and 3 */671matches[mnum].len = (U32)repLen;672mnum++;673if ( (repLen > sufficient_len)674| (ip+repLen == iLimit) ) { /* best possible */675return mnum;676} } } }677678/* HC3 match finder */679if ((mls == 3) /*static*/ && (bestLength < mls)) {680U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);681if ((matchIndex3 >= matchLow)682& (curr - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {683size_t mlen;684if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {685const BYTE* const match = base + matchIndex3;686mlen = ZSTD_count(ip, match, iLimit);687} else {688const BYTE* const match = dictBase + matchIndex3;689mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);690}691692/* save best solution */693if (mlen >= mls /* == 3 > bestLength */) {694DEBUGLOG(8, "found small match with hlog3, of length %u",695(U32)mlen);696bestLength = mlen;697assert(curr > matchIndex3);698assert(mnum==0); /* no prior solution */699matches[0].off = OFFSET_TO_OFFBASE(curr - matchIndex3);700matches[0].len = (U32)mlen;701mnum = 1;702if ( (mlen > sufficient_len) |703(ip+mlen == iLimit) ) { /* best possible length */704ms->nextToUpdate = curr+1; /* skip insertion */705return 1;706} } }707/* no dictMatchState lookup: dicts don't have a populated HC3 table */708} /* if (mls == 3) */709710hashTable[h] = curr; /* Update Hash Table */711712for (; nbCompares && (matchIndex >= matchLow); --nbCompares) {713U32* const nextPtr = bt + 2*(matchIndex & btMask);714const BYTE* match;715size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */716assert(curr > matchIndex);717718if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {719assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */720match = base + matchIndex;721if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */722matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);723} else {724match = dictBase + matchIndex;725assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */726matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);727if (matchIndex+matchLength >= dictLimit)728match = base + matchIndex; /* prepare for match[matchLength] read */729}730731if (matchLength > bestLength) {732DEBUGLOG(8, "found match of length %u at distance %u (offBase=%u)",733(U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));734assert(matchEndIdx > matchIndex);735if (matchLength > matchEndIdx - matchIndex)736matchEndIdx = matchIndex + (U32)matchLength;737bestLength = matchLength;738matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);739matches[mnum].len = (U32)matchLength;740mnum++;741if ( (matchLength > ZSTD_OPT_NUM)742| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {743if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */744break; /* drop, to preserve bt consistency (miss a little bit of compression) */745} }746747if (match[matchLength] < ip[matchLength]) {748/* match smaller than current */749*smallerPtr = matchIndex; /* update smaller idx */750commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */751if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */752smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */753matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */754} else {755*largerPtr = matchIndex;756commonLengthLarger = matchLength;757if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */758largerPtr = nextPtr;759matchIndex = nextPtr[0];760} }761762*smallerPtr = *largerPtr = 0;763764assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */765if (dictMode == ZSTD_dictMatchState && nbCompares) {766size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);767U32 dictMatchIndex = dms->hashTable[dmsH];768const U32* const dmsBt = dms->chainTable;769commonLengthSmaller = commonLengthLarger = 0;770for (; nbCompares && (dictMatchIndex > dmsLowLimit); --nbCompares) {771const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);772size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */773const BYTE* match = dmsBase + dictMatchIndex;774matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);775if (dictMatchIndex+matchLength >= dmsHighLimit)776match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */777778if (matchLength > bestLength) {779matchIndex = dictMatchIndex + dmsIndexDelta;780DEBUGLOG(8, "found dms match of length %u at distance %u (offBase=%u)",781(U32)matchLength, curr - matchIndex, OFFSET_TO_OFFBASE(curr - matchIndex));782if (matchLength > matchEndIdx - matchIndex)783matchEndIdx = matchIndex + (U32)matchLength;784bestLength = matchLength;785matches[mnum].off = OFFSET_TO_OFFBASE(curr - matchIndex);786matches[mnum].len = (U32)matchLength;787mnum++;788if ( (matchLength > ZSTD_OPT_NUM)789| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {790break; /* drop, to guarantee consistency (miss a little bit of compression) */791} }792793if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */794if (match[matchLength] < ip[matchLength]) {795commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */796dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */797} else {798/* match is larger than current */799commonLengthLarger = matchLength;800dictMatchIndex = nextPtr[0];801} } } /* if (dictMode == ZSTD_dictMatchState) */802803assert(matchEndIdx > curr+8);804ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */805return mnum;806}807808typedef U32 (*ZSTD_getAllMatchesFn)(809ZSTD_match_t*,810ZSTD_matchState_t*,811U32*,812const BYTE*,813const BYTE*,814const U32 rep[ZSTD_REP_NUM],815U32 const ll0,816U32 const lengthToBeat);817818FORCE_INLINE_TEMPLATE U32 ZSTD_btGetAllMatches_internal(819ZSTD_match_t* matches,820ZSTD_matchState_t* ms,821U32* nextToUpdate3,822const BYTE* ip,823const BYTE* const iHighLimit,824const U32 rep[ZSTD_REP_NUM],825U32 const ll0,826U32 const lengthToBeat,827const ZSTD_dictMode_e dictMode,828const U32 mls)829{830assert(BOUNDED(3, ms->cParams.minMatch, 6) == mls);831DEBUGLOG(8, "ZSTD_BtGetAllMatches(dictMode=%d, mls=%u)", (int)dictMode, mls);832if (ip < ms->window.base + ms->nextToUpdate)833return 0; /* skipped area */834ZSTD_updateTree_internal(ms, ip, iHighLimit, mls, dictMode);835return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, mls);836}837838#define ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls) ZSTD_btGetAllMatches_##dictMode##_##mls839840#define GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, mls) \841static U32 ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls)( \842ZSTD_match_t* matches, \843ZSTD_matchState_t* ms, \844U32* nextToUpdate3, \845const BYTE* ip, \846const BYTE* const iHighLimit, \847const U32 rep[ZSTD_REP_NUM], \848U32 const ll0, \849U32 const lengthToBeat) \850{ \851return ZSTD_btGetAllMatches_internal( \852matches, ms, nextToUpdate3, ip, iHighLimit, \853rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \854}855856#define GEN_ZSTD_BT_GET_ALL_MATCHES(dictMode) \857GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 3) \858GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 4) \859GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 5) \860GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 6)861862GEN_ZSTD_BT_GET_ALL_MATCHES(noDict)863GEN_ZSTD_BT_GET_ALL_MATCHES(extDict)864GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState)865866#define ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMode) \867{ \868ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 3), \869ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 4), \870ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 5), \871ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 6) \872}873874static ZSTD_getAllMatchesFn875ZSTD_selectBtGetAllMatches(ZSTD_matchState_t const* ms, ZSTD_dictMode_e const dictMode)876{877ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = {878ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict),879ZSTD_BT_GET_ALL_MATCHES_ARRAY(extDict),880ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMatchState)881};882U32 const mls = BOUNDED(3, ms->cParams.minMatch, 6);883assert((U32)dictMode < 3);884assert(mls - 3 < 4);885return getAllMatchesFns[(int)dictMode][mls - 3];886}887888/*************************889* LDM helper functions *890*************************/891892/* Struct containing info needed to make decision about ldm inclusion */893typedef struct {894rawSeqStore_t seqStore; /* External match candidates store for this block */895U32 startPosInBlock; /* Start position of the current match candidate */896U32 endPosInBlock; /* End position of the current match candidate */897U32 offset; /* Offset of the match candidate */898} ZSTD_optLdm_t;899900/* ZSTD_optLdm_skipRawSeqStoreBytes():901* Moves forward in @rawSeqStore by @nbBytes,902* which will update the fields 'pos' and 'posInSequence'.903*/904static void ZSTD_optLdm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes)905{906U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);907while (currPos && rawSeqStore->pos < rawSeqStore->size) {908rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];909if (currPos >= currSeq.litLength + currSeq.matchLength) {910currPos -= currSeq.litLength + currSeq.matchLength;911rawSeqStore->pos++;912} else {913rawSeqStore->posInSequence = currPos;914break;915}916}917if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {918rawSeqStore->posInSequence = 0;919}920}921922/* ZSTD_opt_getNextMatchAndUpdateSeqStore():923* Calculates the beginning and end of the next match in the current block.924* Updates 'pos' and 'posInSequence' of the ldmSeqStore.925*/926static void927ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock,928U32 blockBytesRemaining)929{930rawSeq currSeq;931U32 currBlockEndPos;932U32 literalsBytesRemaining;933U32 matchBytesRemaining;934935/* Setting match end position to MAX to ensure we never use an LDM during this block */936if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {937optLdm->startPosInBlock = UINT_MAX;938optLdm->endPosInBlock = UINT_MAX;939return;940}941/* Calculate appropriate bytes left in matchLength and litLength942* after adjusting based on ldmSeqStore->posInSequence */943currSeq = optLdm->seqStore.seq[optLdm->seqStore.pos];944assert(optLdm->seqStore.posInSequence <= currSeq.litLength + currSeq.matchLength);945currBlockEndPos = currPosInBlock + blockBytesRemaining;946literalsBytesRemaining = (optLdm->seqStore.posInSequence < currSeq.litLength) ?947currSeq.litLength - (U32)optLdm->seqStore.posInSequence :9480;949matchBytesRemaining = (literalsBytesRemaining == 0) ?950currSeq.matchLength - ((U32)optLdm->seqStore.posInSequence - currSeq.litLength) :951currSeq.matchLength;952953/* If there are more literal bytes than bytes remaining in block, no ldm is possible */954if (literalsBytesRemaining >= blockBytesRemaining) {955optLdm->startPosInBlock = UINT_MAX;956optLdm->endPosInBlock = UINT_MAX;957ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, blockBytesRemaining);958return;959}960961/* Matches may be < MINMATCH by this process. In that case, we will reject them962when we are deciding whether or not to add the ldm */963optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining;964optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining;965optLdm->offset = currSeq.offset;966967if (optLdm->endPosInBlock > currBlockEndPos) {968/* Match ends after the block ends, we can't use the whole match */969optLdm->endPosInBlock = currBlockEndPos;970ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, currBlockEndPos - currPosInBlock);971} else {972/* Consume nb of bytes equal to size of sequence left */973ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, literalsBytesRemaining + matchBytesRemaining);974}975}976977/* ZSTD_optLdm_maybeAddMatch():978* Adds a match if it's long enough,979* based on it's 'matchStartPosInBlock' and 'matchEndPosInBlock',980* into 'matches'. Maintains the correct ordering of 'matches'.981*/982static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches,983const ZSTD_optLdm_t* optLdm, U32 currPosInBlock)984{985U32 const posDiff = currPosInBlock - optLdm->startPosInBlock;986/* Note: ZSTD_match_t actually contains offBase and matchLength (before subtracting MINMATCH) */987U32 const candidateMatchLength = optLdm->endPosInBlock - optLdm->startPosInBlock - posDiff;988989/* Ensure that current block position is not outside of the match */990if (currPosInBlock < optLdm->startPosInBlock991|| currPosInBlock >= optLdm->endPosInBlock992|| candidateMatchLength < MINMATCH) {993return;994}995996if (*nbMatches == 0 || ((candidateMatchLength > matches[*nbMatches-1].len) && *nbMatches < ZSTD_OPT_NUM)) {997U32 const candidateOffBase = OFFSET_TO_OFFBASE(optLdm->offset);998DEBUGLOG(6, "ZSTD_optLdm_maybeAddMatch(): Adding ldm candidate match (offBase: %u matchLength %u) at block position=%u",999candidateOffBase, candidateMatchLength, currPosInBlock);1000matches[*nbMatches].len = candidateMatchLength;1001matches[*nbMatches].off = candidateOffBase;1002(*nbMatches)++;1003}1004}10051006/* ZSTD_optLdm_processMatchCandidate():1007* Wrapper function to update ldm seq store and call ldm functions as necessary.1008*/1009static void1010ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm,1011ZSTD_match_t* matches, U32* nbMatches,1012U32 currPosInBlock, U32 remainingBytes)1013{1014if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {1015return;1016}10171018if (currPosInBlock >= optLdm->endPosInBlock) {1019if (currPosInBlock > optLdm->endPosInBlock) {1020/* The position at which ZSTD_optLdm_processMatchCandidate() is called is not necessarily1021* at the end of a match from the ldm seq store, and will often be some bytes1022* over beyond matchEndPosInBlock. As such, we need to correct for these "overshoots"1023*/1024U32 const posOvershoot = currPosInBlock - optLdm->endPosInBlock;1025ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, posOvershoot);1026}1027ZSTD_opt_getNextMatchAndUpdateSeqStore(optLdm, currPosInBlock, remainingBytes);1028}1029ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock);1030}103110321033/*-*******************************1034* Optimal parser1035*********************************/10361037static U32 ZSTD_totalLen(ZSTD_optimal_t sol)1038{1039return sol.litlen + sol.mlen;1040}10411042#if 0 /* debug */10431044static void1045listStats(const U32* table, int lastEltID)1046{1047int const nbElts = lastEltID + 1;1048int enb;1049for (enb=0; enb < nbElts; enb++) {1050(void)table;1051/* RAWLOG(2, "%3i:%3i, ", enb, table[enb]); */1052RAWLOG(2, "%4i,", table[enb]);1053}1054RAWLOG(2, " \n");1055}10561057#endif10581059FORCE_INLINE_TEMPLATE size_t1060ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,1061seqStore_t* seqStore,1062U32 rep[ZSTD_REP_NUM],1063const void* src, size_t srcSize,1064const int optLevel,1065const ZSTD_dictMode_e dictMode)1066{1067optState_t* const optStatePtr = &ms->opt;1068const BYTE* const istart = (const BYTE*)src;1069const BYTE* ip = istart;1070const BYTE* anchor = istart;1071const BYTE* const iend = istart + srcSize;1072const BYTE* const ilimit = iend - 8;1073const BYTE* const base = ms->window.base;1074const BYTE* const prefixStart = base + ms->window.dictLimit;1075const ZSTD_compressionParameters* const cParams = &ms->cParams;10761077ZSTD_getAllMatchesFn getAllMatches = ZSTD_selectBtGetAllMatches(ms, dictMode);10781079U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);1080U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;1081U32 nextToUpdate3 = ms->nextToUpdate;10821083ZSTD_optimal_t* const opt = optStatePtr->priceTable;1084ZSTD_match_t* const matches = optStatePtr->matchTable;1085ZSTD_optimal_t lastSequence;1086ZSTD_optLdm_t optLdm;10871088ZSTD_memset(&lastSequence, 0, sizeof(ZSTD_optimal_t));10891090optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;1091optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;1092ZSTD_opt_getNextMatchAndUpdateSeqStore(&optLdm, (U32)(ip-istart), (U32)(iend-ip));10931094/* init */1095DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",1096(U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);1097assert(optLevel <= 2);1098ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);1099ip += (ip==prefixStart);11001101/* Match Loop */1102while (ip < ilimit) {1103U32 cur, last_pos = 0;11041105/* find first match */1106{ U32 const litlen = (U32)(ip - anchor);1107U32 const ll0 = !litlen;1108U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);1109ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,1110(U32)(ip-istart), (U32)(iend - ip));1111if (!nbMatches) { ip++; continue; }11121113/* initialize opt[0] */1114{ U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }1115opt[0].mlen = 0; /* means is_a_literal */1116opt[0].litlen = litlen;1117/* We don't need to include the actual price of the literals because1118* it is static for the duration of the forward pass, and is included1119* in every price. We include the literal length to avoid negative1120* prices when we subtract the previous literal length.1121*/1122opt[0].price = (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel);11231124/* large match -> immediate encoding */1125{ U32 const maxML = matches[nbMatches-1].len;1126U32 const maxOffBase = matches[nbMatches-1].off;1127DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffBase=%u at cPos=%u => start new series",1128nbMatches, maxML, maxOffBase, (U32)(ip-prefixStart));11291130if (maxML > sufficient_len) {1131lastSequence.litlen = litlen;1132lastSequence.mlen = maxML;1133lastSequence.off = maxOffBase;1134DEBUGLOG(6, "large match (%u>%u), immediate encoding",1135maxML, sufficient_len);1136cur = 0;1137last_pos = ZSTD_totalLen(lastSequence);1138goto _shortestPath;1139} }11401141/* set prices for first matches starting position == 0 */1142assert(opt[0].price >= 0);1143{ U32 const literalsPrice = (U32)opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);1144U32 pos;1145U32 matchNb;1146for (pos = 1; pos < minMatch; pos++) {1147opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */1148}1149for (matchNb = 0; matchNb < nbMatches; matchNb++) {1150U32 const offBase = matches[matchNb].off;1151U32 const end = matches[matchNb].len;1152for ( ; pos <= end ; pos++ ) {1153U32 const matchPrice = ZSTD_getMatchPrice(offBase, pos, optStatePtr, optLevel);1154U32 const sequencePrice = literalsPrice + matchPrice;1155DEBUGLOG(7, "rPos:%u => set initial price : %.2f",1156pos, ZSTD_fCost((int)sequencePrice));1157opt[pos].mlen = pos;1158opt[pos].off = offBase;1159opt[pos].litlen = litlen;1160opt[pos].price = (int)sequencePrice;1161} }1162last_pos = pos-1;1163}1164}11651166/* check further positions */1167for (cur = 1; cur <= last_pos; cur++) {1168const BYTE* const inr = ip + cur;1169assert(cur < ZSTD_OPT_NUM);1170DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)11711172/* Fix current position with one literal if cheaper */1173{ U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;1174int const price = opt[cur-1].price1175+ (int)ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)1176+ (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)1177- (int)ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);1178assert(price < 1000000000); /* overflow check */1179if (price <= opt[cur].price) {1180DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",1181inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,1182opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);1183opt[cur].mlen = 0;1184opt[cur].off = 0;1185opt[cur].litlen = litlen;1186opt[cur].price = price;1187} else {1188DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",1189inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),1190opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);1191}1192}11931194/* Set the repcodes of the current position. We must do it here1195* because we rely on the repcodes of the 2nd to last sequence being1196* correct to set the next chunks repcodes during the backward1197* traversal.1198*/1199ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));1200assert(cur >= opt[cur].mlen);1201if (opt[cur].mlen != 0) {1202U32 const prev = cur - opt[cur].mlen;1203repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0);1204ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));1205} else {1206ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));1207}12081209/* last match must start at a minimum distance of 8 from oend */1210if (inr > ilimit) continue;12111212if (cur == last_pos) break;12131214if ( (optLevel==0) /*static_test*/1215&& (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {1216DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);1217continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */1218}12191220assert(opt[cur].price >= 0);1221{ U32 const ll0 = (opt[cur].mlen != 0);1222U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;1223U32 const previousPrice = (U32)opt[cur].price;1224U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);1225U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);1226U32 matchNb;12271228ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,1229(U32)(inr-istart), (U32)(iend-inr));12301231if (!nbMatches) {1232DEBUGLOG(7, "rPos:%u : no match found", cur);1233continue;1234}12351236{ U32 const maxML = matches[nbMatches-1].len;1237DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",1238inr-istart, cur, nbMatches, maxML);12391240if ( (maxML > sufficient_len)1241|| (cur + maxML >= ZSTD_OPT_NUM) ) {1242lastSequence.mlen = maxML;1243lastSequence.off = matches[nbMatches-1].off;1244lastSequence.litlen = litlen;1245cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0; /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */1246last_pos = cur + ZSTD_totalLen(lastSequence);1247if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */1248goto _shortestPath;1249} }12501251/* set prices using matches found at position == cur */1252for (matchNb = 0; matchNb < nbMatches; matchNb++) {1253U32 const offset = matches[matchNb].off;1254U32 const lastML = matches[matchNb].len;1255U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;1256U32 mlen;12571258DEBUGLOG(7, "testing match %u => offBase=%4u, mlen=%2u, llen=%2u",1259matchNb, matches[matchNb].off, lastML, litlen);12601261for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */1262U32 const pos = cur + mlen;1263int const price = (int)basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);12641265if ((pos > last_pos) || (price < opt[pos].price)) {1266DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",1267pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));1268while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */1269opt[pos].mlen = mlen;1270opt[pos].off = offset;1271opt[pos].litlen = litlen;1272opt[pos].price = price;1273} else {1274DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",1275pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));1276if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */1277}1278} } }1279} /* for (cur = 1; cur <= last_pos; cur++) */12801281lastSequence = opt[last_pos];1282cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */1283assert(cur < ZSTD_OPT_NUM); /* control overflow*/12841285_shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */1286assert(opt[0].mlen == 0);12871288/* Set the next chunk's repcodes based on the repcodes of the beginning1289* of the last match, and the last sequence. This avoids us having to1290* update them while traversing the sequences.1291*/1292if (lastSequence.mlen != 0) {1293repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0);1294ZSTD_memcpy(rep, &reps, sizeof(reps));1295} else {1296ZSTD_memcpy(rep, opt[cur].rep, sizeof(repcodes_t));1297}12981299{ U32 const storeEnd = cur + 1;1300U32 storeStart = storeEnd;1301U32 seqPos = cur;13021303DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",1304last_pos, cur); (void)last_pos;1305assert(storeEnd < ZSTD_OPT_NUM);1306DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1307storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);1308opt[storeEnd] = lastSequence;1309while (seqPos > 0) {1310U32 const backDist = ZSTD_totalLen(opt[seqPos]);1311storeStart--;1312DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1313seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);1314opt[storeStart] = opt[seqPos];1315seqPos = (seqPos > backDist) ? seqPos - backDist : 0;1316}13171318/* save sequences */1319DEBUGLOG(6, "sending selected sequences into seqStore")1320{ U32 storePos;1321for (storePos=storeStart; storePos <= storeEnd; storePos++) {1322U32 const llen = opt[storePos].litlen;1323U32 const mlen = opt[storePos].mlen;1324U32 const offBase = opt[storePos].off;1325U32 const advance = llen + mlen;1326DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",1327anchor - istart, (unsigned)llen, (unsigned)mlen);13281329if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */1330assert(storePos == storeEnd); /* must be last sequence */1331ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */1332continue; /* will finish */1333}13341335assert(anchor + llen <= iend);1336ZSTD_updateStats(optStatePtr, llen, anchor, offBase, mlen);1337ZSTD_storeSeq(seqStore, llen, anchor, iend, offBase, mlen);1338anchor += advance;1339ip = anchor;1340} }1341ZSTD_setBasePrices(optStatePtr, optLevel);1342}1343} /* while (ip < ilimit) */13441345/* Return the last literals size */1346return (size_t)(iend - anchor);1347}13481349static size_t ZSTD_compressBlock_opt0(1350ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1351const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)1352{1353return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode);1354}13551356static size_t ZSTD_compressBlock_opt2(1357ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1358const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)1359{1360return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode);1361}13621363size_t ZSTD_compressBlock_btopt(1364ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1365const void* src, size_t srcSize)1366{1367DEBUGLOG(5, "ZSTD_compressBlock_btopt");1368return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1369}13701371137213731374/* ZSTD_initStats_ultra():1375* make a first compression pass, just to seed stats with more accurate starting values.1376* only works on first block, with no dictionary and no ldm.1377* this function cannot error out, its narrow contract must be respected.1378*/1379static void1380ZSTD_initStats_ultra(ZSTD_matchState_t* ms,1381seqStore_t* seqStore,1382U32 rep[ZSTD_REP_NUM],1383const void* src, size_t srcSize)1384{1385U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */1386ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));13871388DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);1389assert(ms->opt.litLengthSum == 0); /* first block */1390assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */1391assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */1392assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */13931394ZSTD_compressBlock_opt2(ms, seqStore, tmpRep, src, srcSize, ZSTD_noDict); /* generate stats into ms->opt*/13951396/* invalidate first scan from history, only keep entropy stats */1397ZSTD_resetSeqStore(seqStore);1398ms->window.base -= srcSize;1399ms->window.dictLimit += (U32)srcSize;1400ms->window.lowLimit = ms->window.dictLimit;1401ms->nextToUpdate = ms->window.dictLimit;14021403}14041405size_t ZSTD_compressBlock_btultra(1406ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1407const void* src, size_t srcSize)1408{1409DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);1410return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1411}14121413size_t ZSTD_compressBlock_btultra2(1414ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1415const void* src, size_t srcSize)1416{1417U32 const curr = (U32)((const BYTE*)src - ms->window.base);1418DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);14191420/* 2-passes strategy:1421* this strategy makes a first pass over first block to collect statistics1422* in order to seed next round's statistics with it.1423* After 1st pass, function forgets history, and starts a new block.1424* Consequently, this can only work if no data has been previously loaded in tables,1425* aka, no dictionary, no prefix, no ldm preprocessing.1426* The compression ratio gain is generally small (~0.5% on first block),1427** the cost is 2x cpu time on first block. */1428assert(srcSize <= ZSTD_BLOCKSIZE_MAX);1429if ( (ms->opt.litLengthSum==0) /* first block */1430&& (seqStore->sequences == seqStore->sequencesStart) /* no ldm */1431&& (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */1432&& (curr == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */1433&& (srcSize > ZSTD_PREDEF_THRESHOLD) /* input large enough to not employ default stats */1434) {1435ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);1436}14371438return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1439}14401441size_t ZSTD_compressBlock_btopt_dictMatchState(1442ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1443const void* src, size_t srcSize)1444{1445return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);1446}14471448size_t ZSTD_compressBlock_btultra_dictMatchState(1449ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1450const void* src, size_t srcSize)1451{1452return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);1453}14541455size_t ZSTD_compressBlock_btopt_extDict(1456ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1457const void* src, size_t srcSize)1458{1459return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict);1460}14611462size_t ZSTD_compressBlock_btultra_extDict(1463ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1464const void* src, size_t srcSize)1465{1466return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict);1467}14681469/* note : no btultra2 variant for extDict nor dictMatchState,1470* because btultra2 is not meant to work with dictionaries1471* and is only specific for the first block (no prefix) */147214731474