AggressiveInstCombine.cpp 18 KB

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