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