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