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 | // |
| 14 | //===----------------------------------------------------------------------===// |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 15 | // |
| 16 | // TODO List: |
| 17 | // |
| 18 | // Future loop memory idioms to recognize: |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 19 | // memcmp, memmove, strlen, etc. |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 20 | // Future floating point idioms to recognize in -ffast-math mode: |
| 21 | // fpowi |
| 22 | // Future integer operation idioms to recognize: |
| 23 | // ctpop, ctlz, cttz |
| 24 | // |
| 25 | // Beware that isel's default lowering for ctpop is highly inefficient for |
| 26 | // i64 and larger types when i64 is legal and the value has few bits set. It |
| 27 | // would be good to enhance isel to emit a loop for ctpop in this case. |
| 28 | // |
| 29 | // We should enhance the memset/memcpy recognition to handle multiple stores in |
| 30 | // the loop. This would handle things like: |
| 31 | // void foo(_Complex float *P) |
| 32 | // for (i) { __real__(*P) = 0; __imag__(*P) = 0; } |
Chris Lattner | 8fac5db | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 33 | // |
Chris Lattner | bc661d6 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 34 | // We should enhance this to handle negative strides through memory. |
| 35 | // Alternatively (and perhaps better) we could rely on an earlier pass to force |
| 36 | // forward iteration through memory, which is generally better for cache |
| 37 | // behavior. Negative strides *do* happen for memset/memcpy loops. |
| 38 | // |
Chris Lattner | 02a9776 | 2011-01-03 01:10:08 +0000 | [diff] [blame] | 39 | // This could recognize common matrix multiplies and dot product idioms and |
Chris Lattner | 8fac5db | 2011-01-02 23:19:45 +0000 | [diff] [blame] | 40 | // replace them with calls to BLAS (if linked in??). |
| 41 | // |
Chris Lattner | 0469e01 | 2011-01-02 18:32:09 +0000 | [diff] [blame] | 42 | //===----------------------------------------------------------------------===// |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 43 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/AliasAnalysis.h" |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/LoopPass.h" |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 52 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 53 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 54 | #include "llvm/IR/IRBuilder.h" |
| 55 | #include "llvm/IR/IntrinsicInst.h" |
| 56 | #include "llvm/IR/Module.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 57 | #include "llvm/Support/Debug.h" |
| 58 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 59 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 61 | using namespace llvm; |
| 62 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 63 | #define DEBUG_TYPE "loop-idiom" |
| 64 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 65 | STATISTIC(NumMemSet, "Number of memset's formed from loop stores"); |
| 66 | STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores"); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 67 | |
| 68 | namespace { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 69 | |
| 70 | class LoopIdiomRecognize; |
| 71 | |
| 72 | /// This class defines some utility functions for loop idiom recognization. |
| 73 | class LIRUtil { |
| 74 | public: |
| 75 | /// Return true iff the block contains nothing but an uncondition branch |
| 76 | /// (aka goto instruction). |
| 77 | static bool isAlmostEmpty(BasicBlock *); |
| 78 | |
| 79 | static BranchInst *getBranch(BasicBlock *BB) { |
| 80 | return dyn_cast<BranchInst>(BB->getTerminator()); |
| 81 | } |
| 82 | |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 83 | /// Derive the precondition block (i.e the block that guards the loop |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 84 | /// preheader) from the given preheader. |
| 85 | static BasicBlock *getPrecondBb(BasicBlock *PreHead); |
| 86 | }; |
| 87 | |
| 88 | /// This class is to recoginize idioms of population-count conducted in |
| 89 | /// a noncountable loop. Currently it only recognizes this pattern: |
| 90 | /// \code |
| 91 | /// while(x) {cnt++; ...; x &= x - 1; ...} |
| 92 | /// \endcode |
| 93 | class NclPopcountRecognize { |
| 94 | LoopIdiomRecognize &LIR; |
| 95 | Loop *CurLoop; |
| 96 | BasicBlock *PreCondBB; |
| 97 | |
| 98 | typedef IRBuilder<> IRBuilderTy; |
| 99 | |
| 100 | public: |
| 101 | explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR); |
| 102 | bool recognize(); |
| 103 | |
| 104 | private: |
| 105 | /// Take a glimpse of the loop to see if we need to go ahead recoginizing |
| 106 | /// the idiom. |
| 107 | bool preliminaryScreen(); |
| 108 | |
| 109 | /// Check if the given conditional branch is based on the comparison |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 110 | /// between a variable and zero, and if the variable is non-zero, the |
| 111 | /// control yields to the loop entry. If the branch matches the behavior, |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 112 | /// the variable involved in the comparion is returned. This function will |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 113 | /// be called to see if the precondition and postcondition of the loop |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 114 | /// are in desirable form. |
Nick Lewycky | b06a796 | 2014-06-14 03:48:29 +0000 | [diff] [blame] | 115 | Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 116 | |
| 117 | /// Return true iff the idiom is detected in the loop. and 1) \p CntInst |
Jim Grosbach | 4a7d496 | 2014-04-29 22:41:55 +0000 | [diff] [blame] | 118 | /// is set to the instruction counting the population bit. 2) \p CntPhi |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 119 | /// is set to the corresponding phi node. 3) \p Var is set to the value |
| 120 | /// whose population bits are being counted. |
| 121 | bool detectIdiom |
| 122 | (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const; |
| 123 | |
| 124 | /// Insert ctpop intrinsic function and some obviously dead instructions. |
Nick Lewycky | b06a796 | 2014-06-14 03:48:29 +0000 | [diff] [blame] | 125 | void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 126 | |
| 127 | /// Create llvm.ctpop.* intrinsic function. |
| 128 | CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL); |
| 129 | }; |
| 130 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 131 | class LoopIdiomRecognize : public LoopPass { |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 132 | Loop *CurLoop; |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 133 | const DataLayout *DL; |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 134 | DominatorTree *DT; |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 135 | ScalarEvolution *SE; |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 136 | TargetLibraryInfo *TLI; |
Chandler Carruth | 6fe147f | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 137 | const TargetTransformInfo *TTI; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 138 | public: |
| 139 | static char ID; |
| 140 | explicit LoopIdiomRecognize() : LoopPass(ID) { |
| 141 | initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 142 | DL = nullptr; DT = nullptr; SE = nullptr; TLI = nullptr; TTI = nullptr; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 143 | } |
| 144 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 145 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 146 | bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 147 | SmallVectorImpl<BasicBlock*> &ExitBlocks); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 148 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 149 | bool processLoopStore(StoreInst *SI, const SCEV *BECount); |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 150 | bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 151 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 152 | bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
| 153 | unsigned StoreAlignment, |
| 154 | Value *SplatValue, Instruction *TheStore, |
| 155 | const SCEVAddRecExpr *Ev, |
| 156 | const SCEV *BECount); |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 157 | bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize, |
| 158 | const SCEVAddRecExpr *StoreEv, |
| 159 | const SCEVAddRecExpr *LoadEv, |
| 160 | const SCEV *BECount); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 161 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 162 | /// This transformation requires natural loop information & requires that |
| 163 | /// loop preheaders be inserted into the CFG. |
| 164 | /// |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 165 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 166 | AU.addRequired<LoopInfoWrapperPass>(); |
| 167 | AU.addPreserved<LoopInfoWrapperPass>(); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 168 | AU.addRequiredID(LoopSimplifyID); |
| 169 | AU.addPreservedID(LoopSimplifyID); |
| 170 | AU.addRequiredID(LCSSAID); |
| 171 | AU.addPreservedID(LCSSAID); |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 172 | AU.addRequired<AliasAnalysis>(); |
| 173 | AU.addPreserved<AliasAnalysis>(); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 174 | AU.addRequired<ScalarEvolution>(); |
| 175 | AU.addPreserved<ScalarEvolution>(); |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 176 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 177 | AU.addRequired<DominatorTreeWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 178 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 179 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 180 | } |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 181 | |
| 182 | const DataLayout *getDataLayout() { |
Rafael Espindola | 9351251 | 2014-02-25 17:30:31 +0000 | [diff] [blame] | 183 | if (DL) |
| 184 | return DL; |
| 185 | DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 186 | DL = DLP ? &DLP->getDataLayout() : nullptr; |
Rafael Espindola | 9351251 | 2014-02-25 17:30:31 +0000 | [diff] [blame] | 187 | return DL; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 188 | } |
| 189 | |
| 190 | DominatorTree *getDominatorTree() { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 191 | return DT ? DT |
| 192 | : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree()); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 193 | } |
| 194 | |
| 195 | ScalarEvolution *getScalarEvolution() { |
| 196 | return SE ? SE : (SE = &getAnalysis<ScalarEvolution>()); |
| 197 | } |
| 198 | |
| 199 | TargetLibraryInfo *getTargetLibraryInfo() { |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 200 | if (!TLI) |
| 201 | TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 202 | |
| 203 | return TLI; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 204 | } |
| 205 | |
Chandler Carruth | 6fe147f | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 206 | const TargetTransformInfo *getTargetTransformInfo() { |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 207 | return TTI ? TTI |
| 208 | : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( |
| 209 | *CurLoop->getHeader()->getParent())); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 210 | } |
| 211 | |
| 212 | Loop *getLoop() const { return CurLoop; } |
| 213 | |
| 214 | private: |
| 215 | bool runOnNoncountableLoop(); |
| 216 | bool runOnCountableLoop(); |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 217 | }; |
| 218 | } |
| 219 | |
| 220 | char LoopIdiomRecognize::ID = 0; |
| 221 | INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 222 | false, false) |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 223 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 224 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 225 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
| 226 | INITIALIZE_PASS_DEPENDENCY(LCSSA) |
| 227 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 228 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Chris Lattner | cb18bfa | 2010-12-27 18:39:08 +0000 | [diff] [blame] | 229 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 230 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 231 | INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms", |
| 232 | false, false) |
| 233 | |
| 234 | Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); } |
| 235 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 236 | /// deleteDeadInstruction - Delete this instruction. Before we do, go through |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 237 | /// and zero out all the operands of this instruction. If any of them become |
| 238 | /// dead, delete them and the computation tree that feeds them. |
| 239 | /// |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 240 | static void deleteDeadInstruction(Instruction *I, |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 241 | const TargetLibraryInfo *TLI) { |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 242 | SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end()); |
| 243 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
| 244 | I->eraseFromParent(); |
| 245 | for (Value *Op : Operands) |
| 246 | RecursivelyDeleteTriviallyDeadInstructions(Op, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 247 | } |
| 248 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 249 | //===----------------------------------------------------------------------===// |
| 250 | // |
| 251 | // Implementation of LIRUtil |
| 252 | // |
| 253 | //===----------------------------------------------------------------------===// |
| 254 | |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 255 | // This function will return true iff the given block contains nothing but goto. |
| 256 | // A typical usage of this function is to check if the preheader function is |
| 257 | // "almost" empty such that generated intrinsic functions can be moved across |
| 258 | // the preheader and be placed at the end of the precondition block without |
| 259 | // the concern of breaking data dependence. |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 260 | bool LIRUtil::isAlmostEmpty(BasicBlock *BB) { |
| 261 | if (BranchInst *Br = getBranch(BB)) { |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 262 | return Br->isUnconditional() && Br == BB->begin(); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 263 | } |
| 264 | return false; |
| 265 | } |
| 266 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 267 | BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) { |
| 268 | if (BasicBlock *BB = PreHead->getSinglePredecessor()) { |
| 269 | BranchInst *Br = getBranch(BB); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 270 | return Br && Br->isConditional() ? BB : nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 271 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 272 | return nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 273 | } |
| 274 | |
| 275 | //===----------------------------------------------------------------------===// |
| 276 | // |
| 277 | // Implementation of NclPopcountRecognize |
| 278 | // |
| 279 | //===----------------------------------------------------------------------===// |
| 280 | |
| 281 | NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR): |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 282 | LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 283 | } |
| 284 | |
| 285 | bool NclPopcountRecognize::preliminaryScreen() { |
Chandler Carruth | 6fe147f | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 286 | const TargetTransformInfo *TTI = LIR.getTargetTransformInfo(); |
Chandler Carruth | 50a36cd | 2013-01-07 03:16:03 +0000 | [diff] [blame] | 287 | if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 288 | return false; |
| 289 | |
Robert Wilhelm | 2788d3e | 2013-09-28 13:42:22 +0000 | [diff] [blame] | 290 | // Counting population are usually conducted by few arithmetic instructions. |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 291 | // Such instructions can be easilly "absorbed" by vacant slots in a |
| 292 | // non-compact loop. Therefore, recognizing popcount idiom only makes sense |
| 293 | // in a compact loop. |
| 294 | |
| 295 | // Give up if the loop has multiple blocks or multiple backedges. |
| 296 | if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1) |
| 297 | return false; |
| 298 | |
| 299 | BasicBlock *LoopBody = *(CurLoop->block_begin()); |
| 300 | if (LoopBody->size() >= 20) { |
| 301 | // The loop is too big, bail out. |
| 302 | return false; |
| 303 | } |
| 304 | |
| 305 | // It should have a preheader containing nothing but a goto instruction. |
| 306 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 307 | if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead)) |
| 308 | return false; |
| 309 | |
| 310 | // It should have a precondition block where the generated popcount instrinsic |
| 311 | // function will be inserted. |
| 312 | PreCondBB = LIRUtil::getPrecondBb(PreHead); |
| 313 | if (!PreCondBB) |
| 314 | return false; |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 315 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 316 | return true; |
| 317 | } |
| 318 | |
Jim Grosbach | 708f80f | 2014-04-29 22:41:58 +0000 | [diff] [blame] | 319 | Value *NclPopcountRecognize::matchCondition(BranchInst *Br, |
| 320 | BasicBlock *LoopEntry) const { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 321 | if (!Br || !Br->isConditional()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 322 | return nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 323 | |
| 324 | ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition()); |
| 325 | if (!Cond) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 326 | return nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 327 | |
| 328 | ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1)); |
| 329 | if (!CmpZero || !CmpZero->isZero()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 330 | return nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 331 | |
| 332 | ICmpInst::Predicate Pred = Cond->getPredicate(); |
| 333 | if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) || |
| 334 | (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry)) |
| 335 | return Cond->getOperand(0); |
| 336 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 337 | return nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 338 | } |
| 339 | |
| 340 | bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst, |
| 341 | PHINode *&CntPhi, |
| 342 | Value *&Var) const { |
| 343 | // Following code tries to detect this idiom: |
| 344 | // |
| 345 | // if (x0 != 0) |
| 346 | // goto loop-exit // the precondition of the loop |
| 347 | // cnt0 = init-val; |
| 348 | // do { |
| 349 | // x1 = phi (x0, x2); |
| 350 | // cnt1 = phi(cnt0, cnt2); |
| 351 | // |
| 352 | // cnt2 = cnt1 + 1; |
| 353 | // ... |
| 354 | // x2 = x1 & (x1 - 1); |
| 355 | // ... |
| 356 | // } while(x != 0); |
| 357 | // |
| 358 | // loop-exit: |
| 359 | // |
| 360 | |
| 361 | // step 1: Check to see if the look-back branch match this pattern: |
| 362 | // "if (a!=0) goto loop-entry". |
| 363 | BasicBlock *LoopEntry; |
| 364 | Instruction *DefX2, *CountInst; |
| 365 | Value *VarX1, *VarX0; |
| 366 | PHINode *PhiX, *CountPhi; |
| 367 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 368 | DefX2 = CountInst = nullptr; |
| 369 | VarX1 = VarX0 = nullptr; |
| 370 | PhiX = CountPhi = nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 371 | LoopEntry = *(CurLoop->block_begin()); |
| 372 | |
| 373 | // step 1: Check if the loop-back branch is in desirable form. |
| 374 | { |
| 375 | if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry)) |
| 376 | DefX2 = dyn_cast<Instruction>(T); |
| 377 | else |
| 378 | return false; |
| 379 | } |
| 380 | |
| 381 | // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)" |
| 382 | { |
Shuxin Yang | c5c730b | 2013-01-10 23:32:01 +0000 | [diff] [blame] | 383 | if (!DefX2 || DefX2->getOpcode() != Instruction::And) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 384 | return false; |
| 385 | |
| 386 | BinaryOperator *SubOneOp; |
| 387 | |
| 388 | if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0)))) |
| 389 | VarX1 = DefX2->getOperand(1); |
| 390 | else { |
| 391 | VarX1 = DefX2->getOperand(0); |
| 392 | SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1)); |
| 393 | } |
| 394 | if (!SubOneOp) |
| 395 | return false; |
| 396 | |
| 397 | Instruction *SubInst = cast<Instruction>(SubOneOp); |
| 398 | ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1)); |
| 399 | if (!Dec || |
| 400 | !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) || |
| 401 | (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) { |
| 402 | return false; |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | // step 3: Check the recurrence of variable X |
| 407 | { |
| 408 | PhiX = dyn_cast<PHINode>(VarX1); |
| 409 | if (!PhiX || |
| 410 | (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) { |
| 411 | return false; |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1 |
| 416 | { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 417 | CountInst = nullptr; |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 418 | for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(), |
| 419 | IterE = LoopEntry->end(); Iter != IterE; Iter++) { |
| 420 | Instruction *Inst = Iter; |
| 421 | if (Inst->getOpcode() != Instruction::Add) |
| 422 | continue; |
| 423 | |
| 424 | ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 425 | if (!Inc || !Inc->isOne()) |
| 426 | continue; |
| 427 | |
| 428 | PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0)); |
| 429 | if (!Phi || Phi->getParent() != LoopEntry) |
| 430 | continue; |
| 431 | |
| 432 | // Check if the result of the instruction is live of the loop. |
| 433 | bool LiveOutLoop = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 434 | for (User *U : Inst->users()) { |
| 435 | if ((cast<Instruction>(U))->getParent() != LoopEntry) { |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 436 | LiveOutLoop = true; break; |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | if (LiveOutLoop) { |
| 441 | CountInst = Inst; |
| 442 | CountPhi = Phi; |
| 443 | break; |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | if (!CountInst) |
| 448 | return false; |
| 449 | } |
| 450 | |
| 451 | // step 5: check if the precondition is in this form: |
| 452 | // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;" |
| 453 | { |
| 454 | BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB); |
| 455 | Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader()); |
| 456 | if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1)) |
| 457 | return false; |
| 458 | |
| 459 | CntInst = CountInst; |
| 460 | CntPhi = CountPhi; |
| 461 | Var = T; |
| 462 | } |
| 463 | |
| 464 | return true; |
| 465 | } |
| 466 | |
| 467 | void NclPopcountRecognize::transform(Instruction *CntInst, |
| 468 | PHINode *CntPhi, Value *Var) { |
| 469 | |
| 470 | ScalarEvolution *SE = LIR.getScalarEvolution(); |
| 471 | TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo(); |
| 472 | BasicBlock *PreHead = CurLoop->getLoopPreheader(); |
| 473 | BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB); |
| 474 | const DebugLoc DL = CntInst->getDebugLoc(); |
| 475 | |
| 476 | // Assuming before transformation, the loop is following: |
| 477 | // if (x) // the precondition |
| 478 | // do { cnt++; x &= x - 1; } while(x); |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 479 | |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 480 | // Step 1: Insert the ctpop instruction at the end of the precondition block |
| 481 | IRBuilderTy Builder(PreCondBr); |
| 482 | Value *PopCnt, *PopCntZext, *NewCount, *TripCnt; |
| 483 | { |
| 484 | PopCnt = createPopcntIntrinsic(Builder, Var, DL); |
| 485 | NewCount = PopCntZext = |
| 486 | Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType())); |
| 487 | |
| 488 | if (NewCount != PopCnt) |
| 489 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 490 | |
| 491 | // TripCnt is exactly the number of iterations the loop has |
| 492 | TripCnt = NewCount; |
| 493 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 494 | // If the population counter's initial value is not zero, insert Add Inst. |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 495 | Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead); |
| 496 | ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal); |
| 497 | if (!InitConst || !InitConst->isZero()) { |
| 498 | NewCount = Builder.CreateAdd(NewCount, CntInitVal); |
| 499 | (cast<Instruction>(NewCount))->setDebugLoc(DL); |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to |
| 504 | // "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic |
| 505 | // function would be partial dead code, and downstream passes will drag |
| 506 | // it back from the precondition block to the preheader. |
| 507 | { |
| 508 | ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition()); |
| 509 | |
| 510 | Value *Opnd0 = PopCntZext; |
| 511 | Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0); |
| 512 | if (PreCond->getOperand(0) != Var) |
| 513 | std::swap(Opnd0, Opnd1); |
| 514 | |
| 515 | ICmpInst *NewPreCond = |
| 516 | cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1)); |
| 517 | PreCond->replaceAllUsesWith(NewPreCond); |
| 518 | |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 519 | RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 520 | } |
| 521 | |
| 522 | // Step 3: Note that the population count is exactly the trip count of the |
| 523 | // loop in question, which enble us to to convert the loop from noncountable |
| 524 | // loop into a countable one. The benefit is twofold: |
| 525 | // |
| 526 | // - If the loop only counts population, the entire loop become dead after |
| 527 | // the transformation. It is lots easier to prove a countable loop dead |
| 528 | // than to prove a noncountable one. (In some C dialects, a infite loop |
| 529 | // isn't dead even if it computes nothing useful. In general, DCE needs |
| 530 | // to prove a noncountable loop finite before safely delete it.) |
| 531 | // |
| 532 | // - If the loop also performs something else, it remains alive. |
| 533 | // Since it is transformed to countable form, it can be aggressively |
| 534 | // optimized by some optimizations which are in general not applicable |
| 535 | // to a noncountable loop. |
| 536 | // |
| 537 | // After this step, this loop (conceptually) would look like following: |
| 538 | // newcnt = __builtin_ctpop(x); |
| 539 | // t = newcnt; |
| 540 | // if (x) |
| 541 | // do { cnt++; x &= x-1; t--) } while (t > 0); |
| 542 | BasicBlock *Body = *(CurLoop->block_begin()); |
| 543 | { |
| 544 | BranchInst *LbBr = LIRUtil::getBranch(Body); |
| 545 | ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition()); |
| 546 | Type *Ty = TripCnt->getType(); |
| 547 | |
| 548 | PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin()); |
| 549 | |
| 550 | Builder.SetInsertPoint(LbCond); |
| 551 | Value *Opnd1 = cast<Value>(TcPhi); |
| 552 | Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1)); |
| 553 | Instruction *TcDec = |
| 554 | cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true)); |
| 555 | |
| 556 | TcPhi->addIncoming(TripCnt, PreHead); |
| 557 | TcPhi->addIncoming(TcDec, Body); |
| 558 | |
| 559 | CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ? |
| 560 | CmpInst::ICMP_UGT : CmpInst::ICMP_SLE; |
| 561 | LbCond->setPredicate(Pred); |
| 562 | LbCond->setOperand(0, TcDec); |
| 563 | LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0))); |
| 564 | } |
| 565 | |
| 566 | // Step 4: All the references to the original population counter outside |
| 567 | // the loop are replaced with the NewCount -- the value returned from |
| 568 | // __builtin_ctpop(). |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 569 | CntInst->replaceUsesOutsideBlock(NewCount, Body); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 570 | |
| 571 | // step 5: Forget the "non-computable" trip-count SCEV associated with the |
| 572 | // loop. The loop would otherwise not be deleted even if it becomes empty. |
| 573 | SE->forgetLoop(CurLoop); |
| 574 | } |
| 575 | |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 576 | CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder, |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 577 | Value *Val, DebugLoc DL) { |
| 578 | Value *Ops[] = { Val }; |
| 579 | Type *Tys[] = { Val->getType() }; |
| 580 | |
| 581 | Module *M = (*(CurLoop->block_begin()))->getParent()->getParent(); |
| 582 | Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys); |
| 583 | CallInst *CI = IRBuilder.CreateCall(Func, Ops); |
| 584 | CI->setDebugLoc(DL); |
| 585 | |
| 586 | return CI; |
| 587 | } |
| 588 | |
| 589 | /// recognize - detect population count idiom in a non-countable loop. If |
| 590 | /// detected, transform the relevant code to popcount intrinsic function |
| 591 | /// call, and return true; otherwise, return false. |
| 592 | bool NclPopcountRecognize::recognize() { |
| 593 | |
Chandler Carruth | 6fe147f | 2013-01-05 10:00:09 +0000 | [diff] [blame] | 594 | if (!LIR.getTargetTransformInfo()) |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 595 | return false; |
| 596 | |
| 597 | LIR.getScalarEvolution(); |
| 598 | |
| 599 | if (!preliminaryScreen()) |
| 600 | return false; |
| 601 | |
| 602 | Instruction *CntInst; |
| 603 | PHINode *CntPhi; |
| 604 | Value *Val; |
| 605 | if (!detectIdiom(CntInst, CntPhi, Val)) |
| 606 | return false; |
| 607 | |
| 608 | transform(CntInst, CntPhi, Val); |
| 609 | return true; |
| 610 | } |
| 611 | |
| 612 | //===----------------------------------------------------------------------===// |
| 613 | // |
| 614 | // Implementation of LoopIdiomRecognize |
| 615 | // |
| 616 | //===----------------------------------------------------------------------===// |
| 617 | |
| 618 | bool LoopIdiomRecognize::runOnCountableLoop() { |
| 619 | const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop); |
| 620 | if (isa<SCEVCouldNotCompute>(BECount)) return false; |
| 621 | |
| 622 | // If this loop executes exactly one time, then it should be peeled, not |
| 623 | // optimized by this pass. |
| 624 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
| 625 | if (BECst->getValue()->getValue() == 0) |
| 626 | return false; |
| 627 | |
| 628 | // We require target data for now. |
| 629 | if (!getDataLayout()) |
| 630 | return false; |
| 631 | |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 632 | // set DT |
Shuxin Yang | 98c844f | 2013-01-02 18:26:31 +0000 | [diff] [blame] | 633 | (void)getDominatorTree(); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 634 | |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 635 | LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 636 | TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 637 | |
Matt Arsenault | fb18323 | 2013-07-22 18:59:58 +0000 | [diff] [blame] | 638 | // set TLI |
Shuxin Yang | 98c844f | 2013-01-02 18:26:31 +0000 | [diff] [blame] | 639 | (void)getTargetLibraryInfo(); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 640 | |
| 641 | SmallVector<BasicBlock*, 8> ExitBlocks; |
| 642 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 643 | |
| 644 | DEBUG(dbgs() << "loop-idiom Scanning: F[" |
| 645 | << CurLoop->getHeader()->getParent()->getName() |
| 646 | << "] Loop %" << CurLoop->getHeader()->getName() << "\n"); |
| 647 | |
| 648 | bool MadeChange = false; |
| 649 | // Scan all the blocks in the loop that are not in subloops. |
| 650 | for (Loop::block_iterator BI = CurLoop->block_begin(), |
| 651 | E = CurLoop->block_end(); BI != E; ++BI) { |
| 652 | // Ignore blocks in subloops. |
| 653 | if (LI.getLoopFor(*BI) != CurLoop) |
| 654 | continue; |
| 655 | |
| 656 | MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks); |
| 657 | } |
| 658 | return MadeChange; |
| 659 | } |
| 660 | |
| 661 | bool LoopIdiomRecognize::runOnNoncountableLoop() { |
| 662 | NclPopcountRecognize Popcount(*this); |
| 663 | if (Popcount.recognize()) |
| 664 | return true; |
| 665 | |
| 666 | return false; |
| 667 | } |
| 668 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 669 | bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) { |
Paul Robinson | af4e64d | 2014-02-06 00:07:05 +0000 | [diff] [blame] | 670 | if (skipOptnoneFunction(L)) |
| 671 | return false; |
| 672 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 673 | CurLoop = L; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 674 | |
Benjamin Kramer | eba9aca | 2012-09-21 17:27:23 +0000 | [diff] [blame] | 675 | // If the loop could not be converted to canonical form, it must have an |
| 676 | // indirectbr in it, just give up. |
| 677 | if (!L->getLoopPreheader()) |
| 678 | return false; |
| 679 | |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 680 | // Disable loop idiom recognition if the function's name is a common idiom. |
Chad Rosier | a7ff543 | 2011-07-15 18:25:04 +0000 | [diff] [blame] | 681 | StringRef Name = L->getHeader()->getParent()->getName(); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 682 | if (Name == "memset" || Name == "memcpy") |
Chad Rosier | a7ff543 | 2011-07-15 18:25:04 +0000 | [diff] [blame] | 683 | return false; |
| 684 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 685 | SE = &getAnalysis<ScalarEvolution>(); |
Shuxin Yang | 95de7c3 | 2012-12-09 03:12:46 +0000 | [diff] [blame] | 686 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) |
| 687 | return runOnCountableLoop(); |
| 688 | return runOnNoncountableLoop(); |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 689 | } |
| 690 | |
| 691 | /// runOnLoopBlock - Process the specified block, which lives in a counted loop |
| 692 | /// with the specified backedge count. This block is known to be in the current |
| 693 | /// loop and not in any subloops. |
| 694 | bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount, |
| 695 | SmallVectorImpl<BasicBlock*> &ExitBlocks) { |
| 696 | // We can only promote stores in this block if they are unconditionally |
| 697 | // executed in the loop. For a block to be unconditionally executed, it has |
| 698 | // to dominate all the exit blocks of the loop. Verify this now. |
| 699 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) |
| 700 | if (!DT->dominates(BB, ExitBlocks[i])) |
| 701 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 702 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 703 | bool MadeChange = false; |
| 704 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
Chris Lattner | a62b01d | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 705 | Instruction *Inst = I++; |
| 706 | // Look for store instructions, which may be optimized to memset/memcpy. |
| 707 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
Chris Lattner | a62b01d | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 708 | WeakVH InstPtr(I); |
| 709 | if (!processLoopStore(SI, BECount)) continue; |
| 710 | MadeChange = true; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 711 | |
Chris Lattner | a62b01d | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 712 | // If processing the store invalidated our iterator, start over from the |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 713 | // top of the block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 714 | if (!InstPtr) |
Chris Lattner | a62b01d | 2011-01-04 07:27:30 +0000 | [diff] [blame] | 715 | I = BB->begin(); |
| 716 | continue; |
| 717 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 718 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 719 | // Look for memset instructions, which may be optimized to a larger memset. |
| 720 | if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) { |
| 721 | WeakVH InstPtr(I); |
| 722 | if (!processLoopMemSet(MSI, BECount)) continue; |
| 723 | MadeChange = true; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 724 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 725 | // If processing the memset invalidated our iterator, start over from the |
| 726 | // top of the block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 727 | if (!InstPtr) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 728 | I = BB->begin(); |
| 729 | continue; |
| 730 | } |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 731 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 732 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 733 | return MadeChange; |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 734 | } |
| 735 | |
Chris Lattner | 8455b6e | 2011-01-02 19:01:03 +0000 | [diff] [blame] | 736 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 737 | /// processLoopStore - See if this store can be promoted to a memset or memcpy. |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 738 | bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) { |
Eli Friedman | 7c5dc12 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 739 | if (!SI->isSimple()) return false; |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 740 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 741 | Value *StoredVal = SI->getValueOperand(); |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 742 | Value *StorePtr = SI->getPointerOperand(); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 743 | |
Chris Lattner | 65a699d | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 744 | // Reject stores that are so large that they overflow an unsigned. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 745 | uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); |
Chris Lattner | 65a699d | 2010-12-28 18:53:48 +0000 | [diff] [blame] | 746 | if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 747 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 748 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 749 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 750 | // loop, which indicates a strided store. If we have something else, it's a |
| 751 | // random store we can't handle. |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 752 | const SCEVAddRecExpr *StoreEv = |
| 753 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 754 | if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 755 | return false; |
| 756 | |
| 757 | // Check to see if the stride matches the size of the store. If so, then we |
| 758 | // know that every byte is touched in the loop. |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 759 | unsigned StoreSize = (unsigned)SizeInBits >> 3; |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 760 | const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1)); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 761 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 762 | if (!Stride || StoreSize != Stride->getValue()->getValue()) { |
Chris Lattner | bc661d6 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 763 | // TODO: Could also handle negative stride here someday, that will require |
| 764 | // the validity check in mayLoopAccessLocation to be updated though. |
| 765 | // Enable this to print exact negative strides. |
Chris Lattner | 2333ac2 | 2011-02-21 17:02:55 +0000 | [diff] [blame] | 766 | if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) { |
Chris Lattner | bc661d6 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 767 | dbgs() << "NEGATIVE STRIDE: " << *SI << "\n"; |
| 768 | dbgs() << "BB: " << *SI->getParent(); |
| 769 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 770 | |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 771 | return false; |
Chris Lattner | bc661d6 | 2011-02-21 02:08:54 +0000 | [diff] [blame] | 772 | } |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 773 | |
| 774 | // See if we can optimize just this store in isolation. |
| 775 | if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(), |
| 776 | StoredVal, SI, StoreEv, BECount)) |
| 777 | return true; |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 778 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 779 | // If the stored value is a strided load in the same loop with the same stride |
| 780 | // this this may be transformable into a memcpy. This kicks in for stuff like |
| 781 | // for (i) A[i] = B[i]; |
| 782 | if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { |
| 783 | const SCEVAddRecExpr *LoadEv = |
| 784 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0))); |
| 785 | if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() && |
Eli Friedman | 7c5dc12 | 2011-09-12 20:23:13 +0000 | [diff] [blame] | 786 | StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple()) |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 787 | if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount)) |
| 788 | return true; |
| 789 | } |
Chris Lattner | 12f91be | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 790 | //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n"; |
Chris Lattner | 7c5f9c3 | 2010-12-26 20:45:45 +0000 | [diff] [blame] | 791 | |
Chris Lattner | 81ae3f2 | 2010-12-26 19:39:38 +0000 | [diff] [blame] | 792 | return false; |
| 793 | } |
| 794 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 795 | /// processLoopMemSet - See if this memset can be promoted to a large memset. |
| 796 | bool LoopIdiomRecognize:: |
| 797 | processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) { |
| 798 | // We can only handle non-volatile memsets with a constant size. |
| 799 | if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false; |
| 800 | |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 801 | // If we're not allowed to hack on memset, we fail. |
| 802 | if (!TLI->has(LibFunc::memset)) |
| 803 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 804 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 805 | Value *Pointer = MSI->getDest(); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 806 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 807 | // See if the pointer expression is an AddRec like {base,+,1} on the current |
| 808 | // loop, which indicates a strided store. If we have something else, it's a |
| 809 | // random store we can't handle. |
| 810 | const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 811 | if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine()) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 812 | return false; |
| 813 | |
| 814 | // Reject memsets that are so large that they overflow an unsigned. |
| 815 | uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
| 816 | if ((SizeInBytes >> 32) != 0) |
| 817 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 818 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 819 | // Check to see if the stride matches the size of the memset. If so, then we |
| 820 | // know that every byte is touched in the loop. |
| 821 | const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1)); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 822 | |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 823 | // TODO: Could also handle negative stride here someday, that will require the |
| 824 | // validity check in mayLoopAccessLocation to be updated though. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 825 | if (!Stride || MSI->getLength() != Stride->getValue()) |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 826 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 827 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 828 | return processLoopStridedStore(Pointer, (unsigned)SizeInBytes, |
| 829 | MSI->getAlignment(), MSI->getValue(), |
| 830 | MSI, Ev, BECount); |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 831 | } |
| 832 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 833 | |
| 834 | /// mayLoopAccessLocation - Return true if the specified loop might access the |
| 835 | /// specified pointer location, which is a loop-strided access. The 'Access' |
| 836 | /// argument specifies what the verboten forms of access are (read or write). |
| 837 | static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access, |
| 838 | Loop *L, const SCEV *BECount, |
| 839 | unsigned StoreSize, AliasAnalysis &AA, |
| 840 | Instruction *IgnoredStore) { |
| 841 | // Get the location that may be stored across the loop. Since the access is |
| 842 | // strided positively through memory, we say that the modified location starts |
| 843 | // at the pointer and has infinite size. |
| 844 | uint64_t AccessSize = AliasAnalysis::UnknownSize; |
| 845 | |
| 846 | // If the loop iterates a fixed number of times, we can refine the access size |
| 847 | // to be exactly the size of the memset, which is (BECount+1)*StoreSize |
| 848 | if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount)) |
| 849 | AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize; |
| 850 | |
| 851 | // TODO: For this to be really effective, we have to dive into the pointer |
| 852 | // operand in the store. Store to &A[i] of 100 will always return may alias |
| 853 | // with store of &A[100], we need to StoreLoc to be "A" with size of 100, |
| 854 | // which will then no-alias a store to &A[100]. |
| 855 | AliasAnalysis::Location StoreLoc(Ptr, AccessSize); |
| 856 | |
| 857 | for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E; |
| 858 | ++BI) |
| 859 | for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I) |
| 860 | if (&*I != IgnoredStore && |
| 861 | (AA.getModRefInfo(I, StoreLoc) & Access)) |
| 862 | return true; |
| 863 | |
| 864 | return false; |
| 865 | } |
| 866 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 867 | /// getMemSetPatternValue - If a strided store of the specified value is safe to |
| 868 | /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should |
| 869 | /// be passed in. Otherwise, return null. |
| 870 | /// |
| 871 | /// Note that we don't ever attempt to use memset_pattern8 or 4, because these |
| 872 | /// just replicate their input array and then pass on to memset_pattern16. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 873 | static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) { |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 874 | // If the value isn't a constant, we can't promote it to being in a constant |
| 875 | // array. We could theoretically do a store to an alloca or something, but |
| 876 | // that doesn't seem worthwhile. |
| 877 | Constant *C = dyn_cast<Constant>(V); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 878 | if (!C) return nullptr; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 879 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 880 | // Only handle simple values that are a power of two bytes in size. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 881 | uint64_t Size = DL.getTypeSizeInBits(V->getType()); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 882 | if (Size == 0 || (Size & 7) || (Size & (Size-1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 883 | return nullptr; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 884 | |
Chris Lattner | 72a35fb | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 885 | // Don't care enough about darwin/ppc to implement this. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 886 | if (DL.isBigEndian()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 887 | return nullptr; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 888 | |
| 889 | // Convert to size in bytes. |
| 890 | Size /= 8; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 891 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 892 | // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see |
Chris Lattner | 72a35fb | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 893 | // if the top and bottom are the same (e.g. for vectors and large integers). |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 894 | if (Size > 16) return nullptr; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 895 | |
Chris Lattner | 72a35fb | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 896 | // If the constant is exactly 16 bytes, just use it. |
| 897 | if (Size == 16) return C; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 898 | |
Chris Lattner | 72a35fb | 2011-02-19 19:56:44 +0000 | [diff] [blame] | 899 | // Otherwise, we'll use an array of the constants. |
| 900 | unsigned ArraySize = 16/Size; |
| 901 | ArrayType *AT = ArrayType::get(V->getType(), ArraySize); |
| 902 | return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C)); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 903 | } |
| 904 | |
| 905 | |
| 906 | /// processLoopStridedStore - We see a strided store of some value. If we can |
| 907 | /// transform this into a memset or memset_pattern in the loop preheader, do so. |
| 908 | bool LoopIdiomRecognize:: |
| 909 | processLoopStridedStore(Value *DestPtr, unsigned StoreSize, |
| 910 | unsigned StoreAlignment, Value *StoredVal, |
| 911 | Instruction *TheStore, const SCEVAddRecExpr *Ev, |
| 912 | const SCEV *BECount) { |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 913 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 914 | // If the stored value is a byte-wise value (like i32 -1), then it may be |
| 915 | // turned into a memset of i8 -1, assuming that all the consecutive bytes |
| 916 | // are stored. A store of i32 0x01020304 can never be turned into a memset, |
| 917 | // but it can be turned into memset_pattern if the target supports it. |
| 918 | Value *SplatValue = isBytewiseValue(StoredVal); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 919 | Constant *PatternValue = nullptr; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 920 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 921 | unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); |
| 922 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 923 | // If we're allowed to form a memset, and the stored value would be acceptable |
| 924 | // for memset, use it. |
| 925 | if (SplatValue && TLI->has(LibFunc::memset) && |
| 926 | // Verify that the stored value is loop invariant. If not, we can't |
| 927 | // promote the memset. |
| 928 | CurLoop->isLoopInvariant(SplatValue)) { |
| 929 | // Keep and use SplatValue. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 930 | PatternValue = nullptr; |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 931 | } else if (DestAS == 0 && |
| 932 | TLI->has(LibFunc::memset_pattern16) && |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 933 | (PatternValue = getMemSetPatternValue(StoredVal, *DL))) { |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 934 | // Don't create memset_pattern16s with address spaces. |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 935 | // It looks like we can use PatternValue! |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 936 | SplatValue = nullptr; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 937 | } else { |
| 938 | // Otherwise, this isn't an idiom we can transform. For example, we can't |
Eli Friedman | a93ab13 | 2011-09-13 00:44:16 +0000 | [diff] [blame] | 939 | // do anything with a 3-byte store. |
Chris Lattner | a351444 | 2011-01-01 20:12:04 +0000 | [diff] [blame] | 940 | return false; |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 941 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 942 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 943 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 944 | // guaranteed to be loop invariant, which means that it should dominate the |
| 945 | // header. This allows us to insert code for it in the preheader. |
| 946 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 947 | IRBuilder<> Builder(Preheader->getTerminator()); |
Andrew Trick | 411daa5 | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 948 | SCEVExpander Expander(*SE, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 949 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 950 | Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS); |
| 951 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 952 | // 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] | 953 | // this into a memset in the loop preheader now if we want. However, this |
| 954 | // 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] | 955 | // or write to the aliased location. Check for any overlap by generating the |
| 956 | // base pointer and checking the region. |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 957 | Value *BasePtr = |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 958 | Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy, |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 959 | Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 960 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 961 | if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef, |
| 962 | CurLoop, BECount, |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 963 | StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) { |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 964 | Expander.clear(); |
| 965 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 966 | RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 967 | return false; |
| 968 | } |
| 969 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 970 | // Okay, everything looks good, insert the memset. |
| 971 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 972 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 973 | // pointer size if it isn't already. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 974 | Type *IntPtr = Builder.getIntPtrTy(DL, DestAS); |
Chris Lattner | 0ba473c | 2011-01-04 00:06:55 +0000 | [diff] [blame] | 975 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 976 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 977 | const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 978 | SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 979 | if (StoreSize != 1) { |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 980 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 981 | SCEV::FlagNUW); |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 982 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 983 | |
| 984 | Value *NumBytes = |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 985 | Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 986 | |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 987 | CallInst *NewCall; |
Matt Arsenault | 5df49bd | 2013-09-11 05:09:35 +0000 | [diff] [blame] | 988 | if (SplatValue) { |
| 989 | NewCall = Builder.CreateMemSet(BasePtr, |
| 990 | SplatValue, |
| 991 | NumBytes, |
| 992 | StoreAlignment); |
| 993 | } else { |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 994 | // Everything is emitted in default address space |
| 995 | Type *Int8PtrTy = DestInt8PtrTy; |
| 996 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 997 | Module *M = TheStore->getParent()->getParent()->getParent(); |
| 998 | Value *MSP = M->getOrInsertFunction("memset_pattern16", |
| 999 | Builder.getVoidTy(), |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1000 | Int8PtrTy, |
| 1001 | Int8PtrTy, |
| 1002 | IntPtr, |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1003 | (void*)nullptr); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1004 | |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1005 | // Otherwise we should form a memset_pattern16. PatternValue is known to be |
| 1006 | // an constant array of 16-bytes. Plop the value into a mergable global. |
| 1007 | GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true, |
| 1008 | GlobalValue::InternalLinkage, |
| 1009 | PatternValue, ".memset_pattern"); |
| 1010 | GV->setUnnamedAddr(true); // Ok to merge these. |
| 1011 | GV->setAlignment(16); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1012 | Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy); |
Chris Lattner | 0f4a640 | 2011-02-19 19:31:39 +0000 | [diff] [blame] | 1013 | NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes); |
| 1014 | } |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1015 | |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1016 | DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n" |
Chris Lattner | 8643810 | 2011-01-04 07:46:33 +0000 | [diff] [blame] | 1017 | << " from store to: " << *Ev << " at: " << *TheStore << "\n"); |
Devang Patel | d00c628 | 2011-03-07 22:43:45 +0000 | [diff] [blame] | 1018 | NewCall->setDebugLoc(TheStore->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1019 | |
Chris Lattner | b9fe685 | 2010-12-27 00:03:23 +0000 | [diff] [blame] | 1020 | // Okay, the memset has been formed. Zap the original store and anything that |
| 1021 | // feeds into it. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 1022 | deleteDeadInstruction(TheStore, TLI); |
Chris Lattner | 12f91be | 2011-01-02 07:36:44 +0000 | [diff] [blame] | 1023 | ++NumMemSet; |
Chris Lattner | 29e14ed | 2010-12-26 23:42:51 +0000 | [diff] [blame] | 1024 | return true; |
| 1025 | } |
| 1026 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1027 | /// processLoopStoreOfLoopLoad - We see a strided store whose value is a |
| 1028 | /// same-strided load. |
| 1029 | bool LoopIdiomRecognize:: |
| 1030 | processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize, |
| 1031 | const SCEVAddRecExpr *StoreEv, |
| 1032 | const SCEVAddRecExpr *LoadEv, |
| 1033 | const SCEV *BECount) { |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 1034 | // If we're not allowed to form memcpy, we fail. |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1035 | if (!TLI->has(LibFunc::memcpy)) |
Chris Lattner | e6b261f | 2011-02-18 22:22:15 +0000 | [diff] [blame] | 1036 | return false; |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1037 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1038 | LoadInst *LI = cast<LoadInst>(SI->getValueOperand()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1039 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1040 | // The trip count of the loop and the base pointer of the addrec SCEV is |
| 1041 | // guaranteed to be loop invariant, which means that it should dominate the |
| 1042 | // header. This allows us to insert code for it in the preheader. |
| 1043 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
| 1044 | IRBuilder<> Builder(Preheader->getTerminator()); |
Andrew Trick | 411daa5 | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 1045 | SCEVExpander Expander(*SE, "loop-idiom"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1046 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1047 | // 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] | 1048 | // this into a memcpy in the loop preheader now if we want. However, this |
| 1049 | // would be unsafe to do if there is anything else in the loop that may read |
| 1050 | // or write the memory region we're storing to. This includes the load that |
| 1051 | // feeds the stores. Check for an alias by generating the base address and |
| 1052 | // checking everything. |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1053 | Value *StoreBasePtr = |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1054 | Expander.expandCodeFor(StoreEv->getStart(), |
| 1055 | Builder.getInt8PtrTy(SI->getPointerAddressSpace()), |
| 1056 | Preheader->getTerminator()); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1057 | |
| 1058 | if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef, |
| 1059 | CurLoop, BECount, StoreSize, |
| 1060 | getAnalysis<AliasAnalysis>(), SI)) { |
| 1061 | Expander.clear(); |
| 1062 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 1063 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1064 | return false; |
| 1065 | } |
| 1066 | |
| 1067 | // For a memcpy, we have to make sure that the input array is not being |
| 1068 | // mutated by the loop. |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1069 | Value *LoadBasePtr = |
| 1070 | Expander.expandCodeFor(LoadEv->getStart(), |
| 1071 | Builder.getInt8PtrTy(LI->getPointerAddressSpace()), |
| 1072 | Preheader->getTerminator()); |
| 1073 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1074 | if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount, |
| 1075 | StoreSize, getAnalysis<AliasAnalysis>(), SI)) { |
| 1076 | Expander.clear(); |
| 1077 | // If we generated new code for the base pointer, clean up. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 1078 | RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI); |
| 1079 | RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1080 | return false; |
| 1081 | } |
| 1082 | |
Chris Lattner | c4ca7ab | 2011-05-22 17:39:56 +0000 | [diff] [blame] | 1083 | // Okay, everything is safe, we can transform this! |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1084 | |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1085 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1086 | // The # stored bytes is (BECount+1)*Size. Expand the trip count out to |
| 1087 | // pointer size if it isn't already. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1088 | Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace()); |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1089 | BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1090 | |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1091 | const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1092 | SCEV::FlagNUW); |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1093 | if (StoreSize != 1) |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1094 | NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1095 | SCEV::FlagNUW); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1096 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1097 | Value *NumBytes = |
Matt Arsenault | 009faed | 2013-09-11 05:09:42 +0000 | [diff] [blame] | 1098 | Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1099 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1100 | CallInst *NewCall = |
| 1101 | Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, |
| 1102 | std::min(SI->getAlignment(), LI->getAlignment())); |
Devang Patel | 0daa07e | 2011-05-04 21:37:05 +0000 | [diff] [blame] | 1103 | NewCall->setDebugLoc(SI->getDebugLoc()); |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1104 | |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1105 | DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n" |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1106 | << " from load ptr=" << *LoadEv << " at: " << *LI << "\n" |
| 1107 | << " from store ptr=" << *StoreEv << " at: " << *SI << "\n"); |
Andrew Trick | 60ab3ef | 2011-06-28 05:04:16 +0000 | [diff] [blame] | 1108 | |
Andrew Trick | 328b223 | 2011-03-14 16:48:10 +0000 | [diff] [blame] | 1109 | |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1110 | // Okay, the memset has been formed. Zap the original store and anything that |
| 1111 | // feeds into it. |
Benjamin Kramer | f094d77 | 2015-02-07 21:37:08 +0000 | [diff] [blame^] | 1112 | deleteDeadInstruction(SI, TLI); |
Chandler Carruth | 099f5cb0 | 2012-11-02 08:33:25 +0000 | [diff] [blame] | 1113 | ++NumMemCpy; |
Chris Lattner | 85b6d81 | 2011-01-02 03:37:56 +0000 | [diff] [blame] | 1114 | return true; |
| 1115 | } |