Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 1 | //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass implements an idiom recognizer that transforms simple loops into a |
| 11 | // non-loop form. In cases that this kicks in, it can be a significant |
| 12 | // performance win. |
| 13 | // |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 14 | // If compiling for code size we avoid idiom recognition if the resulting |
| 15 | // code could be larger than the code for the original loop. One way this could |
| 16 | // happen is if the loop is not removable after idiom recognition due to the |
| 17 | // presence of non-idiom instructions. The initial implementation of the |
| 18 | // heuristics applies to idioms in multi-block loops. |
| 19 | // |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 20 | //===----------------------------------------------------------------------===// |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 21 | // |
| 22 | // TODO List: |
| 23 | // |
| 24 | // Future loop memory idioms to recognize: |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 25 | // memcmp, memmove, strlen, etc. |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 26 | // Future floating point idioms to recognize in -ffast-math mode: |
| 27 | // fpowi |
| 28 | // Future integer operation idioms to recognize: |
| 29 | // ctpop, ctlz, cttz |
| 30 | // |
| 31 | // Beware that isel's default lowering for ctpop is highly inefficient for |
| 32 | // i64 and larger types when i64 is legal and the value has few bits set. It |
| 33 | // would be good to enhance isel to emit a loop for ctpop in this case. |
| 34 | // |
Chris Lattner | 02a9776 | 2011-01-03 01:10:08 +0000 | [diff] [blame] | 35 | // This could recognize common matrix multiplies and dot product idioms and |
Chris Lattner | 8fac5db | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 36 | // replace them with calls to BLAS (if linked in??). |
| 37 | // |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 38 | //===----------------------------------------------------------------------===// |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 39 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 41 | #include "llvm/ADT/MapVector.h" |
| 42 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 43 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 44 | #include "llvm/Analysis/AliasAnalysis.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
| 46 | #include "llvm/Analysis/GlobalsModRef.h" |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/LoopPass.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
Chad Rosier | a15b4b6 | 2015-11-23 21:09:13 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 53 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 54 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 55 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 56 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 57 | #include "llvm/IR/IRBuilder.h" |
| 58 | #include "llvm/IR/IntrinsicInst.h" |
| 59 | #include "llvm/IR/Module.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 60 | #include "llvm/Support/Debug.h" |
| 61 | #include "llvm/Support/raw_ostream.h" |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 62 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 3bab7e1 | 2017-01-11 09:43:56 +0000 | [diff] [blame] | 63 | #include "llvm/Transforms/Scalar/LoopPassManager.h" |
Ahmed Bougacha | ace97c1 | 2016-04-27 19:04:50 +0000 | [diff] [blame] | 64 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 65 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 66 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 67 | using namespace llvm; |
| 68 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 69 | #define DEBUG_TYPE "loop-idiom" |
| 70 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 71 | STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); |
| 72 | STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 73 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 74 | static cl::opt<bool> UseLIRCodeSizeHeurs( |
| 75 | "use-lir-code-size-heurs", |
| 76 | cl::desc("Use loop idiom recognition code size heuristics when compiling" |
| 77 | "with -Os/-Oz"), |
| 78 | cl::init(true), cl::Hidden); |
| 79 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 80 | namespace { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 81 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 82 | class LoopIdiomRecognize { |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 83 | Loop *CurLoop; |
Chandler Carruth | bf143e2 | 2015-08-14 00:21:10 +0000 | [diff] [blame] | 84 | AliasAnalysis *AA; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 85 | DominatorTree *DT; |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 86 | LoopInfo *LI; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 87 | ScalarEvolution *SE; |
| 88 | TargetLibraryInfo *TLI; |
| 89 | const TargetTransformInfo *TTI; |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 90 | const DataLayout *DL; |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 91 | bool ApplyCodeSizeHeuristics; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 92 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 93 | public: |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 94 | explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT, |
| 95 | LoopInfo *LI, ScalarEvolution *SE, |
| 96 | TargetLibraryInfo *TLI, |
| 97 | const TargetTransformInfo *TTI, |
| 98 | const DataLayout *DL) |
| 99 | : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), |
| 100 | DL(DL) {} |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 101 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 102 | bool runOnLoop(Loop *L); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 103 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 104 | private: |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 105 | typedef SmallVector<StoreInst *, 8> StoreList; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 106 | typedef MapVector<Value *, StoreList> StoreListMap; |
| 107 | StoreListMap StoreRefsForMemset; |
| 108 | StoreListMap StoreRefsForMemsetPattern; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 109 | StoreList StoreRefsForMemcpy; |
| 110 | bool HasMemset; |
| 111 | bool HasMemsetPattern; |
| 112 | bool HasMemcpy; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 113 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 114 | /// \name Countable Loop Idiom Handling |
| 115 | /// @{ |
| 116 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 117 | bool runOnCountableLoop(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 118 | bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 119 | SmallVectorImpl<BasicBlock *> &ExitBlocks); |
| 120 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 121 | void collectStores(BasicBlock *BB); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 122 | bool isLegalStore(StoreInst *SI, bool &ForMemset, bool &ForMemsetPattern, |
| 123 | bool &ForMemcpy); |
| 124 | bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount, |
| 125 | bool ForMemset); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 126 | bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); |
| 127 | |
| 128 | bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 129 | unsigned StoreAlignment, Value *StoredVal, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 130 | Instruction *TheStore, |
| 131 | SmallPtrSetImpl<Instruction *> &Stores, |
| 132 | const SCEVAddRecExpr *Ev, const SCEV *BECount, |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 133 | bool NegStride, bool IsLoopMemset = false); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 134 | bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount); |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 135 | bool avoidLIRForMultiBlockLoop(bool IsMemset = false, |
| 136 | bool IsLoopMemset = false); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 137 | |
| 138 | /// @} |
| 139 | /// \name Noncountable Loop Idiom Handling |
| 140 | /// @{ |
| 141 | |
| 142 | bool runOnNoncountableLoop(); |
| 143 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 144 | bool recognizePopcount(); |
| 145 | void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst, |
| 146 | PHINode *CntPhi, Value *Var); |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 147 | bool recognizeAndInsertCTLZ(); |
| 148 | void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst, |
| 149 | PHINode *CntPhi, Value *Var, const DebugLoc DL, |
| 150 | bool ZeroCheck, bool IsCntPhiUsedOutsideLoop); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 151 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 152 | /// @} |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 153 | }; |
| 154 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 155 | class LoopIdiomRecognizeLegacyPass : public LoopPass { |
| 156 | public: |
| 157 | static char ID; |
| 158 | explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) { |
| 159 | initializeLoopIdiomRecognizeLegacyPassPass( |
| 160 | *PassRegistry::getPassRegistry()); |
| 161 | } |
| 162 | |
| 163 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
| 164 | if (skipLoop(L)) |
| 165 | return false; |
| 166 | |
| 167 | AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 168 | DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 169 | LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 170 | ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
| 171 | TargetLibraryInfo *TLI = |
| 172 | &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 173 | const TargetTransformInfo *TTI = |
| 174 | &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( |
| 175 | *L->getHeader()->getParent()); |
| 176 | const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout(); |
| 177 | |
| 178 | LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL); |
| 179 | return LIR.runOnLoop(L); |
| 180 | } |
| 181 | |
| 182 | /// This transformation requires natural loop information & requires that |
| 183 | /// loop preheaders be inserted into the CFG. |
| 184 | /// |
| 185 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 186 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 187 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
| 188 | getLoopAnalysisUsage(AU); |
| 189 | } |
| 190 | }; |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 191 | } // End anonymous namespace. |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 192 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 193 | PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM, |
| 194 | LoopStandardAnalysisResults &AR, |
| 195 | LPMUpdater &) { |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 196 | const auto *DL = &L.getHeader()->getModule()->getDataLayout(); |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 197 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 198 | LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL); |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 199 | if (!LIR.runOnLoop(&L)) |
| 200 | return PreservedAnalyses::all(); |
| 201 | |
| 202 | return getLoopPassPreservedAnalyses(); |
| 203 | } |
| 204 | |
| 205 | char LoopIdiomRecognizeLegacyPass::ID = 0; |
| 206 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", |
| 207 | "Recognize loop idioms", false, false) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 208 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 209 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 210 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 211 | INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom", |
| 212 | "Recognize loop idioms", false, false) |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 213 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 214 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); } |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 215 | |
David Majnemer | c5601df | 2016-06-20 16:03:25 +0000 | [diff] [blame] | 216 | static void deleteDeadInstruction(Instruction *I) { |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 217 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
| 218 | I->eraseFromParent(); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 219 | } |
| 220 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 221 | //===----------------------------------------------------------------------===// |
| 222 | // |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 223 | // Implementation of LoopIdiomRecognize |
| 224 | // |
| 225 | //===----------------------------------------------------------------------===// |
| 226 | |
Dehao Chen | b9f8e29 | 2016-07-12 18:45:51 +0000 | [diff] [blame] | 227 | bool LoopIdiomRecognize::runOnLoop(Loop *L) { |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 228 | CurLoop = L; |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 229 | // If the loop could not be converted to canonical form, it must have an |
| 230 | // indirectbr in it, just give up. |
| 231 | if (!L->getLoopPreheader()) |
| 232 | return false; |
| 233 | |
| 234 | // Disable loop idiom recognition if the function's name is a common idiom. |
| 235 | StringRef Name = L->getHeader()->getParent()->getName(); |
| 236 | if (Name == "memset" || Name == "memcpy") |
| 237 | return false; |
| 238 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 239 | // Determine if code size heuristics need to be applied. |
| 240 | ApplyCodeSizeHeuristics = |
| 241 | L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs; |
| 242 | |
David L. Jones | d21529f | 2017-01-23 23:16:46 +0000 | [diff] [blame] | 243 | HasMemset = TLI->has(LibFunc_memset); |
| 244 | HasMemsetPattern = TLI->has(LibFunc_memset_pattern16); |
| 245 | HasMemcpy = TLI->has(LibFunc_memcpy); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 246 | |
| 247 | if (HasMemset || HasMemsetPattern || HasMemcpy) |
| 248 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 249 | return runOnCountableLoop(); |
Chandler Carruth | dc29832 | 2015-08-13 01:03:26 +0000 | [diff] [blame] | 250 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 251 | return runOnNoncountableLoop(); |
| 252 | } |
| 253 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 254 | bool LoopIdiomRecognize::runOnCountableLoop() { |
| 255 | const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); |
Davide Italiano | 8ed0446 | 2015-05-11 21:02:34 +0000 | [diff] [blame] | 256 | assert(!isa<SCEVCouldNotCompute>(BECount) && |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 257 | "runOnCountableLoop() called on a loop without a predictable" |
| 258 | "backedge-taken count"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 259 | |
| 260 | // If this loop executes exactly one time, then it should be peeled, not |
| 261 | // optimized by this pass. |
| 262 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 263 | if (BECst->getAPInt() == 0) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 264 | return false; |
| 265 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 266 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 267 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 268 | |
| 269 | DEBUG(dbgs() << "loop-idiom Scanning: F[" |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 270 | << CurLoop->getHeader()->getParent()->getName() << "] Loop %" |
| 271 | << CurLoop->getHeader()->getName() << "\n"); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 272 | |
| 273 | bool MadeChange = false; |
Haicheng Wu | a95cd126 | 2016-07-06 21:05:40 +0000 | [diff] [blame] | 274 | |
| 275 | // The following transforms hoist stores/memsets into the loop pre-header. |
| 276 | // Give up if the loop has instructions may throw. |
| 277 | LoopSafetyInfo SafetyInfo; |
| 278 | computeLoopSafetyInfo(&SafetyInfo, CurLoop); |
Evgeniy Stepanov | 58ccc09 | 2017-04-24 18:25:07 +0000 | [diff] [blame] | 279 | if (SafetyInfo.MayThrow) |
Haicheng Wu | a95cd126 | 2016-07-06 21:05:40 +0000 | [diff] [blame] | 280 | return MadeChange; |
| 281 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 282 | // Scan all the blocks in the loop that are not in subloops. |
Davide Italiano | 95a77e8 | 2015-05-14 21:52:12 +0000 | [diff] [blame] | 283 | for (auto *BB : CurLoop->getBlocks()) { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 284 | // Ignore blocks in subloops. |
Chandler Carruth | 18c2669 | 2015-08-13 09:27:01 +0000 | [diff] [blame] | 285 | if (LI->getLoopFor(BB) != CurLoop) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 286 | continue; |
| 287 | |
Davide Italiano | 80625af | 2015-05-13 19:51:21 +0000 | [diff] [blame] | 288 | MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 289 | } |
| 290 | return MadeChange; |
| 291 | } |
| 292 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 293 | static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) { |
| 294 | uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); |
| 295 | assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) && |
| 296 | "Don't overflow unsigned."); |
| 297 | return (unsigned)SizeInBits >> 3; |
| 298 | } |
| 299 | |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 300 | static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) { |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 301 | const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 302 | return ConstStride->getAPInt(); |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 303 | } |
| 304 | |
Chad Rosier | 94274fb | 2015-12-21 14:49:32 +0000 | [diff] [blame] | 305 | /// getMemSetPatternValue - If a strided store of the specified value is safe to |
| 306 | /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should |
| 307 | /// be passed in. Otherwise, return null. |
| 308 | /// |
| 309 | /// Note that we don't ever attempt to use memset_pattern8 or 4, because these |
| 310 | /// just replicate their input array and then pass on to memset_pattern16. |
| 311 | static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) { |
| 312 | // If the value isn't a constant, we can't promote it to being in a constant |
| 313 | // array. We could theoretically do a store to an alloca or something, but |
| 314 | // that doesn't seem worthwhile. |
| 315 | Constant *C = dyn_cast<Constant>(V); |
| 316 | if (!C) |
| 317 | return nullptr; |
| 318 | |
| 319 | // Only handle simple values that are a power of two bytes in size. |
| 320 | uint64_t Size = DL->getTypeSizeInBits(V->getType()); |
| 321 | if (Size == 0 || (Size & 7) || (Size & (Size - 1))) |
| 322 | return nullptr; |
| 323 | |
| 324 | // Don't care enough about darwin/ppc to implement this. |
| 325 | if (DL->isBigEndian()) |
| 326 | return nullptr; |
| 327 | |
| 328 | // Convert to size in bytes. |
| 329 | Size /= 8; |
| 330 | |
| 331 | // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see |
| 332 | // if the top and bottom are the same (e.g. for vectors and large integers). |
| 333 | if (Size > 16) |
| 334 | return nullptr; |
| 335 | |
| 336 | // If the constant is exactly 16 bytes, just use it. |
| 337 | if (Size == 16) |
| 338 | return C; |
| 339 | |
| 340 | // Otherwise, we'll use an array of the constants. |
| 341 | unsigned ArraySize = 16 / Size; |
| 342 | ArrayType *AT = ArrayType::get(V->getType(), ArraySize); |
| 343 | return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C)); |
| 344 | } |
| 345 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 346 | bool LoopIdiomRecognize::isLegalStore(StoreInst *SI, bool &ForMemset, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 347 | bool &ForMemsetPattern, bool &ForMemcpy) { |
Chad Rosier | 869962f | 2015-12-01 14:26:35 +0000 | [diff] [blame] | 348 | // Don't touch volatile stores. |
| 349 | if (!SI->isSimple()) |
| 350 | return false; |
| 351 | |
Sanjoy Das | 206f65c | 2017-04-24 20:12:10 +0000 | [diff] [blame] | 352 | // Don't convert stores of non-integral pointer types to memsets (which stores |
| 353 | // integers). |
| 354 | if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType())) |
| 355 | return false; |
| 356 | |
Haicheng Wu | 57e1a3e | 2016-02-17 21:00:06 +0000 | [diff] [blame] | 357 | // Avoid merging nontemporal stores. |
| 358 | if (SI->getMetadata(LLVMContext::MD_nontemporal)) |
| 359 | return false; |
| 360 | |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 361 | Value *StoredVal = SI->getValueOperand(); |
| 362 | Value *StorePtr = SI->getPointerOperand(); |
| 363 | |
| 364 | // Reject stores that are so large that they overflow an unsigned. |
| 365 | uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); |
| 366 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
| 367 | return false; |
| 368 | |
| 369 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 370 | // loop, which indicates a strided store. If we have something else, it's a |
| 371 | // random store we can't handle. |
| 372 | const SCEVAddRecExpr *StoreEv = |
| 373 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
| 374 | if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) |
| 375 | return false; |
| 376 | |
| 377 | // Check to see if we have a constant stride. |
| 378 | if (!isa<SCEVConstant>(StoreEv->getOperand(1))) |
| 379 | return false; |
| 380 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 381 | // See if the store can be turned into a memset. |
| 382 | |
| 383 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 384 | // turned into a memset of i8 -1, assuming that all the consecutive bytes |
| 385 | // are stored. A store of i32 0x01020304 can never be turned into a memset, |
| 386 | // but it can be turned into memset_pattern if the target supports it. |
| 387 | Value *SplatValue = isBytewiseValue(StoredVal); |
| 388 | Constant *PatternValue = nullptr; |
| 389 | |
| 390 | // If we're allowed to form a memset, and the stored value would be |
| 391 | // acceptable for memset, use it. |
| 392 | if (HasMemset && SplatValue && |
| 393 | // Verify that the stored value is loop invariant. If not, we can't |
| 394 | // promote the memset. |
| 395 | CurLoop->isLoopInvariant(SplatValue)) { |
| 396 | // It looks like we can use SplatValue. |
| 397 | ForMemset = true; |
| 398 | return true; |
| 399 | } else if (HasMemsetPattern && |
| 400 | // Don't create memset_pattern16s with address spaces. |
| 401 | StorePtr->getType()->getPointerAddressSpace() == 0 && |
| 402 | (PatternValue = getMemSetPatternValue(StoredVal, DL))) { |
| 403 | // It looks like we can use PatternValue! |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 404 | ForMemsetPattern = true; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 405 | return true; |
| 406 | } |
| 407 | |
| 408 | // Otherwise, see if the store can be turned into a memcpy. |
| 409 | if (HasMemcpy) { |
| 410 | // Check to see if the stride matches the size of the store. If so, then we |
| 411 | // know that every byte is touched in the loop. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 412 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 413 | unsigned StoreSize = getStoreSizeInBytes(SI, DL); |
| 414 | if (StoreSize != Stride && StoreSize != -Stride) |
| 415 | return false; |
| 416 | |
| 417 | // The store must be feeding a non-volatile load. |
| 418 | LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand()); |
| 419 | if (!LI || !LI->isSimple()) |
| 420 | return false; |
| 421 | |
| 422 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 423 | // loop, which indicates a strided load. If we have something else, it's a |
| 424 | // random load we can't handle. |
| 425 | const SCEVAddRecExpr *LoadEv = |
| 426 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
| 427 | if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) |
| 428 | return false; |
| 429 | |
| 430 | // The store and load must share the same stride. |
| 431 | if (StoreEv->getOperand(1) != LoadEv->getOperand(1)) |
| 432 | return false; |
| 433 | |
| 434 | // Success. This store can be converted into a memcpy. |
| 435 | ForMemcpy = true; |
| 436 | return true; |
| 437 | } |
| 438 | // This store can't be transformed into a memset/memcpy. |
| 439 | return false; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 440 | } |
| 441 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 442 | void LoopIdiomRecognize::collectStores(BasicBlock *BB) { |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 443 | StoreRefsForMemset.clear(); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 444 | StoreRefsForMemsetPattern.clear(); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 445 | StoreRefsForMemcpy.clear(); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 446 | for (Instruction &I : *BB) { |
| 447 | StoreInst *SI = dyn_cast<StoreInst>(&I); |
| 448 | if (!SI) |
| 449 | continue; |
| 450 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 451 | bool ForMemset = false; |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 452 | bool ForMemsetPattern = false; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 453 | bool ForMemcpy = false; |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 454 | // Make sure this is a strided store with a constant stride. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 455 | if (!isLegalStore(SI, ForMemset, ForMemsetPattern, ForMemcpy)) |
Chad Rosier | a548fe5 | 2015-11-12 19:09:16 +0000 | [diff] [blame] | 456 | continue; |
| 457 | |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 458 | // Save the store locations. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 459 | if (ForMemset) { |
| 460 | // Find the base pointer. |
| 461 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 462 | StoreRefsForMemset[Ptr].push_back(SI); |
| 463 | } else if (ForMemsetPattern) { |
| 464 | // Find the base pointer. |
| 465 | Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL); |
| 466 | StoreRefsForMemsetPattern[Ptr].push_back(SI); |
| 467 | } else if (ForMemcpy) |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 468 | StoreRefsForMemcpy.push_back(SI); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 469 | } |
| 470 | } |
| 471 | |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 472 | /// runOnLoopBlock - Process the specified block, which lives in a counted loop |
| 473 | /// with the specified backedge count. This block is known to be in the current |
| 474 | /// loop and not in any subloops. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 475 | bool LoopIdiomRecognize::runOnLoopBlock( |
| 476 | BasicBlock *BB, const SCEV *BECount, |
| 477 | SmallVectorImpl<BasicBlock *> &ExitBlocks) { |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 478 | // We can only promote stores in this block if they are unconditionally |
| 479 | // executed in the loop. For a block to be unconditionally executed, it has |
| 480 | // to dominate all the exit blocks of the loop. Verify this now. |
| 481 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 482 | if (!DT->dominates(BB, ExitBlocks[i])) |
| 483 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 484 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 485 | bool MadeChange = false; |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 486 | // Look for store instructions, which may be optimized to memset/memcpy. |
| 487 | collectStores(BB); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 488 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 489 | // Look for a single store or sets of stores with a common base, which can be |
| 490 | // optimized into a memset (memset_pattern). The latter most commonly happens |
| 491 | // with structs and handunrolled loops. |
| 492 | for (auto &SL : StoreRefsForMemset) |
| 493 | MadeChange |= processLoopStores(SL.second, BECount, true); |
| 494 | |
| 495 | for (auto &SL : StoreRefsForMemsetPattern) |
| 496 | MadeChange |= processLoopStores(SL.second, BECount, false); |
Chad Rosier | cc9030b | 2015-11-11 23:00:59 +0000 | [diff] [blame] | 497 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 498 | // Optimize the store into a memcpy, if it feeds an similarly strided load. |
| 499 | for (auto &SI : StoreRefsForMemcpy) |
| 500 | MadeChange |= processLoopStoreOfLoopLoad(SI, BECount); |
| 501 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 502 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 503 | Instruction *Inst = &*I++; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 504 | // Look for memset instructions, which may be optimized to a larger memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 505 | if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 506 | WeakTrackingVH InstPtr(&*I); |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 507 | if (!processLoopMemSet(MSI, BECount)) |
| 508 | continue; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 509 | MadeChange = true; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 510 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 511 | // If processing the memset invalidated our iterator, start over from the |
| 512 | // top of the block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 513 | if (!InstPtr) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 514 | I = BB->begin(); |
| 515 | continue; |
| 516 | } |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 517 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 518 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 519 | return MadeChange; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 520 | } |
| 521 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 522 | /// processLoopStores - See if this store(s) can be promoted to a memset. |
| 523 | bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL, |
| 524 | const SCEV *BECount, |
| 525 | bool ForMemset) { |
| 526 | // Try to find consecutive stores that can be transformed into memsets. |
| 527 | SetVector<StoreInst *> Heads, Tails; |
| 528 | SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 529 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 530 | // Do a quadratic search on all of the given stores and find |
| 531 | // all of the pairs of stores that follow each other. |
| 532 | SmallVector<unsigned, 16> IndexQueue; |
| 533 | for (unsigned i = 0, e = SL.size(); i < e; ++i) { |
| 534 | assert(SL[i]->isSimple() && "Expected only non-volatile stores."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 535 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 536 | Value *FirstStoredVal = SL[i]->getValueOperand(); |
| 537 | Value *FirstStorePtr = SL[i]->getPointerOperand(); |
| 538 | const SCEVAddRecExpr *FirstStoreEv = |
| 539 | cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 540 | APInt FirstStride = getStoreStride(FirstStoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 541 | unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 542 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 543 | // See if we can optimize just this store in isolation. |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 544 | if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) { |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 545 | Heads.insert(SL[i]); |
| 546 | continue; |
| 547 | } |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 548 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 549 | Value *FirstSplatValue = nullptr; |
| 550 | Constant *FirstPatternValue = nullptr; |
| 551 | |
| 552 | if (ForMemset) |
| 553 | FirstSplatValue = isBytewiseValue(FirstStoredVal); |
| 554 | else |
| 555 | FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL); |
| 556 | |
| 557 | assert((FirstSplatValue || FirstPatternValue) && |
| 558 | "Expected either splat value or pattern value."); |
| 559 | |
| 560 | IndexQueue.clear(); |
| 561 | // If a store has multiple consecutive store candidates, search Stores |
| 562 | // array according to the sequence: from i+1 to e, then from i-1 to 0. |
| 563 | // This is because usually pairing with immediate succeeding or preceding |
| 564 | // candidate create the best chance to find memset opportunity. |
| 565 | unsigned j = 0; |
| 566 | for (j = i + 1; j < e; ++j) |
| 567 | IndexQueue.push_back(j); |
| 568 | for (j = i; j > 0; --j) |
| 569 | IndexQueue.push_back(j - 1); |
| 570 | |
| 571 | for (auto &k : IndexQueue) { |
| 572 | assert(SL[k]->isSimple() && "Expected only non-volatile stores."); |
| 573 | Value *SecondStorePtr = SL[k]->getPointerOperand(); |
| 574 | const SCEVAddRecExpr *SecondStoreEv = |
| 575 | cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 576 | APInt SecondStride = getStoreStride(SecondStoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 577 | |
| 578 | if (FirstStride != SecondStride) |
| 579 | continue; |
| 580 | |
| 581 | Value *SecondStoredVal = SL[k]->getValueOperand(); |
| 582 | Value *SecondSplatValue = nullptr; |
| 583 | Constant *SecondPatternValue = nullptr; |
| 584 | |
| 585 | if (ForMemset) |
| 586 | SecondSplatValue = isBytewiseValue(SecondStoredVal); |
| 587 | else |
| 588 | SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL); |
| 589 | |
| 590 | assert((SecondSplatValue || SecondPatternValue) && |
| 591 | "Expected either splat value or pattern value."); |
| 592 | |
| 593 | if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) { |
| 594 | if (ForMemset) { |
| 595 | if (FirstSplatValue != SecondSplatValue) |
| 596 | continue; |
| 597 | } else { |
| 598 | if (FirstPatternValue != SecondPatternValue) |
| 599 | continue; |
| 600 | } |
| 601 | Tails.insert(SL[k]); |
| 602 | Heads.insert(SL[i]); |
| 603 | ConsecutiveChain[SL[i]] = SL[k]; |
| 604 | break; |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | // We may run into multiple chains that merge into a single chain. We mark the |
| 610 | // stores that we transformed so that we don't visit the same store twice. |
| 611 | SmallPtrSet<Value *, 16> TransformedStores; |
| 612 | bool Changed = false; |
| 613 | |
| 614 | // For stores that start but don't end a link in the chain: |
| 615 | for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end(); |
| 616 | it != e; ++it) { |
| 617 | if (Tails.count(*it)) |
| 618 | continue; |
| 619 | |
| 620 | // We found a store instr that starts a chain. Now follow the chain and try |
| 621 | // to transform it. |
| 622 | SmallPtrSet<Instruction *, 8> AdjacentStores; |
| 623 | StoreInst *I = *it; |
| 624 | |
| 625 | StoreInst *HeadStore = I; |
| 626 | unsigned StoreSize = 0; |
| 627 | |
| 628 | // Collect the chain into a list. |
| 629 | while (Tails.count(I) || Heads.count(I)) { |
| 630 | if (TransformedStores.count(I)) |
| 631 | break; |
| 632 | AdjacentStores.insert(I); |
| 633 | |
| 634 | StoreSize += getStoreSizeInBytes(I, DL); |
| 635 | // Move to the next value in the chain. |
| 636 | I = ConsecutiveChain[I]; |
| 637 | } |
| 638 | |
| 639 | Value *StoredVal = HeadStore->getValueOperand(); |
| 640 | Value *StorePtr = HeadStore->getPointerOperand(); |
| 641 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 642 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 643 | |
| 644 | // Check to see if the stride matches the size of the stores. If so, then |
| 645 | // we know that every byte is touched in the loop. |
| 646 | if (StoreSize != Stride && StoreSize != -Stride) |
| 647 | continue; |
| 648 | |
| 649 | bool NegStride = StoreSize == -Stride; |
| 650 | |
| 651 | if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(), |
| 652 | StoredVal, HeadStore, AdjacentStores, StoreEv, |
| 653 | BECount, NegStride)) { |
| 654 | TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end()); |
| 655 | Changed = true; |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | return Changed; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 660 | } |
| 661 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 662 | /// processLoopMemSet - See if this memset can be promoted to a large memset. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 663 | bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI, |
| 664 | const SCEV *BECount) { |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 665 | // We can only handle non-volatile memsets with a constant size. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 666 | if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) |
| 667 | return false; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 668 | |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 669 | // If we're not allowed to hack on memset, we fail. |
Ahmed Bougacha | 7f97193 | 2016-04-27 19:04:46 +0000 | [diff] [blame] | 670 | if (!HasMemset) |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 671 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 672 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 673 | Value *Pointer = MSI->getDest(); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 674 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 675 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 676 | // loop, which indicates a strided store. If we have something else, it's a |
| 677 | // random store we can't handle. |
| 678 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 679 | if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 680 | return false; |
| 681 | |
| 682 | // Reject memsets that are so large that they overflow an unsigned. |
| 683 | uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 684 | if ((SizeInBytes >> 32) != 0) |
| 685 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 686 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 687 | // Check to see if the stride matches the size of the memset. If so, then we |
| 688 | // know that every byte is touched in the loop. |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 689 | const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
| 690 | if (!ConstStride) |
| 691 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 692 | |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 693 | APInt Stride = ConstStride->getAPInt(); |
| 694 | if (SizeInBytes != Stride && SizeInBytes != -Stride) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 695 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 696 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 697 | // Verify that the memset value is loop invariant. If not, we can't promote |
| 698 | // the memset. |
| 699 | Value *SplatValue = MSI->getValue(); |
| 700 | if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue)) |
| 701 | return false; |
| 702 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 703 | SmallPtrSet<Instruction *, 1> MSIs; |
| 704 | MSIs.insert(MSI); |
Chad Rosier | 81362a8 | 2016-02-12 21:03:23 +0000 | [diff] [blame] | 705 | bool NegStride = SizeInBytes == -Stride; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 706 | return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 707 | MSI->getAlignment(), SplatValue, MSI, MSIs, Ev, |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 708 | BECount, NegStride, /*IsLoopMemset=*/true); |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 709 | } |
| 710 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 711 | /// mayLoopAccessLocation - Return true if the specified loop might access the |
| 712 | /// specified pointer location, which is a loop-strided access. The 'Access' |
| 713 | /// argument specifies what the verboten forms of access are (read or write). |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 714 | static bool |
| 715 | mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, |
| 716 | const SCEV *BECount, unsigned StoreSize, |
| 717 | AliasAnalysis &AA, |
| 718 | SmallPtrSetImpl<Instruction *> &IgnoredStores) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 719 | // Get the location that may be stored across the loop. Since the access is |
| 720 | // strided positively through memory, we say that the modified location starts |
| 721 | // at the pointer and has infinite size. |
Chandler Carruth | ecbd168 | 2015-06-17 07:21:38 +0000 | [diff] [blame] | 722 | uint64_t AccessSize = MemoryLocation::UnknownSize; |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 723 | |
| 724 | // If the loop iterates a fixed number of times, we can refine the access size |
| 725 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 726 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 727 | AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize; |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 728 | |
| 729 | // TODO: For this to be really effective, we have to dive into the pointer |
| 730 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 731 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 732 | // which will then no-alias a store to &A[100]. |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 733 | MemoryLocation StoreLoc(Ptr, AccessSize); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 734 | |
| 735 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 736 | ++BI) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 737 | for (Instruction &I : **BI) |
| 738 | if (IgnoredStores.count(&I) == 0 && |
| 739 | (AA.getModRefInfo(&I, StoreLoc) & Access)) |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 740 | return true; |
| 741 | |
| 742 | return false; |
| 743 | } |
| 744 | |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 745 | // If we have a negative stride, Start refers to the end of the memory location |
| 746 | // we're trying to memset. Therefore, we need to recompute the base pointer, |
| 747 | // which is just Start - BECount*Size. |
| 748 | static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount, |
| 749 | Type *IntPtr, unsigned StoreSize, |
| 750 | ScalarEvolution *SE) { |
| 751 | const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
| 752 | if (StoreSize != 1) |
| 753 | Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize), |
| 754 | SCEV::FlagNUW); |
| 755 | return SE->getMinusSCEV(Start, Index); |
| 756 | } |
| 757 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 758 | /// processLoopStridedStore - We see a strided store of some value. If we can |
| 759 | /// transform this into a memset or memset_pattern in the loop preheader, do so. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 760 | bool LoopIdiomRecognize::processLoopStridedStore( |
| 761 | Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 762 | Value *StoredVal, Instruction *TheStore, |
| 763 | SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev, |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 764 | const SCEV *BECount, bool NegStride, bool IsLoopMemset) { |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 765 | Value *SplatValue = isBytewiseValue(StoredVal); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 766 | Constant *PatternValue = nullptr; |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 767 | |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 768 | if (!SplatValue) |
| 769 | PatternValue = getMemSetPatternValue(StoredVal, DL); |
| 770 | |
| 771 | assert((SplatValue || PatternValue) && |
| 772 | "Expected either splat value or pattern value."); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 773 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 774 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 775 | // guaranteed to be loop invariant, which means that it should dominate the |
| 776 | // header. This allows us to insert code for it in the preheader. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 777 | unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 778 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 779 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 780 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 781 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 782 | Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 783 | Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS); |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 784 | |
| 785 | const SCEV *Start = Ev->getStart(); |
Chad Rosier | 2fa50a7 | 2015-11-13 19:13:40 +0000 | [diff] [blame] | 786 | // Handle negative strided loops. |
Chad Rosier | ed0c7d1 | 2015-11-13 19:11:07 +0000 | [diff] [blame] | 787 | if (NegStride) |
| 788 | Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 789 | |
Aditya Kumar | 1c42d13 | 2017-05-05 14:49:45 +0000 | [diff] [blame] | 790 | // TODO: ideally we should still be able to generate memset if SCEV expander |
| 791 | // is taught to generate the dependencies at the latest point. |
| 792 | if (!isSafeToExpand(Start, *SE)) |
| 793 | return false; |
| 794 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 795 | // Okay, we have a strided store "p[i]" of a splattable value. We can turn |
Benjamin Kramer | f77f224 | 2012-10-21 19:31:16 +0000 | [diff] [blame] | 796 | // this into a memset in the loop preheader now if we want. However, this |
| 797 | // would be unsafe to do if there is anything else in the loop that may read |
Chandler Carruth | 7ec5085 | 2012-11-01 08:07:29 +0000 | [diff] [blame] | 798 | // or write to the aliased location. Check for any overlap by generating the |
| 799 | // base pointer and checking the region. |
Chad Rosier | 7967614 | 2015-10-28 14:38:49 +0000 | [diff] [blame] | 800 | Value *BasePtr = |
| 801 | Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator()); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 802 | if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 803 | *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 804 | Expander.clear(); |
| 805 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 806 | RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 807 | return false; |
| 808 | } |
| 809 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 810 | if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset)) |
| 811 | return false; |
| 812 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 813 | // Okay, everything looks good, insert the memset. |
| 814 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 815 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 816 | // pointer size if it isn't already. |
Chris Lattner | 0ba473c | 2011-01-04 00:06:55 +0000 | [diff] [blame] | 817 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 818 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 819 | const SCEV *NumBytesS = |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 820 | SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 821 | if (StoreSize != 1) { |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 822 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 823 | SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 824 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 825 | |
Aditya Kumar | 1c42d13 | 2017-05-05 14:49:45 +0000 | [diff] [blame] | 826 | // TODO: ideally we should still be able to generate memset if SCEV expander |
| 827 | // is taught to generate the dependencies at the latest point. |
| 828 | if (!isSafeToExpand(NumBytesS, *SE)) |
| 829 | return false; |
| 830 | |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 831 | Value *NumBytes = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 832 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 833 | |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 834 | CallInst *NewCall; |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 835 | if (SplatValue) { |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 836 | NewCall = |
| 837 | Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 838 | } else { |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 839 | // Everything is emitted in default address space |
| 840 | Type *Int8PtrTy = DestInt8PtrTy; |
| 841 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 842 | Module *M = TheStore->getModule(); |
Mehdi Amini | db11fdf | 2017-04-06 20:23:57 +0000 | [diff] [blame] | 843 | Value *MSP = |
| 844 | M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(), |
Serge Guelton | 59a2d7b | 2017-04-11 15:01:18 +0000 | [diff] [blame] | 845 | Int8PtrTy, Int8PtrTy, IntPtr); |
Ahmed Bougacha | ace97c1 | 2016-04-27 19:04:50 +0000 | [diff] [blame] | 846 | inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 847 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 848 | // Otherwise we should form a memset_pattern16. PatternValue is known to be |
| 849 | // an constant array of 16-bytes. Plop the value into a mergable global. |
| 850 | GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, |
Benjamin Kramer | 838752d | 2015-03-03 00:17:09 +0000 | [diff] [blame] | 851 | GlobalValue::PrivateLinkage, |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 852 | PatternValue, ".memset_pattern"); |
Peter Collingbourne | 96efdd6 | 2016-06-14 21:01:22 +0000 | [diff] [blame] | 853 | GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these. |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 854 | GV->setAlignment(16); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 855 | Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 856 | NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes}); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 857 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 858 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 859 | DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 860 | << " from store to: " << *Ev << " at: " << *TheStore << "\n"); |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 861 | NewCall->setDebugLoc(TheStore->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 862 | |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 863 | // Okay, the memset has been formed. Zap the original store and anything that |
| 864 | // feeds into it. |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 865 | for (auto *I : Stores) |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 866 | deleteDeadInstruction(I); |
Chris Lattner | 12f91be | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 867 | ++NumMemSet; |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 868 | return true; |
| 869 | } |
| 870 | |
Chad Rosier | 1cd3da1 | 2015-11-19 21:33:07 +0000 | [diff] [blame] | 871 | /// If the stored value is a strided load in the same loop with the same stride |
| 872 | /// this may be transformable into a memcpy. This kicks in for stuff like |
Xin Tong | a41bf70 | 2017-05-01 23:08:19 +0000 | [diff] [blame] | 873 | /// for (i) A[i] = B[i]; |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 874 | bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI, |
| 875 | const SCEV *BECount) { |
| 876 | assert(SI->isSimple() && "Expected only non-volatile stores."); |
| 877 | |
| 878 | Value *StorePtr = SI->getPointerOperand(); |
| 879 | const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Chad Rosier | 4acff96 | 2016-02-12 19:05:27 +0000 | [diff] [blame] | 880 | APInt Stride = getStoreStride(StoreEv); |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 881 | unsigned StoreSize = getStoreSizeInBytes(SI, DL); |
| 882 | bool NegStride = StoreSize == -Stride; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 883 | |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 884 | // The store must be feeding a non-volatile load. |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 885 | LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); |
| 886 | assert(LI->isSimple() && "Expected only non-volatile stores."); |
Chad Rosier | fddc01f | 2015-11-19 18:22:21 +0000 | [diff] [blame] | 887 | |
| 888 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 889 | // loop, which indicates a strided load. If we have something else, it's a |
| 890 | // random load we can't handle. |
Chad Rosier | 3ecc8d8 | 2015-11-19 18:25:11 +0000 | [diff] [blame] | 891 | const SCEVAddRecExpr *LoadEv = |
Haicheng Wu | 9d6c940 | 2016-01-04 21:43:14 +0000 | [diff] [blame] | 892 | cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand())); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 893 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 894 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 895 | // guaranteed to be loop invariant, which means that it should dominate the |
| 896 | // header. This allows us to insert code for it in the preheader. |
| 897 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 898 | IRBuilder<> Builder(Preheader->getTerminator()); |
Chad Rosier | 43f9b48 | 2015-11-06 16:33:57 +0000 | [diff] [blame] | 899 | SCEVExpander Expander(*SE, *DL, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 900 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 901 | const SCEV *StrStart = StoreEv->getStart(); |
| 902 | unsigned StrAS = SI->getPointerAddressSpace(); |
| 903 | Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS); |
| 904 | |
| 905 | // Handle negative strided loops. |
| 906 | if (NegStride) |
| 907 | StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE); |
| 908 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 909 | // Okay, we have a strided store "p[i]" of a loaded value. We can turn |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 910 | // this into a memcpy in the loop preheader now if we want. However, this |
| 911 | // would be unsafe to do if there is anything else in the loop that may read |
| 912 | // or write the memory region we're storing to. This includes the load that |
| 913 | // feeds the stores. Check for an alias by generating the base address and |
| 914 | // checking everything. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 915 | Value *StoreBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 916 | StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator()); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 917 | |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 918 | SmallPtrSet<Instruction *, 1> Stores; |
| 919 | Stores.insert(SI); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 920 | if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 921 | StoreSize, *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 922 | Expander.clear(); |
| 923 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 924 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 925 | return false; |
| 926 | } |
| 927 | |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 928 | const SCEV *LdStart = LoadEv->getStart(); |
| 929 | unsigned LdAS = LI->getPointerAddressSpace(); |
| 930 | |
| 931 | // Handle negative strided loops. |
| 932 | if (NegStride) |
| 933 | LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE); |
| 934 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 935 | // For a memcpy, we have to make sure that the input array is not being |
| 936 | // mutated by the loop. |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 937 | Value *LoadBasePtr = Expander.expandCodeFor( |
Chad Rosier | cc299b6 | 2015-11-13 21:51:02 +0000 | [diff] [blame] | 938 | LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator()); |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 939 | |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 940 | if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize, |
Haicheng Wu | f1c00a2 | 2016-01-26 02:27:47 +0000 | [diff] [blame] | 941 | *AA, Stores)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 942 | Expander.clear(); |
| 943 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame] | 944 | RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); |
| 945 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 946 | return false; |
| 947 | } |
| 948 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 949 | if (avoidLIRForMultiBlockLoop()) |
| 950 | return false; |
| 951 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 952 | // Okay, everything is safe, we can transform this! |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 953 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 954 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 955 | // pointer size if it isn't already. |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 956 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 957 | |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 958 | const SCEV *NumBytesS = |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 959 | SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW); |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 960 | if (StoreSize != 1) |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 961 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 962 | SCEV::FlagNUW); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 963 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 964 | Value *NumBytes = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 965 | Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 966 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 967 | CallInst *NewCall = |
Chandler Carruth | bad690e | 2015-08-12 23:06:37 +0000 | [diff] [blame] | 968 | Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 969 | std::min(SI->getAlignment(), LI->getAlignment())); |
Devang Patel | 0daa07e | 2011-05-04 21:37:05 +0000 | [diff] [blame] | 970 | NewCall->setDebugLoc(SI->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 971 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 972 | DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 973 | << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" |
| 974 | << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 975 | |
Chad Rosier | 7f08d80 | 2015-10-13 20:59:16 +0000 | [diff] [blame] | 976 | // Okay, the memcpy has been formed. Zap the original store and anything that |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 977 | // feeds into it. |
David Majnemer | 41ff4fd | 2016-06-20 16:07:38 +0000 | [diff] [blame] | 978 | deleteDeadInstruction(SI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 979 | ++NumMemCpy; |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 980 | return true; |
| 981 | } |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 982 | |
Andrew Kaylor | 7cdf01e | 2016-08-11 18:28:33 +0000 | [diff] [blame] | 983 | // When compiling for codesize we avoid idiom recognition for a multi-block loop |
| 984 | // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop. |
| 985 | // |
| 986 | bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset, |
| 987 | bool IsLoopMemset) { |
| 988 | if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) { |
| 989 | if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) { |
| 990 | DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName() |
| 991 | << " : LIR " << (IsMemset ? "Memset" : "Memcpy") |
| 992 | << " avoided: multi-block top-level loop\n"); |
| 993 | return true; |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | return false; |
| 998 | } |
| 999 | |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 1000 | bool LoopIdiomRecognize::runOnNoncountableLoop() { |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1001 | return recognizePopcount() || recognizeAndInsertCTLZ(); |
Chandler Carruth | d9c6070 | 2015-08-13 00:10:03 +0000 | [diff] [blame] | 1002 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1003 | |
| 1004 | /// Check if the given conditional branch is based on the comparison between |
| 1005 | /// a variable and zero, and if the variable is non-zero, the control yields to |
| 1006 | /// the loop entry. If the branch matches the behavior, the variable involved |
Xin Tong | 8b8a600 | 2017-01-05 21:40:08 +0000 | [diff] [blame] | 1007 | /// in the comparison is returned. This function will be called to see if the |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1008 | /// precondition and postcondition of the loop are in desirable form. |
| 1009 | static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) { |
| 1010 | if (!BI || !BI->isConditional()) |
| 1011 | return nullptr; |
| 1012 | |
| 1013 | ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); |
| 1014 | if (!Cond) |
| 1015 | return nullptr; |
| 1016 | |
| 1017 | ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); |
| 1018 | if (!CmpZero || !CmpZero->isZero()) |
| 1019 | return nullptr; |
| 1020 | |
| 1021 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
| 1022 | if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) || |
| 1023 | (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry)) |
| 1024 | return Cond->getOperand(0); |
| 1025 | |
| 1026 | return nullptr; |
| 1027 | } |
| 1028 | |
| 1029 | /// Return true iff the idiom is detected in the loop. |
| 1030 | /// |
| 1031 | /// Additionally: |
| 1032 | /// 1) \p CntInst is set to the instruction counting the population bit. |
| 1033 | /// 2) \p CntPhi is set to the corresponding phi node. |
| 1034 | /// 3) \p Var is set to the value whose population bits are being counted. |
| 1035 | /// |
| 1036 | /// The core idiom we are trying to detect is: |
| 1037 | /// \code |
| 1038 | /// if (x0 != 0) |
| 1039 | /// goto loop-exit // the precondition of the loop |
| 1040 | /// cnt0 = init-val; |
| 1041 | /// do { |
| 1042 | /// x1 = phi (x0, x2); |
| 1043 | /// cnt1 = phi(cnt0, cnt2); |
| 1044 | /// |
| 1045 | /// cnt2 = cnt1 + 1; |
| 1046 | /// ... |
| 1047 | /// x2 = x1 & (x1 - 1); |
| 1048 | /// ... |
| 1049 | /// } while(x != 0); |
| 1050 | /// |
| 1051 | /// loop-exit: |
| 1052 | /// \endcode |
| 1053 | static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, |
| 1054 | Instruction *&CntInst, PHINode *&CntPhi, |
| 1055 | Value *&Var) { |
| 1056 | // step 1: Check to see if the look-back branch match this pattern: |
| 1057 | // "if (a!=0) goto loop-entry". |
| 1058 | BasicBlock *LoopEntry; |
| 1059 | Instruction *DefX2, *CountInst; |
| 1060 | Value *VarX1, *VarX0; |
| 1061 | PHINode *PhiX, *CountPhi; |
| 1062 | |
| 1063 | DefX2 = CountInst = nullptr; |
| 1064 | VarX1 = VarX0 = nullptr; |
| 1065 | PhiX = CountPhi = nullptr; |
| 1066 | LoopEntry = *(CurLoop->block_begin()); |
| 1067 | |
| 1068 | // step 1: Check if the loop-back branch is in desirable form. |
| 1069 | { |
| 1070 | if (Value *T = matchCondition( |
| 1071 | dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) |
| 1072 | DefX2 = dyn_cast<Instruction>(T); |
| 1073 | else |
| 1074 | return false; |
| 1075 | } |
| 1076 | |
| 1077 | // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" |
| 1078 | { |
| 1079 | if (!DefX2 || DefX2->getOpcode() != Instruction::And) |
| 1080 | return false; |
| 1081 | |
| 1082 | BinaryOperator *SubOneOp; |
| 1083 | |
| 1084 | if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) |
| 1085 | VarX1 = DefX2->getOperand(1); |
| 1086 | else { |
| 1087 | VarX1 = DefX2->getOperand(0); |
| 1088 | SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); |
| 1089 | } |
| 1090 | if (!SubOneOp) |
| 1091 | return false; |
| 1092 | |
| 1093 | Instruction *SubInst = cast<Instruction>(SubOneOp); |
| 1094 | ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); |
| 1095 | if (!Dec || |
| 1096 | !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || |
| 1097 | (SubInst->getOpcode() == Instruction::Add && |
| 1098 | Dec->isAllOnesValue()))) { |
| 1099 | return false; |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | // step 3: Check the recurrence of variable X |
| 1104 | { |
| 1105 | PhiX = dyn_cast<PHINode>(VarX1); |
| 1106 | if (!PhiX || |
| 1107 | (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { |
| 1108 | return false; |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 |
| 1113 | { |
| 1114 | CountInst = nullptr; |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1115 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1116 | IterE = LoopEntry->end(); |
| 1117 | Iter != IterE; Iter++) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1118 | Instruction *Inst = &*Iter; |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1119 | if (Inst->getOpcode() != Instruction::Add) |
| 1120 | continue; |
| 1121 | |
| 1122 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 1123 | if (!Inc || !Inc->isOne()) |
| 1124 | continue; |
| 1125 | |
| 1126 | PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); |
| 1127 | if (!Phi || Phi->getParent() != LoopEntry) |
| 1128 | continue; |
| 1129 | |
| 1130 | // Check if the result of the instruction is live of the loop. |
| 1131 | bool LiveOutLoop = false; |
| 1132 | for (User *U : Inst->users()) { |
| 1133 | if ((cast<Instruction>(U))->getParent() != LoopEntry) { |
| 1134 | LiveOutLoop = true; |
| 1135 | break; |
| 1136 | } |
| 1137 | } |
| 1138 | |
| 1139 | if (LiveOutLoop) { |
| 1140 | CountInst = Inst; |
| 1141 | CountPhi = Phi; |
| 1142 | break; |
| 1143 | } |
| 1144 | } |
| 1145 | |
| 1146 | if (!CountInst) |
| 1147 | return false; |
| 1148 | } |
| 1149 | |
| 1150 | // step 5: check if the precondition is in this form: |
| 1151 | // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" |
| 1152 | { |
| 1153 | auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1154 | Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader()); |
| 1155 | if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) |
| 1156 | return false; |
| 1157 | |
| 1158 | CntInst = CountInst; |
| 1159 | CntPhi = CountPhi; |
| 1160 | Var = T; |
| 1161 | } |
| 1162 | |
| 1163 | return true; |
| 1164 | } |
| 1165 | |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1166 | /// Return true if the idiom is detected in the loop. |
| 1167 | /// |
| 1168 | /// Additionally: |
| 1169 | /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ) |
| 1170 | /// or nullptr if there is no such. |
| 1171 | /// 2) \p CntPhi is set to the corresponding phi node |
| 1172 | /// or nullptr if there is no such. |
| 1173 | /// 3) \p Var is set to the value whose CTLZ could be used. |
| 1174 | /// 4) \p DefX is set to the instruction calculating Loop exit condition. |
| 1175 | /// |
| 1176 | /// The core idiom we are trying to detect is: |
| 1177 | /// \code |
| 1178 | /// if (x0 == 0) |
| 1179 | /// goto loop-exit // the precondition of the loop |
| 1180 | /// cnt0 = init-val; |
| 1181 | /// do { |
| 1182 | /// x = phi (x0, x.next); //PhiX |
| 1183 | /// cnt = phi(cnt0, cnt.next); |
| 1184 | /// |
| 1185 | /// cnt.next = cnt + 1; |
| 1186 | /// ... |
| 1187 | /// x.next = x >> 1; // DefX |
| 1188 | /// ... |
| 1189 | /// } while(x.next != 0); |
| 1190 | /// |
| 1191 | /// loop-exit: |
| 1192 | /// \endcode |
| 1193 | static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX, |
| 1194 | Instruction *&CntInst, PHINode *&CntPhi, |
| 1195 | Instruction *&DefX) { |
| 1196 | BasicBlock *LoopEntry; |
| 1197 | Value *VarX = nullptr; |
| 1198 | |
| 1199 | DefX = nullptr; |
| 1200 | PhiX = nullptr; |
| 1201 | CntInst = nullptr; |
| 1202 | CntPhi = nullptr; |
| 1203 | LoopEntry = *(CurLoop->block_begin()); |
| 1204 | |
| 1205 | // step 1: Check if the loop-back branch is in desirable form. |
| 1206 | if (Value *T = matchCondition( |
| 1207 | dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry)) |
| 1208 | DefX = dyn_cast<Instruction>(T); |
| 1209 | else |
| 1210 | return false; |
| 1211 | |
| 1212 | // step 2: detect instructions corresponding to "x.next = x >> 1" |
| 1213 | if (!DefX || DefX->getOpcode() != Instruction::AShr) |
| 1214 | return false; |
| 1215 | if (ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1))) |
| 1216 | if (!Shft || !Shft->isOne()) |
| 1217 | return false; |
| 1218 | VarX = DefX->getOperand(0); |
| 1219 | |
| 1220 | // step 3: Check the recurrence of variable X |
| 1221 | PhiX = dyn_cast<PHINode>(VarX); |
| 1222 | if (!PhiX || (PhiX->getOperand(0) != DefX && PhiX->getOperand(1) != DefX)) |
| 1223 | return false; |
| 1224 | |
| 1225 | // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1 |
| 1226 | // TODO: We can skip the step. If loop trip count is known (CTLZ), |
| 1227 | // then all uses of "cnt.next" could be optimized to the trip count |
| 1228 | // plus "cnt0". Currently it is not optimized. |
| 1229 | // This step could be used to detect POPCNT instruction: |
| 1230 | // cnt.next = cnt + (x.next & 1) |
| 1231 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(), |
| 1232 | IterE = LoopEntry->end(); |
| 1233 | Iter != IterE; Iter++) { |
| 1234 | Instruction *Inst = &*Iter; |
| 1235 | if (Inst->getOpcode() != Instruction::Add) |
| 1236 | continue; |
| 1237 | |
| 1238 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 1239 | if (!Inc || !Inc->isOne()) |
| 1240 | continue; |
| 1241 | |
| 1242 | PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); |
| 1243 | if (!Phi || Phi->getParent() != LoopEntry) |
| 1244 | continue; |
| 1245 | |
| 1246 | CntInst = Inst; |
| 1247 | CntPhi = Phi; |
| 1248 | break; |
| 1249 | } |
| 1250 | if (!CntInst) |
| 1251 | return false; |
| 1252 | |
| 1253 | return true; |
| 1254 | } |
| 1255 | |
| 1256 | /// Recognize CTLZ idiom in a non-countable loop and convert the loop |
| 1257 | /// to countable (with CTLZ trip count). |
| 1258 | /// If CTLZ inserted as a new trip count returns true; otherwise, returns false. |
| 1259 | bool LoopIdiomRecognize::recognizeAndInsertCTLZ() { |
| 1260 | // Give up if the loop has multiple blocks or multiple backedges. |
| 1261 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
| 1262 | return false; |
| 1263 | |
| 1264 | Instruction *CntInst, *DefX; |
| 1265 | PHINode *CntPhi, *PhiX; |
| 1266 | if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX)) |
| 1267 | return false; |
| 1268 | |
| 1269 | bool IsCntPhiUsedOutsideLoop = false; |
| 1270 | for (User *U : CntPhi->users()) |
| 1271 | if (!CurLoop->contains(dyn_cast<Instruction>(U))) { |
| 1272 | IsCntPhiUsedOutsideLoop = true; |
| 1273 | break; |
| 1274 | } |
| 1275 | bool IsCntInstUsedOutsideLoop = false; |
| 1276 | for (User *U : CntInst->users()) |
| 1277 | if (!CurLoop->contains(dyn_cast<Instruction>(U))) { |
| 1278 | IsCntInstUsedOutsideLoop = true; |
| 1279 | break; |
| 1280 | } |
| 1281 | // If both CntInst and CntPhi are used outside the loop the profitability |
| 1282 | // is questionable. |
| 1283 | if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop) |
| 1284 | return false; |
| 1285 | |
| 1286 | // For some CPUs result of CTLZ(X) intrinsic is undefined |
| 1287 | // when X is 0. If we can not guarantee X != 0, we need to check this |
| 1288 | // when expand. |
| 1289 | bool ZeroCheck = false; |
| 1290 | // It is safe to assume Preheader exist as it was checked in |
| 1291 | // parent function RunOnLoop. |
| 1292 | BasicBlock *PH = CurLoop->getLoopPreheader(); |
| 1293 | Value *InitX = PhiX->getIncomingValueForBlock(PH); |
| 1294 | // If we check X != 0 before entering the loop we don't need a zero |
| 1295 | // check in CTLZ intrinsic. |
| 1296 | if (BasicBlock *PreCondBB = PH->getSinglePredecessor()) |
| 1297 | if (BranchInst *PreCondBr = |
| 1298 | dyn_cast<BranchInst>(PreCondBB->getTerminator())) { |
| 1299 | if (matchCondition(PreCondBr, PH) == InitX) |
| 1300 | ZeroCheck = true; |
| 1301 | } |
| 1302 | |
| 1303 | // Check if CTLZ intrinsic is profitable. Assume it is always profitable |
| 1304 | // if we delete the loop (the loop has only 6 instructions): |
| 1305 | // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ] |
| 1306 | // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ] |
| 1307 | // %shr = ashr %n.addr.0, 1 |
| 1308 | // %tobool = icmp eq %shr, 0 |
| 1309 | // %inc = add nsw %i.0, 1 |
| 1310 | // br i1 %tobool |
| 1311 | |
| 1312 | IRBuilder<> Builder(PH->getTerminator()); |
| 1313 | SmallVector<const Value *, 2> Ops = |
| 1314 | {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()}; |
| 1315 | ArrayRef<const Value *> Args(Ops); |
| 1316 | if (CurLoop->getHeader()->size() != 6 && |
| 1317 | TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) > |
| 1318 | TargetTransformInfo::TCC_Basic) |
| 1319 | return false; |
| 1320 | |
| 1321 | const DebugLoc DL = DefX->getDebugLoc(); |
| 1322 | transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck, |
| 1323 | IsCntPhiUsedOutsideLoop); |
| 1324 | return true; |
| 1325 | } |
| 1326 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1327 | /// Recognizes a population count idiom in a non-countable loop. |
| 1328 | /// |
| 1329 | /// If detected, transforms the relevant code to issue the popcount intrinsic |
| 1330 | /// function call, and returns true; otherwise, returns false. |
| 1331 | bool LoopIdiomRecognize::recognizePopcount() { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1332 | if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) |
| 1333 | return false; |
| 1334 | |
| 1335 | // Counting population are usually conducted by few arithmetic instructions. |
Nick Lewycky | 06b0ea2 | 2015-08-18 22:41:58 +0000 | [diff] [blame] | 1336 | // Such instructions can be easily "absorbed" by vacant slots in a |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1337 | // non-compact loop. Therefore, recognizing popcount idiom only makes sense |
| 1338 | // in a compact loop. |
| 1339 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1340 | // Give up if the loop has multiple blocks or multiple backedges. |
| 1341 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1342 | return false; |
| 1343 | |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1344 | BasicBlock *LoopBody = *(CurLoop->block_begin()); |
| 1345 | if (LoopBody->size() >= 20) { |
| 1346 | // The loop is too big, bail out. |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1347 | return false; |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1348 | } |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1349 | |
| 1350 | // It should have a preheader containing nothing but an unconditional branch. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1351 | BasicBlock *PH = CurLoop->getLoopPreheader(); |
Davide Italiano | c0169fa | 2016-10-07 18:39:43 +0000 | [diff] [blame] | 1352 | if (!PH || &PH->front() != PH->getTerminator()) |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1353 | return false; |
| 1354 | auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1355 | if (!EntryBI || EntryBI->isConditional()) |
| 1356 | return false; |
| 1357 | |
| 1358 | // It should have a precondition block where the generated popcount instrinsic |
| 1359 | // function can be inserted. |
Renato Golin | 655348f | 2015-08-13 11:25:38 +0000 | [diff] [blame] | 1360 | auto *PreCondBB = PH->getSinglePredecessor(); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1361 | if (!PreCondBB) |
| 1362 | return false; |
| 1363 | auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1364 | if (!PreCondBI || PreCondBI->isUnconditional()) |
| 1365 | return false; |
| 1366 | |
| 1367 | Instruction *CntInst; |
| 1368 | PHINode *CntPhi; |
| 1369 | Value *Val; |
| 1370 | if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val)) |
| 1371 | return false; |
| 1372 | |
| 1373 | transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val); |
| 1374 | return true; |
| 1375 | } |
| 1376 | |
| 1377 | static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, |
Benjamin Kramer | bdc4956 | 2016-06-12 15:39:02 +0000 | [diff] [blame] | 1378 | const DebugLoc &DL) { |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1379 | Value *Ops[] = {Val}; |
| 1380 | Type *Tys[] = {Val->getType()}; |
| 1381 | |
| 1382 | Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); |
| 1383 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); |
| 1384 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 1385 | CI->setDebugLoc(DL); |
| 1386 | |
| 1387 | return CI; |
| 1388 | } |
| 1389 | |
Evgeny Stupachenko | 2fecd38 | 2017-05-15 19:08:56 +0000 | [diff] [blame] | 1390 | static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val, |
| 1391 | const DebugLoc &DL, bool ZeroCheck) { |
| 1392 | Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()}; |
| 1393 | Type *Tys[] = {Val->getType()}; |
| 1394 | |
| 1395 | Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent(); |
| 1396 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys); |
| 1397 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 1398 | CI->setDebugLoc(DL); |
| 1399 | |
| 1400 | return CI; |
| 1401 | } |
| 1402 | |
| 1403 | /// Transform the following loop: |
| 1404 | /// loop: |
| 1405 | /// CntPhi = PHI [Cnt0, CntInst] |
| 1406 | /// PhiX = PHI [InitX, DefX] |
| 1407 | /// CntInst = CntPhi + 1 |
| 1408 | /// DefX = PhiX >> 1 |
| 1409 | // LOOP_BODY |
| 1410 | /// Br: loop if (DefX != 0) |
| 1411 | /// Use(CntPhi) or Use(CntInst) |
| 1412 | /// |
| 1413 | /// Into: |
| 1414 | /// If CntPhi used outside the loop: |
| 1415 | /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1) |
| 1416 | /// Count = CountPrev + 1 |
| 1417 | /// else |
| 1418 | /// Count = BitWidth(InitX) - CTLZ(InitX) |
| 1419 | /// loop: |
| 1420 | /// CntPhi = PHI [Cnt0, CntInst] |
| 1421 | /// PhiX = PHI [InitX, DefX] |
| 1422 | /// PhiCount = PHI [Count, Dec] |
| 1423 | /// CntInst = CntPhi + 1 |
| 1424 | /// DefX = PhiX >> 1 |
| 1425 | /// Dec = PhiCount - 1 |
| 1426 | /// LOOP_BODY |
| 1427 | /// Br: loop if (Dec != 0) |
| 1428 | /// Use(CountPrev + Cnt0) // Use(CntPhi) |
| 1429 | /// or |
| 1430 | /// Use(Count + Cnt0) // Use(CntInst) |
| 1431 | /// |
| 1432 | /// If LOOP_BODY is empty the loop will be deleted. |
| 1433 | /// If CntInst and DefX are not used in LOOP_BODY they will be removed. |
| 1434 | void LoopIdiomRecognize::transformLoopToCountable( |
| 1435 | BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX, |
| 1436 | const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) { |
| 1437 | BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator()); |
| 1438 | |
| 1439 | // Step 1: Insert the CTLZ instruction at the end of the preheader block |
| 1440 | // Count = BitWidth - CTLZ(InitX); |
| 1441 | // If there are uses of CntPhi create: |
| 1442 | // CountPrev = BitWidth - CTLZ(InitX >> 1); |
| 1443 | IRBuilder<> Builder(PreheaderBr); |
| 1444 | Builder.SetCurrentDebugLocation(DL); |
| 1445 | Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext; |
| 1446 | |
| 1447 | if (IsCntPhiUsedOutsideLoop) |
| 1448 | InitXNext = Builder.CreateAShr(InitX, |
| 1449 | ConstantInt::get(InitX->getType(), 1)); |
| 1450 | else |
| 1451 | InitXNext = InitX; |
| 1452 | CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck); |
| 1453 | Count = Builder.CreateSub( |
| 1454 | ConstantInt::get(CTLZ->getType(), |
| 1455 | CTLZ->getType()->getIntegerBitWidth()), |
| 1456 | CTLZ); |
| 1457 | if (IsCntPhiUsedOutsideLoop) { |
| 1458 | CountPrev = Count; |
| 1459 | Count = Builder.CreateAdd( |
| 1460 | CountPrev, |
| 1461 | ConstantInt::get(CountPrev->getType(), 1)); |
| 1462 | } |
| 1463 | if (IsCntPhiUsedOutsideLoop) |
| 1464 | NewCount = Builder.CreateZExtOrTrunc(CountPrev, |
| 1465 | cast<IntegerType>(CntInst->getType())); |
| 1466 | else |
| 1467 | NewCount = Builder.CreateZExtOrTrunc(Count, |
| 1468 | cast<IntegerType>(CntInst->getType())); |
| 1469 | |
| 1470 | // If the CTLZ counter's initial value is not zero, insert Add Inst. |
| 1471 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader); |
| 1472 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 1473 | if (!InitConst || !InitConst->isZero()) |
| 1474 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 1475 | |
| 1476 | // Step 2: Insert new IV and loop condition: |
| 1477 | // loop: |
| 1478 | // ... |
| 1479 | // PhiCount = PHI [Count, Dec] |
| 1480 | // ... |
| 1481 | // Dec = PhiCount - 1 |
| 1482 | // ... |
| 1483 | // Br: loop if (Dec != 0) |
| 1484 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 1485 | auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); |
| 1486 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 1487 | Type *Ty = Count->getType(); |
| 1488 | |
| 1489 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); |
| 1490 | |
| 1491 | Builder.SetInsertPoint(LbCond); |
| 1492 | Instruction *TcDec = cast<Instruction>( |
| 1493 | Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), |
| 1494 | "tcdec", false, true)); |
| 1495 | |
| 1496 | TcPhi->addIncoming(Count, Preheader); |
| 1497 | TcPhi->addIncoming(TcDec, Body); |
| 1498 | |
| 1499 | CmpInst::Predicate Pred = |
| 1500 | (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; |
| 1501 | LbCond->setPredicate(Pred); |
| 1502 | LbCond->setOperand(0, TcDec); |
| 1503 | LbCond->setOperand(1, ConstantInt::get(Ty, 0)); |
| 1504 | |
| 1505 | // Step 3: All the references to the original counter outside |
| 1506 | // the loop are replaced with the NewCount -- the value returned from |
| 1507 | // __builtin_ctlz(x). |
| 1508 | if (IsCntPhiUsedOutsideLoop) |
| 1509 | CntPhi->replaceUsesOutsideBlock(NewCount, Body); |
| 1510 | else |
| 1511 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
| 1512 | |
| 1513 | // step 4: Forget the "non-computable" trip-count SCEV associated with the |
| 1514 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 1515 | SE->forgetLoop(CurLoop); |
| 1516 | } |
| 1517 | |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1518 | void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB, |
| 1519 | Instruction *CntInst, |
| 1520 | PHINode *CntPhi, Value *Var) { |
| 1521 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 1522 | auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator()); |
| 1523 | const DebugLoc DL = CntInst->getDebugLoc(); |
| 1524 | |
| 1525 | // Assuming before transformation, the loop is following: |
| 1526 | // if (x) // the precondition |
| 1527 | // do { cnt++; x &= x - 1; } while(x); |
| 1528 | |
| 1529 | // Step 1: Insert the ctpop instruction at the end of the precondition block |
| 1530 | IRBuilder<> Builder(PreCondBr); |
| 1531 | Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; |
| 1532 | { |
| 1533 | PopCnt = createPopcntIntrinsic(Builder, Var, DL); |
| 1534 | NewCount = PopCntZext = |
| 1535 | Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); |
| 1536 | |
| 1537 | if (NewCount != PopCnt) |
| 1538 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1539 | |
| 1540 | // TripCnt is exactly the number of iterations the loop has |
| 1541 | TripCnt = NewCount; |
| 1542 | |
| 1543 | // If the population counter's initial value is not zero, insert Add Inst. |
| 1544 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); |
| 1545 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 1546 | if (!InitConst || !InitConst->isZero()) { |
| 1547 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 1548 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 1549 | } |
| 1550 | } |
| 1551 | |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1552 | // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1553 | // "if (NewCount == 0) loop-exit". Without this change, the intrinsic |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1554 | // function would be partial dead code, and downstream passes will drag |
| 1555 | // it back from the precondition block to the preheader. |
| 1556 | { |
| 1557 | ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); |
| 1558 | |
| 1559 | Value *Opnd0 = PopCntZext; |
| 1560 | Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); |
| 1561 | if (PreCond->getOperand(0) != Var) |
| 1562 | std::swap(Opnd0, Opnd1); |
| 1563 | |
| 1564 | ICmpInst *NewPreCond = cast<ICmpInst>( |
| 1565 | Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); |
| 1566 | PreCondBr->setCondition(NewPreCond); |
| 1567 | |
| 1568 | RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); |
| 1569 | } |
| 1570 | |
| 1571 | // Step 3: Note that the population count is exactly the trip count of the |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1572 | // loop in question, which enable us to to convert the loop from noncountable |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1573 | // loop into a countable one. The benefit is twofold: |
| 1574 | // |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1575 | // - If the loop only counts population, the entire loop becomes dead after |
| 1576 | // the transformation. It is a lot easier to prove a countable loop dead |
| 1577 | // than to prove a noncountable one. (In some C dialects, an infinite loop |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1578 | // isn't dead even if it computes nothing useful. In general, DCE needs |
| 1579 | // to prove a noncountable loop finite before safely delete it.) |
| 1580 | // |
| 1581 | // - If the loop also performs something else, it remains alive. |
| 1582 | // Since it is transformed to countable form, it can be aggressively |
| 1583 | // optimized by some optimizations which are in general not applicable |
| 1584 | // to a noncountable loop. |
| 1585 | // |
| 1586 | // After this step, this loop (conceptually) would look like following: |
| 1587 | // newcnt = __builtin_ctpop(x); |
| 1588 | // t = newcnt; |
| 1589 | // if (x) |
| 1590 | // do { cnt++; x &= x-1; t--) } while (t > 0); |
| 1591 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 1592 | { |
| 1593 | auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator()); |
| 1594 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 1595 | Type *Ty = TripCnt->getType(); |
| 1596 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1597 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front()); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1598 | |
| 1599 | Builder.SetInsertPoint(LbCond); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1600 | Instruction *TcDec = cast<Instruction>( |
Nick Lewycky | 1098e49 | 2015-08-19 06:25:30 +0000 | [diff] [blame] | 1601 | Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1), |
| 1602 | "tcdec", false, true)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1603 | |
| 1604 | TcPhi->addIncoming(TripCnt, PreHead); |
| 1605 | TcPhi->addIncoming(TcDec, Body); |
| 1606 | |
| 1607 | CmpInst::Predicate Pred = |
| 1608 | (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; |
| 1609 | LbCond->setPredicate(Pred); |
| 1610 | LbCond->setOperand(0, TcDec); |
Nick Lewycky | 2c85254 | 2015-08-19 06:22:33 +0000 | [diff] [blame] | 1611 | LbCond->setOperand(1, ConstantInt::get(Ty, 0)); |
Chandler Carruth | 8219a50 | 2015-08-13 00:44:29 +0000 | [diff] [blame] | 1612 | } |
| 1613 | |
| 1614 | // Step 4: All the references to the original population counter outside |
| 1615 | // the loop are replaced with the NewCount -- the value returned from |
| 1616 | // __builtin_ctpop(). |
| 1617 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
| 1618 | |
| 1619 | // step 5: Forget the "non-computable" trip-count SCEV associated with the |
| 1620 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 1621 | SE->forgetLoop(CurLoop); |
| 1622 | } |