[llvm] [AggressiveInstCombine] Fold low-bits mask table loads to arithmetic (PR #222509)
Craig Topper via llvm-commits
llvm-commits at lists.llvm.org
Mon Sep 14 10:47:35 PDT 2026
================
@@ -1231,12 +1233,84 @@ static bool tryToRecognizeTableBasedLog2(LoadInst *LI, Type *AccessType,
return true;
}
-// Match a table-based cttz or log2 implementation. These patterns share a
-// load from a global table pattern that we match first. Then we try the
-// specific matches for the cttz and log2 patterns.
-static bool tryToRecognizeTableBasedCttzOrLog2(Instruction &I,
- const DataLayout &DL,
- TargetTransformInfo &TTI) {
+// Recognize a load from a "low bits mask" table, tbl[j] == (1 << j) - 1:
+//
+// static const uintN_t tbl[K] = { 0, 1, 3, 7, ... };
+// ... x & tbl[i] ...
+//
+// The loaded value equals the arithmetic mask (1 << i) - 1, so replace the load
+// with that expression and drop the table. On X86+BMI2 a surrounding `and` then
+// selects to a single `bzhi`; on other targets it is a shift and a decrement.
+//
+// Shares the load/GEP/offset match with the cttz and log2 recognizers above;
+// see tryToRecognizeTableBasedPatterns().
+static bool tryToRecognizeTableBasedLowBitsMask(LoadInst *LI, Type *AccessType,
+ GlobalVariable *GVTable,
+ Value *GepIdx,
+ const APInt &GEPScale,
+ const DataLayout &DL) {
+ // The value must be exactly the table element; refuse volatile/atomic loads.
+ if (!LI->isSimple())
+ return false;
+
+ // The table must be [K x AccessType] of integers; a narrower load would read
+ // only part of an element.
+ auto *ArrTy = dyn_cast<ArrayType>(GVTable->getValueType());
+ if (!ArrTy || ArrTy->getElementType() != AccessType ||
+ !AccessType->isIntegerTy())
+ return false;
+
+ unsigned EltBits = AccessType->getIntegerBitWidth();
+ uint64_t EltBytes = DL.getTypeAllocSize(AccessType).getFixedValue();
+ uint64_t K = ArrTy->getNumElements();
+
+ // Only fire for an integer width the target handles natively, so the emitted
+ // shift is a cheap instruction rather than a runtime libcall (e.g. __ashlti3
+ // for i128) -- which would be worse than the load and is unavailable in
+ // freestanding environments that do not link a runtime library.
+ if (!DL.isLegalInteger(EltBits))
----------------
topperc wrote:
Can this be fitsInLegalInteger?
https://github.com/llvm/llvm-project/pull/222509
More information about the llvm-commits
mailing list