1 //===- AggressiveInstCombine.cpp ------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the aggressive expression pattern combiner classes. 10 // Currently, it handles expression patterns for: 11 // * Truncate instruction 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 16 #include "AggressiveInstCombineInternal.h" 17 #include "llvm-c/Initialization.h" 18 #include "llvm-c/Transforms/AggressiveInstCombine.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BasicAliasAnalysis.h" 22 #include "llvm/Analysis/GlobalsModRef.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/LegacyPassManager.h" 29 #include "llvm/IR/PatternMatch.h" 30 #include "llvm/InitializePasses.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 34 using namespace llvm; 35 using namespace PatternMatch; 36 37 #define DEBUG_TYPE "aggressive-instcombine" 38 39 STATISTIC(NumAnyOrAllBitsSet, "Number of any/all-bits-set patterns folded"); 40 STATISTIC(NumGuardedRotates, 41 "Number of guarded rotates transformed into funnel shifts"); 42 STATISTIC(NumPopCountRecognized, "Number of popcount idioms recognized"); 43 44 namespace { 45 /// Contains expression pattern combiner logic. 46 /// This class provides both the logic to combine expression patterns and 47 /// combine them. It differs from InstCombiner class in that each pattern 48 /// combiner runs only once as opposed to InstCombine's multi-iteration, 49 /// which allows pattern combiner to have higher complexity than the O(1) 50 /// required by the instruction combiner. 51 class AggressiveInstCombinerLegacyPass : public FunctionPass { 52 public: 53 static char ID; // Pass identification, replacement for typeid 54 55 AggressiveInstCombinerLegacyPass() : FunctionPass(ID) { 56 initializeAggressiveInstCombinerLegacyPassPass( 57 *PassRegistry::getPassRegistry()); 58 } 59 60 void getAnalysisUsage(AnalysisUsage &AU) const override; 61 62 /// Run all expression pattern optimizations on the given /p F function. 63 /// 64 /// \param F function to optimize. 65 /// \returns true if the IR is changed. 66 bool runOnFunction(Function &F) override; 67 }; 68 } // namespace 69 70 /// Match a pattern for a bitwise rotate operation that partially guards 71 /// against undefined behavior by branching around the rotation when the shift 72 /// amount is 0. 73 static bool foldGuardedRotateToFunnelShift(Instruction &I) { 74 if (I.getOpcode() != Instruction::PHI || I.getNumOperands() != 2) 75 return false; 76 77 // As with the one-use checks below, this is not strictly necessary, but we 78 // are being cautious to avoid potential perf regressions on targets that 79 // do not actually have a rotate instruction (where the funnel shift would be 80 // expanded back into math/shift/logic ops). 81 if (!isPowerOf2_32(I.getType()->getScalarSizeInBits())) 82 return false; 83 84 // Match V to funnel shift left/right and capture the source operand and 85 // shift amount in X and Y. 86 auto matchRotate = [](Value *V, Value *&X, Value *&Y) { 87 Value *L0, *L1, *R0, *R1; 88 unsigned Width = V->getType()->getScalarSizeInBits(); 89 auto Sub = m_Sub(m_SpecificInt(Width), m_Value(R1)); 90 91 // rotate_left(X, Y) == (X << Y) | (X >> (Width - Y)) 92 auto RotL = m_OneUse( 93 m_c_Or(m_Shl(m_Value(L0), m_Value(L1)), m_LShr(m_Value(R0), Sub))); 94 if (RotL.match(V) && L0 == R0 && L1 == R1) { 95 X = L0; 96 Y = L1; 97 return Intrinsic::fshl; 98 } 99 100 // rotate_right(X, Y) == (X >> Y) | (X << (Width - Y)) 101 auto RotR = m_OneUse( 102 m_c_Or(m_LShr(m_Value(L0), m_Value(L1)), m_Shl(m_Value(R0), Sub))); 103 if (RotR.match(V) && L0 == R0 && L1 == R1) { 104 X = L0; 105 Y = L1; 106 return Intrinsic::fshr; 107 } 108 109 return Intrinsic::not_intrinsic; 110 }; 111 112 // One phi operand must be a rotate operation, and the other phi operand must 113 // be the source value of that rotate operation: 114 // phi [ rotate(RotSrc, RotAmt), RotBB ], [ RotSrc, GuardBB ] 115 PHINode &Phi = cast<PHINode>(I); 116 Value *P0 = Phi.getOperand(0), *P1 = Phi.getOperand(1); 117 Value *RotSrc, *RotAmt; 118 Intrinsic::ID IID = matchRotate(P0, RotSrc, RotAmt); 119 if (IID == Intrinsic::not_intrinsic || RotSrc != P1) { 120 IID = matchRotate(P1, RotSrc, RotAmt); 121 if (IID == Intrinsic::not_intrinsic || RotSrc != P0) 122 return false; 123 assert((IID == Intrinsic::fshl || IID == Intrinsic::fshr) && 124 "Pattern must match funnel shift left or right"); 125 } 126 127 // The incoming block with our source operand must be the "guard" block. 128 // That must contain a cmp+branch to avoid the rotate when the shift amount 129 // is equal to 0. The other incoming block is the block with the rotate. 130 BasicBlock *GuardBB = Phi.getIncomingBlock(RotSrc == P1); 131 BasicBlock *RotBB = Phi.getIncomingBlock(RotSrc != P1); 132 Instruction *TermI = GuardBB->getTerminator(); 133 ICmpInst::Predicate Pred; 134 BasicBlock *PhiBB = Phi.getParent(); 135 if (!match(TermI, m_Br(m_ICmp(Pred, m_Specific(RotAmt), m_ZeroInt()), 136 m_SpecificBB(PhiBB), m_SpecificBB(RotBB)))) 137 return false; 138 139 if (Pred != CmpInst::ICMP_EQ) 140 return false; 141 142 // We matched a variation of this IR pattern: 143 // GuardBB: 144 // %cmp = icmp eq i32 %RotAmt, 0 145 // br i1 %cmp, label %PhiBB, label %RotBB 146 // RotBB: 147 // %sub = sub i32 32, %RotAmt 148 // %shr = lshr i32 %X, %sub 149 // %shl = shl i32 %X, %RotAmt 150 // %rot = or i32 %shr, %shl 151 // br label %PhiBB 152 // PhiBB: 153 // %cond = phi i32 [ %rot, %RotBB ], [ %X, %GuardBB ] 154 // --> 155 // llvm.fshl.i32(i32 %X, i32 %RotAmt) 156 IRBuilder<> Builder(PhiBB, PhiBB->getFirstInsertionPt()); 157 Function *F = Intrinsic::getDeclaration(Phi.getModule(), IID, Phi.getType()); 158 Phi.replaceAllUsesWith(Builder.CreateCall(F, {RotSrc, RotSrc, RotAmt})); 159 ++NumGuardedRotates; 160 return true; 161 } 162 163 /// This is used by foldAnyOrAllBitsSet() to capture a source value (Root) and 164 /// the bit indexes (Mask) needed by a masked compare. If we're matching a chain 165 /// of 'and' ops, then we also need to capture the fact that we saw an 166 /// "and X, 1", so that's an extra return value for that case. 167 struct MaskOps { 168 Value *Root; 169 APInt Mask; 170 bool MatchAndChain; 171 bool FoundAnd1; 172 173 MaskOps(unsigned BitWidth, bool MatchAnds) 174 : Root(nullptr), Mask(APInt::getNullValue(BitWidth)), 175 MatchAndChain(MatchAnds), FoundAnd1(false) {} 176 }; 177 178 /// This is a recursive helper for foldAnyOrAllBitsSet() that walks through a 179 /// chain of 'and' or 'or' instructions looking for shift ops of a common source 180 /// value. Examples: 181 /// or (or (or X, (X >> 3)), (X >> 5)), (X >> 8) 182 /// returns { X, 0x129 } 183 /// and (and (X >> 1), 1), (X >> 4) 184 /// returns { X, 0x12 } 185 static bool matchAndOrChain(Value *V, MaskOps &MOps) { 186 Value *Op0, *Op1; 187 if (MOps.MatchAndChain) { 188 // Recurse through a chain of 'and' operands. This requires an extra check 189 // vs. the 'or' matcher: we must find an "and X, 1" instruction somewhere 190 // in the chain to know that all of the high bits are cleared. 191 if (match(V, m_And(m_Value(Op0), m_One()))) { 192 MOps.FoundAnd1 = true; 193 return matchAndOrChain(Op0, MOps); 194 } 195 if (match(V, m_And(m_Value(Op0), m_Value(Op1)))) 196 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps); 197 } else { 198 // Recurse through a chain of 'or' operands. 199 if (match(V, m_Or(m_Value(Op0), m_Value(Op1)))) 200 return matchAndOrChain(Op0, MOps) && matchAndOrChain(Op1, MOps); 201 } 202 203 // We need a shift-right or a bare value representing a compare of bit 0 of 204 // the original source operand. 205 Value *Candidate; 206 const APInt *BitIndex = nullptr; 207 if (!match(V, m_LShr(m_Value(Candidate), m_APInt(BitIndex)))) 208 Candidate = V; 209 210 // Initialize result source operand. 211 if (!MOps.Root) 212 MOps.Root = Candidate; 213 214 // The shift constant is out-of-range? This code hasn't been simplified. 215 if (BitIndex && BitIndex->uge(MOps.Mask.getBitWidth())) 216 return false; 217 218 // Fill in the mask bit derived from the shift constant. 219 MOps.Mask.setBit(BitIndex ? BitIndex->getZExtValue() : 0); 220 return MOps.Root == Candidate; 221 } 222 223 /// Match patterns that correspond to "any-bits-set" and "all-bits-set". 224 /// These will include a chain of 'or' or 'and'-shifted bits from a 225 /// common source value: 226 /// and (or (lshr X, C), ...), 1 --> (X & CMask) != 0 227 /// and (and (lshr X, C), ...), 1 --> (X & CMask) == CMask 228 /// Note: "any-bits-clear" and "all-bits-clear" are variations of these patterns 229 /// that differ only with a final 'not' of the result. We expect that final 230 /// 'not' to be folded with the compare that we create here (invert predicate). 231 static bool foldAnyOrAllBitsSet(Instruction &I) { 232 // The 'any-bits-set' ('or' chain) pattern is simpler to match because the 233 // final "and X, 1" instruction must be the final op in the sequence. 234 bool MatchAllBitsSet; 235 if (match(&I, m_c_And(m_OneUse(m_And(m_Value(), m_Value())), m_Value()))) 236 MatchAllBitsSet = true; 237 else if (match(&I, m_And(m_OneUse(m_Or(m_Value(), m_Value())), m_One()))) 238 MatchAllBitsSet = false; 239 else 240 return false; 241 242 MaskOps MOps(I.getType()->getScalarSizeInBits(), MatchAllBitsSet); 243 if (MatchAllBitsSet) { 244 if (!matchAndOrChain(cast<BinaryOperator>(&I), MOps) || !MOps.FoundAnd1) 245 return false; 246 } else { 247 if (!matchAndOrChain(cast<BinaryOperator>(&I)->getOperand(0), MOps)) 248 return false; 249 } 250 251 // The pattern was found. Create a masked compare that replaces all of the 252 // shift and logic ops. 253 IRBuilder<> Builder(&I); 254 Constant *Mask = ConstantInt::get(I.getType(), MOps.Mask); 255 Value *And = Builder.CreateAnd(MOps.Root, Mask); 256 Value *Cmp = MatchAllBitsSet ? Builder.CreateICmpEQ(And, Mask) 257 : Builder.CreateIsNotNull(And); 258 Value *Zext = Builder.CreateZExt(Cmp, I.getType()); 259 I.replaceAllUsesWith(Zext); 260 ++NumAnyOrAllBitsSet; 261 return true; 262 } 263 264 // Try to recognize below function as popcount intrinsic. 265 // This is the "best" algorithm from 266 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 267 // Also used in TargetLowering::expandCTPOP(). 268 // 269 // int popcount(unsigned int i) { 270 // i = i - ((i >> 1) & 0x55555555); 271 // i = (i & 0x33333333) + ((i >> 2) & 0x33333333); 272 // i = ((i + (i >> 4)) & 0x0F0F0F0F); 273 // return (i * 0x01010101) >> 24; 274 // } 275 static bool tryToRecognizePopCount(Instruction &I) { 276 if (I.getOpcode() != Instruction::LShr) 277 return false; 278 279 Type *Ty = I.getType(); 280 if (!Ty->isIntOrIntVectorTy()) 281 return false; 282 283 unsigned Len = Ty->getScalarSizeInBits(); 284 // FIXME: fix Len == 8 and other irregular type lengths. 285 if (!(Len <= 128 && Len > 8 && Len % 8 == 0)) 286 return false; 287 288 APInt Mask55 = APInt::getSplat(Len, APInt(8, 0x55)); 289 APInt Mask33 = APInt::getSplat(Len, APInt(8, 0x33)); 290 APInt Mask0F = APInt::getSplat(Len, APInt(8, 0x0F)); 291 APInt Mask01 = APInt::getSplat(Len, APInt(8, 0x01)); 292 APInt MaskShift = APInt(Len, Len - 8); 293 294 Value *Op0 = I.getOperand(0); 295 Value *Op1 = I.getOperand(1); 296 Value *MulOp0; 297 // Matching "(i * 0x01010101...) >> 24". 298 if ((match(Op0, m_Mul(m_Value(MulOp0), m_SpecificInt(Mask01)))) && 299 match(Op1, m_SpecificInt(MaskShift))) { 300 Value *ShiftOp0; 301 // Matching "((i + (i >> 4)) & 0x0F0F0F0F...)". 302 if (match(MulOp0, m_And(m_c_Add(m_LShr(m_Value(ShiftOp0), m_SpecificInt(4)), 303 m_Deferred(ShiftOp0)), 304 m_SpecificInt(Mask0F)))) { 305 Value *AndOp0; 306 // Matching "(i & 0x33333333...) + ((i >> 2) & 0x33333333...)". 307 if (match(ShiftOp0, 308 m_c_Add(m_And(m_Value(AndOp0), m_SpecificInt(Mask33)), 309 m_And(m_LShr(m_Deferred(AndOp0), m_SpecificInt(2)), 310 m_SpecificInt(Mask33))))) { 311 Value *Root, *SubOp1; 312 // Matching "i - ((i >> 1) & 0x55555555...)". 313 if (match(AndOp0, m_Sub(m_Value(Root), m_Value(SubOp1))) && 314 match(SubOp1, m_And(m_LShr(m_Specific(Root), m_SpecificInt(1)), 315 m_SpecificInt(Mask55)))) { 316 LLVM_DEBUG(dbgs() << "Recognized popcount intrinsic\n"); 317 IRBuilder<> Builder(&I); 318 Function *Func = Intrinsic::getDeclaration( 319 I.getModule(), Intrinsic::ctpop, I.getType()); 320 I.replaceAllUsesWith(Builder.CreateCall(Func, {Root})); 321 ++NumPopCountRecognized; 322 return true; 323 } 324 } 325 } 326 } 327 328 return false; 329 } 330 331 /// This is the entry point for folds that could be implemented in regular 332 /// InstCombine, but they are separated because they are not expected to 333 /// occur frequently and/or have more than a constant-length pattern match. 334 static bool foldUnusualPatterns(Function &F, DominatorTree &DT) { 335 bool MadeChange = false; 336 for (BasicBlock &BB : F) { 337 // Ignore unreachable basic blocks. 338 if (!DT.isReachableFromEntry(&BB)) 339 continue; 340 // Do not delete instructions under here and invalidate the iterator. 341 // Walk the block backwards for efficiency. We're matching a chain of 342 // use->defs, so we're more likely to succeed by starting from the bottom. 343 // Also, we want to avoid matching partial patterns. 344 // TODO: It would be more efficient if we removed dead instructions 345 // iteratively in this loop rather than waiting until the end. 346 for (Instruction &I : make_range(BB.rbegin(), BB.rend())) { 347 MadeChange |= foldAnyOrAllBitsSet(I); 348 MadeChange |= foldGuardedRotateToFunnelShift(I); 349 MadeChange |= tryToRecognizePopCount(I); 350 } 351 } 352 353 // We're done with transforms, so remove dead instructions. 354 if (MadeChange) 355 for (BasicBlock &BB : F) 356 SimplifyInstructionsInBlock(&BB); 357 358 return MadeChange; 359 } 360 361 /// This is the entry point for all transforms. Pass manager differences are 362 /// handled in the callers of this function. 363 static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT) { 364 bool MadeChange = false; 365 const DataLayout &DL = F.getParent()->getDataLayout(); 366 TruncInstCombine TIC(TLI, DL, DT); 367 MadeChange |= TIC.run(F); 368 MadeChange |= foldUnusualPatterns(F, DT); 369 return MadeChange; 370 } 371 372 void AggressiveInstCombinerLegacyPass::getAnalysisUsage( 373 AnalysisUsage &AU) const { 374 AU.setPreservesCFG(); 375 AU.addRequired<DominatorTreeWrapperPass>(); 376 AU.addRequired<TargetLibraryInfoWrapperPass>(); 377 AU.addPreserved<AAResultsWrapperPass>(); 378 AU.addPreserved<BasicAAWrapperPass>(); 379 AU.addPreserved<DominatorTreeWrapperPass>(); 380 AU.addPreserved<GlobalsAAWrapperPass>(); 381 } 382 383 bool AggressiveInstCombinerLegacyPass::runOnFunction(Function &F) { 384 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 385 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 386 return runImpl(F, TLI, DT); 387 } 388 389 PreservedAnalyses AggressiveInstCombinePass::run(Function &F, 390 FunctionAnalysisManager &AM) { 391 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 392 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 393 if (!runImpl(F, TLI, DT)) { 394 // No changes, all analyses are preserved. 395 return PreservedAnalyses::all(); 396 } 397 // Mark all the analyses that instcombine updates as preserved. 398 PreservedAnalyses PA; 399 PA.preserveSet<CFGAnalyses>(); 400 PA.preserve<AAManager>(); 401 PA.preserve<GlobalsAA>(); 402 return PA; 403 } 404 405 char AggressiveInstCombinerLegacyPass::ID = 0; 406 INITIALIZE_PASS_BEGIN(AggressiveInstCombinerLegacyPass, 407 "aggressive-instcombine", 408 "Combine pattern based expressions", false, false) 409 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 410 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 411 INITIALIZE_PASS_END(AggressiveInstCombinerLegacyPass, "aggressive-instcombine", 412 "Combine pattern based expressions", false, false) 413 414 // Initialization Routines 415 void llvm::initializeAggressiveInstCombine(PassRegistry &Registry) { 416 initializeAggressiveInstCombinerLegacyPassPass(Registry); 417 } 418 419 void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R) { 420 initializeAggressiveInstCombinerLegacyPassPass(*unwrap(R)); 421 } 422 423 FunctionPass *llvm::createAggressiveInstCombinerPass() { 424 return new AggressiveInstCombinerLegacyPass(); 425 } 426 427 void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM) { 428 unwrap(PM)->add(createAggressiveInstCombinerPass()); 429 } 430