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