Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 1 | //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | c051768 | 2003-12-09 17:18:00 +0000 | [diff] [blame] | 10 | // This pass performs loop invariant code motion, attempting to remove as much |
| 11 | // code from the body of a loop as possible. It does this by either hoisting |
| 12 | // code into the preheader block, or by sinking code to the exit blocks if it is |
| 13 | // safe. This pass also promotes must-aliased memory locations in the loop to |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 14 | // live in registers, thus hoisting and sinking "invariant" loads and stores. |
Chris Lattner | c051768 | 2003-12-09 17:18:00 +0000 | [diff] [blame] | 15 | // |
| 16 | // This pass uses alias analysis for two purposes: |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 17 | // |
Chris Lattner | 289ba2a | 2004-05-23 21:20:19 +0000 | [diff] [blame] | 18 | // 1. Moving loop invariant loads and calls out of loops. If we can determine |
| 19 | // that a load or call inside of a loop never aliases anything stored to, |
| 20 | // we can hoist it or sink it like any other instruction. |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 21 | // 2. Scalar Promotion of Memory - If there is a store instruction inside of |
| 22 | // the loop, we try to move the store to happen AFTER the loop instead of |
| 23 | // inside of the loop. This can only happen if a few conditions are true: |
| 24 | // A. The pointer stored through is loop invariant |
| 25 | // B. There are no stores or loads in the loop which _may_ alias the |
| 26 | // pointer. There are no calls in the loop which mod/ref the pointer. |
| 27 | // If these conditions are true, we can promote the loads and stores in the |
| 28 | // loop of the pointer to use a temporary alloca'd variable. We then use |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 29 | // the SSAUpdater to construct the appropriate SSA form for the value. |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 30 | // |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 31 | //===----------------------------------------------------------------------===// |
| 32 | |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 33 | #include "llvm/Transforms/Scalar/LICM.h" |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 34 | #include "llvm/ADT/SetOperations.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 35 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | a51fa88 | 2002-08-22 21:39:55 +0000 | [diff] [blame] | 36 | #include "llvm/Analysis/AliasAnalysis.h" |
Chris Lattner | 0592bb7 | 2003-03-03 23:32:45 +0000 | [diff] [blame] | 37 | #include "llvm/Analysis/AliasSetTracker.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 38 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 39 | #include "llvm/Analysis/CaptureTracking.h" |
Chris Lattner | 030f020 | 2010-08-31 23:00:16 +0000 | [diff] [blame] | 40 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 41 | #include "llvm/Analysis/GlobalsModRef.h" |
Max Kazantsev | 3c284bd | 2018-08-30 03:39:16 +0000 | [diff] [blame] | 42 | #include "llvm/Analysis/GuardUtils.h" |
Philip Reames | e0a5454 | 2016-03-09 23:07:53 +0000 | [diff] [blame] | 43 | #include "llvm/Analysis/Loads.h" |
Chris Lattner | 030f020 | 2010-08-31 23:00:16 +0000 | [diff] [blame] | 44 | #include "llvm/Analysis/LoopInfo.h" |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/LoopIterator.h" |
Chris Lattner | 030f020 | 2010-08-31 23:00:16 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/LoopPass.h" |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/MemoryBuiltins.h" |
Alina Sbirlea | ff8b8ae | 2017-11-21 15:45:46 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/MemorySSA.h" |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/MemorySSAUpdater.h" |
Adam Nemet | 0965da2 | 2017-10-09 23:19:02 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
Chandler Carruth | abfa3e5 | 2014-01-24 01:59:49 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/ScalarEvolution.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 52 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 53 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 75d7d5e | 2011-12-14 23:49:11 +0000 | [diff] [blame] | 54 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 55 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 56 | #include "llvm/IR/Constants.h" |
| 57 | #include "llvm/IR/DataLayout.h" |
| 58 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 59 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 60 | #include "llvm/IR/Instructions.h" |
| 61 | #include "llvm/IR/IntrinsicInst.h" |
| 62 | #include "llvm/IR/LLVMContext.h" |
Chris Lattner | 473988c | 2013-01-05 16:44:07 +0000 | [diff] [blame] | 63 | #include "llvm/IR/Metadata.h" |
Max Kazantsev | 097ef69 | 2018-08-21 08:11:31 +0000 | [diff] [blame] | 64 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | aa0ab63 | 2014-03-04 12:09:19 +0000 | [diff] [blame] | 65 | #include "llvm/IR/PredIteratorCache.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 66 | #include "llvm/Support/CommandLine.h" |
| 67 | #include "llvm/Support/Debug.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 68 | #include "llvm/Support/raw_ostream.h" |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 69 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 3bab7e1 | 2017-01-11 09:43:56 +0000 | [diff] [blame] | 70 | #include "llvm/Transforms/Scalar/LoopPassManager.h" |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 71 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 72 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 73 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 74 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 75 | #include <algorithm> |
Benjamin Kramer | 82de7d3 | 2016-05-27 14:27:24 +0000 | [diff] [blame] | 76 | #include <utility> |
Chris Lattner | c051768 | 2003-12-09 17:18:00 +0000 | [diff] [blame] | 77 | using namespace llvm; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 78 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 79 | #define DEBUG_TYPE "licm" |
| 80 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 81 | STATISTIC(NumCreatedBlocks, "Number of blocks created"); |
| 82 | STATISTIC(NumClonedBranches, "Number of branches cloned"); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 83 | STATISTIC(NumSunk, "Number of instructions sunk out of loop"); |
| 84 | STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 85 | STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); |
| 86 | STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 87 | STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 88 | |
Xin Tong | ccee0e0 | 2017-02-21 20:53:48 +0000 | [diff] [blame] | 89 | /// Memory promotion is enabled by default. |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 90 | static cl::opt<bool> |
Xin Tong | ccee0e0 | 2017-02-21 20:53:48 +0000 | [diff] [blame] | 91 | DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 92 | cl::desc("Disable memory promotion in LICM pass")); |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 93 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 94 | static cl::opt<bool> ControlFlowHoisting( |
| 95 | "licm-control-flow-hoisting", cl::Hidden, cl::init(false), |
| 96 | cl::desc("Enable control flow (and PHI) hoisting in LICM")); |
| 97 | |
Anna Thomas | 7f4b26e | 2017-02-02 13:22:03 +0000 | [diff] [blame] | 98 | static cl::opt<uint32_t> MaxNumUsesTraversed( |
| 99 | "licm-max-num-uses-traversed", cl::Hidden, cl::init(8), |
| 100 | cl::desc("Max num uses visited for identifying load " |
| 101 | "invariance in loop using invariant start (default = 8)")); |
| 102 | |
Anna Thomas | 1962621 | 2018-08-17 13:44:00 +0000 | [diff] [blame] | 103 | // Default value of zero implies we use the regular alias set tracker mechanism |
| 104 | // instead of the cross product using AA to identify aliasing of the memory |
| 105 | // location we are interested in. |
| 106 | static cl::opt<int> |
| 107 | LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0), |
| 108 | cl::desc("How many instruction to cross product using AA")); |
| 109 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 110 | // Experimental option to allow imprecision in LICM (use MemorySSA cap) in |
| 111 | // pathological cases, in exchange for faster compile. This is to be removed |
| 112 | // if MemorySSA starts to address the same issue. This flag applies only when |
| 113 | // LICM uses MemorySSA instead on AliasSetTracker. When the flag is disabled |
| 114 | // (default), LICM calls MemorySSAWalker's getClobberingMemoryAccess, which |
| 115 | // gets perfect accuracy. When flag is enabled, LICM will call into MemorySSA's |
| 116 | // getDefiningAccess, which may not be precise, since optimizeUses is capped. |
| 117 | static cl::opt<bool> EnableLicmCap( |
| 118 | "enable-licm-cap", cl::init(false), cl::Hidden, |
| 119 | cl::desc("Enable imprecision in LICM (uses MemorySSA cap) in " |
| 120 | "pathological cases, in exchange for faster compile")); |
| 121 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 122 | static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 123 | static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, |
| 124 | const LoopSafetyInfo *SafetyInfo, |
| 125 | TargetTransformInfo *TTI, bool &FreeInLoop); |
Max Kazantsev | 68290f8 | 2018-08-15 02:49:12 +0000 | [diff] [blame] | 126 | static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 127 | BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 128 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 129 | static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 130 | const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 131 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE, |
| 132 | bool FreeInLoop); |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 133 | static bool isSafeToExecuteUnconditionally(Instruction &Inst, |
Pete Cooper | 0cabcf2 | 2015-05-13 01:12:18 +0000 | [diff] [blame] | 134 | const DominatorTree *DT, |
| 135 | const Loop *CurLoop, |
Evgeniy Stepanov | 122f984 | 2016-06-10 20:03:17 +0000 | [diff] [blame] | 136 | const LoopSafetyInfo *SafetyInfo, |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 137 | OptimizationRemarkEmitter *ORE, |
Philip Reames | b47b9c2 | 2015-05-22 02:14:05 +0000 | [diff] [blame] | 138 | const Instruction *CtxI = nullptr); |
Anna Thomas | 1962621 | 2018-08-17 13:44:00 +0000 | [diff] [blame] | 139 | static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, |
| 140 | AliasSetTracker *CurAST, Loop *CurLoop, |
| 141 | AliasAnalysis *AA); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 142 | static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, |
| 143 | Loop *CurLoop); |
| 144 | static Instruction *CloneInstructionInExitBlock( |
| 145 | Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, |
| 146 | const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU); |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 147 | |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 148 | static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 149 | AliasSetTracker *AST, MemorySSAUpdater *MSSAU); |
Max Kazantsev | 872bb74 | 2018-11-02 00:21:45 +0000 | [diff] [blame] | 150 | |
Max Kazantsev | 9883d1e | 2018-11-09 05:39:04 +0000 | [diff] [blame] | 151 | static void moveInstructionBefore(Instruction &I, Instruction &Dest, |
| 152 | ICFLoopSafetyInfo &SafetyInfo); |
| 153 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 154 | namespace { |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 155 | struct LoopInvariantCodeMotion { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 156 | using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>; |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 157 | bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 158 | TargetLibraryInfo *TLI, TargetTransformInfo *TTI, |
| 159 | ScalarEvolution *SE, MemorySSA *MSSA, |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 160 | OptimizationRemarkEmitter *ORE, bool DeleteAST); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 161 | |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 162 | ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; } |
Dehao Chen | 7ef5820 | 2016-07-11 22:45:24 +0000 | [diff] [blame] | 163 | |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 164 | private: |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 165 | ASTrackerMapTy LoopToAliasSetMap; |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 166 | |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 167 | std::unique_ptr<AliasSetTracker> |
| 168 | collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 169 | }; |
| 170 | |
| 171 | struct LegacyLICMPass : public LoopPass { |
| 172 | static char ID; // Pass identification, replacement for typeid |
| 173 | LegacyLICMPass() : LoopPass(ID) { |
| 174 | initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry()); |
| 175 | } |
| 176 | |
| 177 | bool runOnLoop(Loop *L, LPPassManager &LPM) override { |
Davide Italiano | 34f9438 | 2016-12-23 13:12:50 +0000 | [diff] [blame] | 178 | if (skipLoop(L)) { |
| 179 | // If we have run LICM on a previous loop but now we are skipping |
| 180 | // (because we've hit the opt-bisect limit), we need to clear the |
| 181 | // loop alias information. |
| 182 | LICM.getLoopToAliasSetMap().clear(); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 183 | return false; |
Davide Italiano | 34f9438 | 2016-12-23 13:12:50 +0000 | [diff] [blame] | 184 | } |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 185 | |
| 186 | auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); |
Alina Sbirlea | ff8b8ae | 2017-11-21 15:45:46 +0000 | [diff] [blame] | 187 | MemorySSA *MSSA = EnableMSSALoopDependency |
| 188 | ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA()) |
| 189 | : nullptr; |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 190 | // For the old PM, we can't use OptimizationRemarkEmitter as an analysis |
| 191 | // pass. Function analyses need to be preserved across loop transformations |
| 192 | // but ORE cannot be preserved (see comment before the pass definition). |
| 193 | OptimizationRemarkEmitter ORE(L->getHeader()->getParent()); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 194 | return LICM.runOnLoop(L, |
| 195 | &getAnalysis<AAResultsWrapperPass>().getAAResults(), |
| 196 | &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), |
| 197 | &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 198 | &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 199 | &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( |
| 200 | *L->getHeader()->getParent()), |
Alina Sbirlea | ff8b8ae | 2017-11-21 15:45:46 +0000 | [diff] [blame] | 201 | SE ? &SE->getSE() : nullptr, MSSA, &ORE, false); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 202 | } |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 203 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 204 | /// This transformation requires natural loop information & requires that |
| 205 | /// loop preheaders be inserted into the CFG... |
| 206 | /// |
| 207 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Jun Bum Lim | dfbe6fa | 2018-05-24 15:58:34 +0000 | [diff] [blame] | 208 | AU.addPreserved<DominatorTreeWrapperPass>(); |
| 209 | AU.addPreserved<LoopInfoWrapperPass>(); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 210 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 211 | if (EnableMSSALoopDependency) { |
Alina Sbirlea | ff8b8ae | 2017-11-21 15:45:46 +0000 | [diff] [blame] | 212 | AU.addRequired<MemorySSAWrapperPass>(); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 213 | AU.addPreserved<MemorySSAWrapperPass>(); |
| 214 | } |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 215 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 216 | getLoopAnalysisUsage(AU); |
| 217 | } |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 218 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 219 | using llvm::Pass::doFinalization; |
Matt Beaumont-Gay | abfc446 | 2012-12-04 05:41:27 +0000 | [diff] [blame] | 220 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 221 | bool doFinalization() override { |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 222 | assert(LICM.getLoopToAliasSetMap().empty() && |
| 223 | "Didn't free loop alias sets"); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 224 | return false; |
| 225 | } |
Devang Patel | 69730c9 | 2007-03-07 04:41:30 +0000 | [diff] [blame] | 226 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 227 | private: |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 228 | LoopInvariantCodeMotion LICM; |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 229 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 230 | /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. |
| 231 | void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, |
| 232 | Loop *L) override; |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 233 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 234 | /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias |
| 235 | /// set. |
| 236 | void deleteAnalysisValue(Value *V, Loop *L) override; |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 237 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 238 | /// Simple Analysis hook. Delete loop L from alias set map. |
| 239 | void deleteAnalysisLoop(Loop *L) override; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 240 | }; |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 241 | } // namespace |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 242 | |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 243 | PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM, |
| 244 | LoopStandardAnalysisResults &AR, LPMUpdater &) { |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 245 | const auto &FAM = |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 246 | AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager(); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 247 | Function *F = L.getHeader()->getParent(); |
| 248 | |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 249 | auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F); |
Chandler Carruth | 410eaeb | 2017-01-11 06:23:21 +0000 | [diff] [blame] | 250 | // FIXME: This should probably be optional rather than required. |
| 251 | if (!ORE) |
| 252 | report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not " |
| 253 | "cached at a higher level"); |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 254 | |
| 255 | LoopInvariantCodeMotion LICM; |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 256 | if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE, |
| 257 | AR.MSSA, ORE, true)) |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 258 | return PreservedAnalyses::all(); |
| 259 | |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 260 | auto PA = getLoopPassPreservedAnalyses(); |
Jun Bum Lim | dfbe6fa | 2018-05-24 15:58:34 +0000 | [diff] [blame] | 261 | |
| 262 | PA.preserve<DominatorTreeAnalysis>(); |
| 263 | PA.preserve<LoopAnalysis>(); |
| 264 | |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 265 | return PA; |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 266 | } |
| 267 | |
| 268 | char LegacyLICMPass::ID = 0; |
| 269 | INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", |
| 270 | false, false) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 271 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 272 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 273 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Alina Sbirlea | ff8b8ae | 2017-11-21 15:45:46 +0000 | [diff] [blame] | 274 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 275 | INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, |
| 276 | false) |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 277 | |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 278 | Pass *llvm::createLICMPass() { return new LegacyLICMPass(); } |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 279 | |
Devang Patel | d8b1ceb | 2007-07-31 16:52:25 +0000 | [diff] [blame] | 280 | /// Hoist expressions out of the specified loop. Note, alias info for inner |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 281 | /// loop is not preserved so it is not a good idea to run LICM multiple |
Devang Patel | d8b1ceb | 2007-07-31 16:52:25 +0000 | [diff] [blame] | 282 | /// times on one loop. |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 283 | /// We should delete AST for inner loops in the new pass manager to avoid |
| 284 | /// memory leak. |
Chris Lattner | f64f2d3 | 2002-09-26 16:52:07 +0000 | [diff] [blame] | 285 | /// |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 286 | bool LoopInvariantCodeMotion::runOnLoop( |
| 287 | Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT, |
| 288 | TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE, |
| 289 | MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) { |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 290 | bool Changed = false; |
Chad Rosier | 43a3306 | 2011-12-02 01:26:24 +0000 | [diff] [blame] | 291 | |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 292 | assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); |
| 293 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 294 | std::unique_ptr<AliasSetTracker> CurAST; |
| 295 | std::unique_ptr<MemorySSAUpdater> MSSAU; |
| 296 | if (!MSSA) { |
| 297 | LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n"); |
| 298 | CurAST = collectAliasInfoForLoop(L, LI, AA); |
| 299 | } else { |
| 300 | LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA. Promotion disabled.\n"); |
| 301 | MSSAU = make_unique<MemorySSAUpdater>(MSSA); |
| 302 | } |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 303 | |
Chris Lattner | d57f3f5 | 2002-09-26 19:40:25 +0000 | [diff] [blame] | 304 | // Get the preheader block to move instructions into... |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 305 | BasicBlock *Preheader = L->getLoopPreheader(); |
Chris Lattner | d57f3f5 | 2002-09-26 19:40:25 +0000 | [diff] [blame] | 306 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 307 | // Compute loop safety information. |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 308 | ICFLoopSafetyInfo SafetyInfo(DT); |
Max Kazantsev | 530b8d1 | 2018-08-15 05:55:43 +0000 | [diff] [blame] | 309 | SafetyInfo.computeLoopSafetyInfo(L); |
Nadav Rotem | 03dcd85 | 2012-09-04 10:25:04 +0000 | [diff] [blame] | 310 | |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 311 | // We want to visit all of the instructions in this loop... that are not parts |
| 312 | // of our subloops (they have already had their invariants hoisted out of |
| 313 | // their loop, into this loop, so there is no need to process the BODIES of |
| 314 | // the subloops). |
| 315 | // |
Chris Lattner | 6443769 | 2002-09-29 21:46:09 +0000 | [diff] [blame] | 316 | // Traverse the body of the loop in depth first order on the dominator tree so |
| 317 | // that we are guaranteed to see definitions before we see uses. This allows |
Nick Lewycky | a0d49da | 2007-08-18 15:08:56 +0000 | [diff] [blame] | 318 | // us to sink instructions in one pass, without iteration. After sinking |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 319 | // instructions, we perform another pass to hoist them out of the loop. |
Chris Lattner | 6443769 | 2002-09-29 21:46:09 +0000 | [diff] [blame] | 320 | // |
Dan Gohman | a83ac2d | 2009-11-05 21:11:53 +0000 | [diff] [blame] | 321 | if (L->hasDedicatedExits()) |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 322 | Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 323 | CurAST.get(), MSSAU.get(), &SafetyInfo, ORE); |
Dan Gohman | a83ac2d | 2009-11-05 21:11:53 +0000 | [diff] [blame] | 324 | if (Preheader) |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 325 | Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 326 | CurAST.get(), MSSAU.get(), &SafetyInfo, ORE); |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 327 | |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 328 | // Now that all loop invariants have been removed from the loop, promote any |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 329 | // memory references to scalars that we can. |
Michael Kuperstein | 5566092 | 2016-12-29 22:51:22 +0000 | [diff] [blame] | 330 | // Don't sink stores from loops without dedicated block exits. Exits |
| 331 | // containing indirect branches are not transformed by loop simplify, |
| 332 | // make sure we catch that. An additional load may be generated in the |
| 333 | // preheader for SSA updater, so also avoid sinking when no preheader |
| 334 | // is available. |
| 335 | if (!DisablePromotion && Preheader && L->hasDedicatedExits()) { |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 336 | // Figure out the loop exits and their insertion points |
Dan Gohman | b948736 | 2012-08-08 00:00:26 +0000 | [diff] [blame] | 337 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 338 | L->getUniqueExitBlocks(ExitBlocks); |
Dan Gohman | b948736 | 2012-08-08 00:00:26 +0000 | [diff] [blame] | 339 | |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 340 | // We can't insert into a catchswitch. |
| 341 | bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) { |
| 342 | return isa<CatchSwitchInst>(Exit->getTerminator()); |
| 343 | }); |
Michael Kuperstein | b6da9cf | 2016-12-29 22:37:13 +0000 | [diff] [blame] | 344 | |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 345 | if (!HasCatchSwitch) { |
| 346 | SmallVector<Instruction *, 8> InsertPts; |
| 347 | InsertPts.reserve(ExitBlocks.size()); |
| 348 | for (BasicBlock *ExitBlock : ExitBlocks) |
| 349 | InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); |
Chandler Carruth | 1665152 | 2014-02-01 13:35:14 +0000 | [diff] [blame] | 350 | |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 351 | PredIteratorCache PIC; |
Michael Kuperstein | b6da9cf | 2016-12-29 22:37:13 +0000 | [diff] [blame] | 352 | |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 353 | bool Promoted = false; |
| 354 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 355 | if (CurAST.get()) { |
| 356 | // Loop over all of the alias sets in the tracker object. |
| 357 | for (AliasSet &AS : *CurAST) { |
| 358 | // We can promote this alias set if it has a store, if it is a "Must" |
| 359 | // alias set, if the pointer is loop invariant, and if we are not |
| 360 | // eliminating any volatile loads or stores. |
| 361 | if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || |
| 362 | !L->isLoopInvariant(AS.begin()->getValue())) |
| 363 | continue; |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 364 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 365 | assert( |
| 366 | !AS.empty() && |
| 367 | "Must alias set should have at least one pointer element in it!"); |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 368 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 369 | SmallSetVector<Value *, 8> PointerMustAliases; |
| 370 | for (const auto &ASI : AS) |
| 371 | PointerMustAliases.insert(ASI.getValue()); |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 372 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 373 | Promoted |= promoteLoopAccessesToScalars( |
| 374 | PointerMustAliases, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L, |
| 375 | CurAST.get(), &SafetyInfo, ORE); |
| 376 | } |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 377 | } |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 378 | // FIXME: Promotion initially disabled when using MemorySSA. |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 379 | |
| 380 | // Once we have promoted values across the loop body we have to |
| 381 | // recursively reform LCSSA as any nested loop may now have values defined |
| 382 | // within the loop used in the outer loop. |
| 383 | // FIXME: This is really heavy handed. It would be a bit better to use an |
| 384 | // SSAUpdater strategy during promotion that was LCSSA aware and reformed |
| 385 | // it as it went. |
| 386 | if (Promoted) |
| 387 | formLCSSARecursively(*L, *DT, LI, SE); |
| 388 | |
| 389 | Changed |= Promoted; |
| 390 | } |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 391 | } |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 392 | |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 393 | // Check that neither this loop nor its parent have had LCSSA broken. LICM is |
| 394 | // specifically moving instructions across the loop boundary and so it is |
| 395 | // especially in need of sanity checking here. |
| 396 | assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); |
| 397 | assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && |
| 398 | "Parent loop not left in LCSSA form after LICM!"); |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 399 | |
Chris Lattner | cc9cbc6 | 2010-08-29 17:46:00 +0000 | [diff] [blame] | 400 | // If this loop is nested inside of another one, save the alias information |
| 401 | // for when we process the outer loop. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 402 | if (CurAST.get() && L->getParentLoop() && !DeleteAST) |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 403 | LoopToAliasSetMap[L] = std::move(CurAST); |
Sanjoy Das | 4ae3920 | 2016-05-03 17:50:11 +0000 | [diff] [blame] | 404 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 405 | if (MSSAU.get() && VerifyMemorySSA) |
| 406 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
| 407 | |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 408 | if (Changed && SE) |
| 409 | SE->forgetLoopDispositions(L); |
Devang Patel | 69730c9 | 2007-03-07 04:41:30 +0000 | [diff] [blame] | 410 | return Changed; |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 411 | } |
| 412 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 413 | /// Walk the specified region of the CFG (defined by all blocks dominated by |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 414 | /// the specified block, and that are in the current loop) in reverse depth |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 415 | /// first order w.r.t the DominatorTree. This allows us to visit uses before |
| 416 | /// definitions, allowing us to sink a loop body in one pass without iteration. |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 417 | /// |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 418 | bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 419 | DominatorTree *DT, TargetLibraryInfo *TLI, |
| 420 | TargetTransformInfo *TTI, Loop *CurLoop, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 421 | AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, |
| 422 | ICFLoopSafetyInfo *SafetyInfo, |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 423 | OptimizationRemarkEmitter *ORE) { |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 424 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 425 | // Verify inputs. |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 426 | assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 427 | CurLoop != nullptr && SafetyInfo != nullptr && |
| 428 | "Unexpected input to sinkRegion."); |
| 429 | assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && |
| 430 | "Either AliasSetTracker or MemorySSA should be initialized."); |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 431 | |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 432 | // We want to visit children before parents. We will enque all the parents |
| 433 | // before their children in the worklist and process the worklist in reverse |
| 434 | // order. |
| 435 | SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop); |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 436 | |
Sanjay Patel | 9913322 | 2016-01-13 23:01:57 +0000 | [diff] [blame] | 437 | bool Changed = false; |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 438 | for (DomTreeNode *DTN : reverse(Worklist)) { |
| 439 | BasicBlock *BB = DTN->getBlock(); |
| 440 | // Only need to process the contents of this block if it is not part of a |
| 441 | // subloop (which would already have been processed). |
| 442 | if (inSubLoop(BB, CurLoop, LI)) |
Chris Lattner | 263f804 | 2010-08-29 18:22:25 +0000 | [diff] [blame] | 443 | continue; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 444 | |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 445 | for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { |
| 446 | Instruction &I = *--II; |
| 447 | |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 448 | // If the instruction is dead, we would try to sink it because it isn't |
| 449 | // used in the loop, instead, just delete it. |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 450 | if (isInstructionTriviallyDead(&I, TLI)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 451 | LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); |
Anastasis Grammenos | 3a58910 | 2018-03-18 15:59:19 +0000 | [diff] [blame] | 452 | salvageDebugInfo(I); |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 453 | ++II; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 454 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 455 | Changed = true; |
| 456 | continue; |
| 457 | } |
| 458 | |
| 459 | // Check to see if we can sink this instruction to the exit blocks |
| 460 | // of the loop. We can do this if the all users of the instruction are |
| 461 | // outside of the loop. In this case, it doesn't even matter if the |
| 462 | // operands of the instruction are loop invariant. |
| 463 | // |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 464 | bool FreeInLoop = false; |
| 465 | if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) && |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 466 | canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, ORE) && |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 467 | !I.mayHaveSideEffects()) { |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 468 | if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE, FreeInLoop)) { |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 469 | if (!FreeInLoop) { |
| 470 | ++II; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 471 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 472 | } |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 473 | Changed = true; |
| 474 | } |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 475 | } |
Chris Lattner | 9184601 | 2003-12-19 08:18:16 +0000 | [diff] [blame] | 476 | } |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 477 | } |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 478 | if (MSSAU && VerifyMemorySSA) |
| 479 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 480 | return Changed; |
Chris Lattner | 547192d6 | 2003-12-19 07:22:45 +0000 | [diff] [blame] | 481 | } |
| 482 | |
Benjamin Kramer | b17d213 | 2019-01-12 18:36:22 +0000 | [diff] [blame] | 483 | namespace { |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 484 | // This is a helper class for hoistRegion to make it able to hoist control flow |
| 485 | // in order to be able to hoist phis. The way this works is that we initially |
| 486 | // start hoisting to the loop preheader, and when we see a loop invariant branch |
| 487 | // we make note of this. When we then come to hoist an instruction that's |
| 488 | // conditional on such a branch we duplicate the branch and the relevant control |
| 489 | // flow, then hoist the instruction into the block corresponding to its original |
| 490 | // block in the duplicated control flow. |
| 491 | class ControlFlowHoister { |
| 492 | private: |
| 493 | // Information about the loop we are hoisting from |
| 494 | LoopInfo *LI; |
| 495 | DominatorTree *DT; |
| 496 | Loop *CurLoop; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 497 | MemorySSAUpdater *MSSAU; |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 498 | |
| 499 | // A map of blocks in the loop to the block their instructions will be hoisted |
| 500 | // to. |
| 501 | DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap; |
| 502 | |
| 503 | // The branches that we can hoist, mapped to the block that marks a |
| 504 | // convergence point of their control flow. |
| 505 | DenseMap<BranchInst *, BasicBlock *> HoistableBranches; |
| 506 | |
| 507 | public: |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 508 | ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop, |
| 509 | MemorySSAUpdater *MSSAU) |
| 510 | : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {} |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 511 | |
| 512 | void registerPossiblyHoistableBranch(BranchInst *BI) { |
| 513 | // We can only hoist conditional branches with loop invariant operands. |
| 514 | if (!ControlFlowHoisting || !BI->isConditional() || |
| 515 | !CurLoop->hasLoopInvariantOperands(BI)) |
| 516 | return; |
| 517 | |
| 518 | // The branch destinations need to be in the loop, and we don't gain |
| 519 | // anything by duplicating conditional branches with duplicate successors, |
| 520 | // as it's essentially the same as an unconditional branch. |
| 521 | BasicBlock *TrueDest = BI->getSuccessor(0); |
| 522 | BasicBlock *FalseDest = BI->getSuccessor(1); |
| 523 | if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) || |
| 524 | TrueDest == FalseDest) |
| 525 | return; |
| 526 | |
| 527 | // We can hoist BI if one branch destination is the successor of the other, |
| 528 | // or both have common successor which we check by seeing if the |
| 529 | // intersection of their successors is non-empty. |
| 530 | // TODO: This could be expanded to allowing branches where both ends |
| 531 | // eventually converge to a single block. |
| 532 | SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc; |
| 533 | TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest)); |
| 534 | FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest)); |
| 535 | BasicBlock *CommonSucc = nullptr; |
| 536 | if (TrueDestSucc.count(FalseDest)) { |
| 537 | CommonSucc = FalseDest; |
| 538 | } else if (FalseDestSucc.count(TrueDest)) { |
| 539 | CommonSucc = TrueDest; |
| 540 | } else { |
| 541 | set_intersect(TrueDestSucc, FalseDestSucc); |
| 542 | // If there's one common successor use that. |
| 543 | if (TrueDestSucc.size() == 1) |
| 544 | CommonSucc = *TrueDestSucc.begin(); |
| 545 | // If there's more than one pick whichever appears first in the block list |
| 546 | // (we can't use the value returned by TrueDestSucc.begin() as it's |
| 547 | // unpredicatable which element gets returned). |
| 548 | else if (!TrueDestSucc.empty()) { |
| 549 | Function *F = TrueDest->getParent(); |
| 550 | auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); }; |
| 551 | auto It = std::find_if(F->begin(), F->end(), IsSucc); |
| 552 | assert(It != F->end() && "Could not find successor in function"); |
| 553 | CommonSucc = &*It; |
| 554 | } |
| 555 | } |
| 556 | // The common successor has to be dominated by the branch, as otherwise |
| 557 | // there will be some other path to the successor that will not be |
| 558 | // controlled by this branch so any phi we hoist would be controlled by the |
| 559 | // wrong condition. This also takes care of avoiding hoisting of loop back |
| 560 | // edges. |
| 561 | // TODO: In some cases this could be relaxed if the successor is dominated |
| 562 | // by another block that's been hoisted and we can guarantee that the |
| 563 | // control flow has been replicated exactly. |
| 564 | if (CommonSucc && DT->dominates(BI, CommonSucc)) |
| 565 | HoistableBranches[BI] = CommonSucc; |
| 566 | } |
| 567 | |
| 568 | bool canHoistPHI(PHINode *PN) { |
| 569 | // The phi must have loop invariant operands. |
| 570 | if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN)) |
| 571 | return false; |
| 572 | // We can hoist phis if the block they are in is the target of hoistable |
| 573 | // branches which cover all of the predecessors of the block. |
| 574 | SmallPtrSet<BasicBlock *, 8> PredecessorBlocks; |
| 575 | BasicBlock *BB = PN->getParent(); |
| 576 | for (BasicBlock *PredBB : predecessors(BB)) |
| 577 | PredecessorBlocks.insert(PredBB); |
| 578 | // If we have less predecessor blocks than predecessors then the phi will |
| 579 | // have more than one incoming value for the same block which we can't |
| 580 | // handle. |
| 581 | // TODO: This could be handled be erasing some of the duplicate incoming |
| 582 | // values. |
| 583 | if (PredecessorBlocks.size() != pred_size(BB)) |
| 584 | return false; |
| 585 | for (auto &Pair : HoistableBranches) { |
| 586 | if (Pair.second == BB) { |
| 587 | // Which blocks are predecessors via this branch depends on if the |
| 588 | // branch is triangle-like or diamond-like. |
| 589 | if (Pair.first->getSuccessor(0) == BB) { |
| 590 | PredecessorBlocks.erase(Pair.first->getParent()); |
| 591 | PredecessorBlocks.erase(Pair.first->getSuccessor(1)); |
| 592 | } else if (Pair.first->getSuccessor(1) == BB) { |
| 593 | PredecessorBlocks.erase(Pair.first->getParent()); |
| 594 | PredecessorBlocks.erase(Pair.first->getSuccessor(0)); |
| 595 | } else { |
| 596 | PredecessorBlocks.erase(Pair.first->getSuccessor(0)); |
| 597 | PredecessorBlocks.erase(Pair.first->getSuccessor(1)); |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | // PredecessorBlocks will now be empty if for every predecessor of BB we |
| 602 | // found a hoistable branch source. |
| 603 | return PredecessorBlocks.empty(); |
| 604 | } |
| 605 | |
| 606 | BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) { |
Alina Sbirlea | 0e21685 | 2018-12-05 10:16:21 +0000 | [diff] [blame] | 607 | if (!ControlFlowHoisting) |
| 608 | return CurLoop->getLoopPreheader(); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 609 | // If BB has already been hoisted, return that |
| 610 | if (HoistDestinationMap.count(BB)) |
| 611 | return HoistDestinationMap[BB]; |
| 612 | |
| 613 | // Check if this block is conditional based on a pending branch |
| 614 | auto HasBBAsSuccessor = |
| 615 | [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) { |
| 616 | return BB != Pair.second && (Pair.first->getSuccessor(0) == BB || |
| 617 | Pair.first->getSuccessor(1) == BB); |
| 618 | }; |
| 619 | auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(), |
| 620 | HasBBAsSuccessor); |
| 621 | |
| 622 | // If not involved in a pending branch, hoist to preheader |
| 623 | BasicBlock *InitialPreheader = CurLoop->getLoopPreheader(); |
| 624 | if (It == HoistableBranches.end()) { |
| 625 | LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName() |
| 626 | << " as hoist destination for " << BB->getName() |
| 627 | << "\n"); |
| 628 | HoistDestinationMap[BB] = InitialPreheader; |
| 629 | return InitialPreheader; |
| 630 | } |
| 631 | BranchInst *BI = It->first; |
| 632 | assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) == |
| 633 | HoistableBranches.end() && |
| 634 | "BB is expected to be the target of at most one branch"); |
| 635 | |
| 636 | LLVMContext &C = BB->getContext(); |
| 637 | BasicBlock *TrueDest = BI->getSuccessor(0); |
| 638 | BasicBlock *FalseDest = BI->getSuccessor(1); |
| 639 | BasicBlock *CommonSucc = HoistableBranches[BI]; |
| 640 | BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent()); |
| 641 | |
| 642 | // Create hoisted versions of blocks that currently don't have them |
| 643 | auto CreateHoistedBlock = [&](BasicBlock *Orig) { |
| 644 | if (HoistDestinationMap.count(Orig)) |
| 645 | return HoistDestinationMap[Orig]; |
| 646 | BasicBlock *New = |
| 647 | BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent()); |
| 648 | HoistDestinationMap[Orig] = New; |
| 649 | DT->addNewBlock(New, HoistTarget); |
| 650 | if (CurLoop->getParentLoop()) |
| 651 | CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI); |
| 652 | ++NumCreatedBlocks; |
| 653 | LLVM_DEBUG(dbgs() << "LICM created " << New->getName() |
| 654 | << " as hoist destination for " << Orig->getName() |
| 655 | << "\n"); |
| 656 | return New; |
| 657 | }; |
| 658 | BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest); |
| 659 | BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest); |
| 660 | BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc); |
| 661 | |
| 662 | // Link up these blocks with branches. |
| 663 | if (!HoistCommonSucc->getTerminator()) { |
| 664 | // The new common successor we've generated will branch to whatever that |
| 665 | // hoist target branched to. |
| 666 | BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor(); |
| 667 | assert(TargetSucc && "Expected hoist target to have a single successor"); |
| 668 | HoistCommonSucc->moveBefore(TargetSucc); |
| 669 | BranchInst::Create(TargetSucc, HoistCommonSucc); |
| 670 | } |
| 671 | if (!HoistTrueDest->getTerminator()) { |
| 672 | HoistTrueDest->moveBefore(HoistCommonSucc); |
| 673 | BranchInst::Create(HoistCommonSucc, HoistTrueDest); |
| 674 | } |
| 675 | if (!HoistFalseDest->getTerminator()) { |
| 676 | HoistFalseDest->moveBefore(HoistCommonSucc); |
| 677 | BranchInst::Create(HoistCommonSucc, HoistFalseDest); |
| 678 | } |
| 679 | |
| 680 | // If BI is being cloned to what was originally the preheader then |
| 681 | // HoistCommonSucc will now be the new preheader. |
| 682 | if (HoistTarget == InitialPreheader) { |
| 683 | // Phis in the loop header now need to use the new preheader. |
| 684 | InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 685 | if (MSSAU) |
| 686 | MSSAU->wireOldPredecessorsToNewImmediatePredecessor( |
| 687 | HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget}); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 688 | // The new preheader dominates the loop header. |
| 689 | DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc); |
| 690 | DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader()); |
| 691 | DT->changeImmediateDominator(HeaderNode, PreheaderNode); |
| 692 | // The preheader hoist destination is now the new preheader, with the |
| 693 | // exception of the hoist destination of this branch. |
| 694 | for (auto &Pair : HoistDestinationMap) |
| 695 | if (Pair.second == InitialPreheader && Pair.first != BI->getParent()) |
| 696 | Pair.second = HoistCommonSucc; |
| 697 | } |
| 698 | |
| 699 | // Now finally clone BI. |
| 700 | ReplaceInstWithInst( |
| 701 | HoistTarget->getTerminator(), |
| 702 | BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition())); |
| 703 | ++NumClonedBranches; |
| 704 | |
| 705 | assert(CurLoop->getLoopPreheader() && |
| 706 | "Hoisting blocks should not have destroyed preheader"); |
| 707 | return HoistDestinationMap[BB]; |
| 708 | } |
| 709 | }; |
Benjamin Kramer | b17d213 | 2019-01-12 18:36:22 +0000 | [diff] [blame] | 710 | } // namespace |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 711 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 712 | /// Walk the specified region of the CFG (defined by all blocks dominated by |
| 713 | /// the specified block, and that are in the current loop) in depth first |
| 714 | /// order w.r.t the DominatorTree. This allows us to visit definitions before |
| 715 | /// uses, allowing us to hoist a loop body in one pass without iteration. |
Chris Lattner | 6443769 | 2002-09-29 21:46:09 +0000 | [diff] [blame] | 716 | /// |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 717 | bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, |
| 718 | DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 719 | AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU, |
| 720 | ICFLoopSafetyInfo *SafetyInfo, |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 721 | OptimizationRemarkEmitter *ORE) { |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 722 | // Verify inputs. |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 723 | assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 724 | CurLoop != nullptr && SafetyInfo != nullptr && |
| 725 | "Unexpected input to hoistRegion."); |
| 726 | assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) && |
| 727 | "Either AliasSetTracker or MemorySSA should be initialized."); |
Sanjay Patel | 9913322 | 2016-01-13 23:01:57 +0000 | [diff] [blame] | 728 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 729 | ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU); |
Sanjay Patel | 9913322 | 2016-01-13 23:01:57 +0000 | [diff] [blame] | 730 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 731 | // Keep track of instructions that have been hoisted, as they may need to be |
| 732 | // re-hoisted if they end up not dominating all of their uses. |
| 733 | SmallVector<Instruction *, 16> HoistedInstructions; |
| 734 | |
| 735 | // For PHI hoisting to work we need to hoist blocks before their successors. |
| 736 | // We can do this by iterating through the blocks in the loop in reverse |
| 737 | // post-order. |
| 738 | LoopBlocksRPO Worklist(CurLoop); |
| 739 | Worklist.perform(LI); |
Sanjay Patel | 9913322 | 2016-01-13 23:01:57 +0000 | [diff] [blame] | 740 | bool Changed = false; |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 741 | for (BasicBlock *BB : Worklist) { |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 742 | // Only need to process the contents of this block if it is not part of a |
| 743 | // subloop (which would already have been processed). |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 744 | if (inSubLoop(BB, CurLoop, LI)) |
| 745 | continue; |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 746 | |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 747 | for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { |
| 748 | Instruction &I = *II++; |
| 749 | // Try constant folding this instruction. If all the operands are |
| 750 | // constants, it is technically hoistable, but it would be better to |
| 751 | // just fold it. |
| 752 | if (Constant *C = ConstantFoldInstruction( |
| 753 | &I, I.getModule()->getDataLayout(), TLI)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 754 | LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C |
| 755 | << '\n'); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 756 | if (CurAST) |
| 757 | CurAST->copyValue(&I, C); |
| 758 | // FIXME MSSA: Such replacements may make accesses unoptimized (D51960). |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 759 | I.replaceAllUsesWith(C); |
Max Kazantsev | 872bb74 | 2018-11-02 00:21:45 +0000 | [diff] [blame] | 760 | if (isInstructionTriviallyDead(&I, TLI)) |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 761 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 762 | Changed = true; |
| 763 | continue; |
Chris Lattner | 030f020 | 2010-08-31 23:00:16 +0000 | [diff] [blame] | 764 | } |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 765 | |
Stanislav Mekhanoshin | d8c9374 | 2018-06-23 04:01:28 +0000 | [diff] [blame] | 766 | // Try hoisting the instruction out to the preheader. We can only do |
| 767 | // this if all of the operands of the instruction are loop invariant and |
| 768 | // if it is safe to hoist the instruction. |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 769 | // TODO: It may be safe to hoist if we are hoisting to a conditional block |
| 770 | // and we have accurately duplicated the control flow from the loop header |
| 771 | // to that block. |
Stanislav Mekhanoshin | d8c9374 | 2018-06-23 04:01:28 +0000 | [diff] [blame] | 772 | if (CurLoop->hasLoopInvariantOperands(&I) && |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 773 | canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, ORE) && |
Max Kazantsev | 0042c06 | 2018-11-06 04:17:40 +0000 | [diff] [blame] | 774 | isSafeToExecuteUnconditionally( |
| 775 | I, DT, CurLoop, SafetyInfo, ORE, |
| 776 | CurLoop->getLoopPreheader()->getTerminator())) { |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 777 | hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, |
| 778 | MSSAU, ORE); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 779 | HoistedInstructions.push_back(&I); |
Max Kazantsev | 68290f8 | 2018-08-15 02:49:12 +0000 | [diff] [blame] | 780 | Changed = true; |
Stanislav Mekhanoshin | d8c9374 | 2018-06-23 04:01:28 +0000 | [diff] [blame] | 781 | continue; |
| 782 | } |
| 783 | |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 784 | // Attempt to remove floating point division out of the loop by |
| 785 | // converting it to a reciprocal multiplication. |
| 786 | if (I.getOpcode() == Instruction::FDiv && |
| 787 | CurLoop->isLoopInvariant(I.getOperand(1)) && |
| 788 | I.hasAllowReciprocal()) { |
| 789 | auto Divisor = I.getOperand(1); |
| 790 | auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0); |
| 791 | auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor); |
| 792 | ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags()); |
Max Kazantsev | 4615a50 | 2019-01-09 07:28:13 +0000 | [diff] [blame] | 793 | SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent()); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 794 | ReciprocalDivisor->insertBefore(&I); |
| 795 | |
| 796 | auto Product = |
| 797 | BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor); |
| 798 | Product->setFastMathFlags(I.getFastMathFlags()); |
Max Kazantsev | 4615a50 | 2019-01-09 07:28:13 +0000 | [diff] [blame] | 799 | SafetyInfo->insertInstructionTo(Product, I.getParent()); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 800 | Product->insertAfter(&I); |
| 801 | I.replaceAllUsesWith(Product); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 802 | eraseInstruction(I, *SafetyInfo, CurAST, MSSAU); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 803 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 804 | hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 805 | SafetyInfo, MSSAU, ORE); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 806 | HoistedInstructions.push_back(ReciprocalDivisor); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 807 | Changed = true; |
| 808 | continue; |
| 809 | } |
| 810 | |
Max Kazantsev | 097ef69 | 2018-08-21 08:11:31 +0000 | [diff] [blame] | 811 | using namespace PatternMatch; |
Philip Reames | 9ec15fa | 2018-08-24 16:24:48 +0000 | [diff] [blame] | 812 | if (((I.use_empty() && |
| 813 | match(&I, m_Intrinsic<Intrinsic::invariant_start>())) || |
Max Kazantsev | 3c284bd | 2018-08-30 03:39:16 +0000 | [diff] [blame] | 814 | isGuard(&I)) && |
Max Kazantsev | 7d49a3a | 2018-11-12 09:29:58 +0000 | [diff] [blame] | 815 | CurLoop->hasLoopInvariantOperands(&I) && |
| 816 | SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) && |
| 817 | SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop)) { |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 818 | hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, |
| 819 | MSSAU, ORE); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 820 | HoistedInstructions.push_back(&I); |
Max Kazantsev | 097ef69 | 2018-08-21 08:11:31 +0000 | [diff] [blame] | 821 | Changed = true; |
| 822 | continue; |
| 823 | } |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 824 | |
| 825 | if (PHINode *PN = dyn_cast<PHINode>(&I)) { |
| 826 | if (CFH.canHoistPHI(PN)) { |
| 827 | // Redirect incoming blocks first to ensure that we create hoisted |
| 828 | // versions of those blocks before we hoist the phi. |
| 829 | for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i) |
| 830 | PN->setIncomingBlock( |
| 831 | i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i))); |
| 832 | hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 833 | MSSAU, ORE); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 834 | assert(DT->dominates(PN, BB) && "Conditional PHIs not expected"); |
| 835 | Changed = true; |
| 836 | continue; |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | // Remember possibly hoistable branches so we can actually hoist them |
| 841 | // later if needed. |
| 842 | if (BranchInst *BI = dyn_cast<BranchInst>(&I)) |
| 843 | CFH.registerPossiblyHoistableBranch(BI); |
Philip Reames | 5a64824 | 2018-04-27 20:58:30 +0000 | [diff] [blame] | 844 | } |
David Majnemer | e6bb895 | 2017-07-20 03:27:02 +0000 | [diff] [blame] | 845 | } |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 846 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 847 | // If we hoisted instructions to a conditional block they may not dominate |
| 848 | // their uses that weren't hoisted (such as phis where some operands are not |
| 849 | // loop invariant). If so make them unconditional by moving them to their |
| 850 | // immediate dominator. We iterate through the instructions in reverse order |
| 851 | // which ensures that when we rehoist an instruction we rehoist its operands, |
| 852 | // and also keep track of where in the block we are rehoisting to to make sure |
| 853 | // that we rehoist instructions before the instructions that use them. |
| 854 | Instruction *HoistPoint = nullptr; |
Alina Sbirlea | 0e21685 | 2018-12-05 10:16:21 +0000 | [diff] [blame] | 855 | if (ControlFlowHoisting) { |
| 856 | for (Instruction *I : reverse(HoistedInstructions)) { |
| 857 | if (!llvm::all_of(I->uses(), |
| 858 | [&](Use &U) { return DT->dominates(I, U); })) { |
| 859 | BasicBlock *Dominator = |
| 860 | DT->getNode(I->getParent())->getIDom()->getBlock(); |
John Brawn | 39ac159 | 2019-01-04 17:12:09 +0000 | [diff] [blame] | 861 | if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) { |
Alina Sbirlea | 0e21685 | 2018-12-05 10:16:21 +0000 | [diff] [blame] | 862 | if (HoistPoint) |
| 863 | assert(DT->dominates(Dominator, HoistPoint->getParent()) && |
| 864 | "New hoist point expected to dominate old hoist point"); |
| 865 | HoistPoint = Dominator->getTerminator(); |
| 866 | } |
John Brawn | 39ac159 | 2019-01-04 17:12:09 +0000 | [diff] [blame] | 867 | LLVM_DEBUG(dbgs() << "LICM rehoisting to " |
| 868 | << HoistPoint->getParent()->getName() |
| 869 | << ": " << *I << "\n"); |
Alina Sbirlea | 0e21685 | 2018-12-05 10:16:21 +0000 | [diff] [blame] | 870 | moveInstructionBefore(*I, *HoistPoint, *SafetyInfo); |
| 871 | HoistPoint = I; |
| 872 | Changed = true; |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 873 | } |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 874 | } |
| 875 | } |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 876 | if (MSSAU && VerifyMemorySSA) |
| 877 | MSSAU->getMemorySSA()->verifyMemorySSA(); |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 878 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 879 | // Now that we've finished hoisting make sure that LI and DT are still |
| 880 | // valid. |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 881 | #ifndef NDEBUG |
| 882 | if (Changed) { |
| 883 | assert(DT->verify(DominatorTree::VerificationLevel::Fast) && |
| 884 | "Dominator tree verification failed"); |
| 885 | LI->verify(*DT); |
| 886 | } |
| 887 | #endif |
| 888 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 889 | return Changed; |
| 890 | } |
| 891 | |
Anna Thomas | 7f4b26e | 2017-02-02 13:22:03 +0000 | [diff] [blame] | 892 | // Return true if LI is invariant within scope of the loop. LI is invariant if |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 893 | // CurLoop is dominated by an invariant.start representing the same memory |
| 894 | // location and size as the memory location LI loads from, and also the |
| 895 | // invariant.start has no uses. |
Anna Thomas | 7f4b26e | 2017-02-02 13:22:03 +0000 | [diff] [blame] | 896 | static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, |
| 897 | Loop *CurLoop) { |
| 898 | Value *Addr = LI->getOperand(0); |
| 899 | const DataLayout &DL = LI->getModule()->getDataLayout(); |
| 900 | const uint32_t LocSizeInBits = DL.getTypeSizeInBits( |
| 901 | cast<PointerType>(Addr->getType())->getElementType()); |
| 902 | |
| 903 | // if the type is i8 addrspace(x)*, we know this is the type of |
| 904 | // llvm.invariant.start operand |
| 905 | auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()), |
| 906 | LI->getPointerAddressSpace()); |
| 907 | unsigned BitcastsVisited = 0; |
| 908 | // Look through bitcasts until we reach the i8* type (this is invariant.start |
| 909 | // operand type). |
| 910 | while (Addr->getType() != PtrInt8Ty) { |
| 911 | auto *BC = dyn_cast<BitCastInst>(Addr); |
| 912 | // Avoid traversing high number of bitcast uses. |
| 913 | if (++BitcastsVisited > MaxNumUsesTraversed || !BC) |
| 914 | return false; |
| 915 | Addr = BC->getOperand(0); |
| 916 | } |
| 917 | |
| 918 | unsigned UsesVisited = 0; |
| 919 | // Traverse all uses of the load operand value, to see if invariant.start is |
| 920 | // one of the uses, and whether it dominates the load instruction. |
| 921 | for (auto *U : Addr->users()) { |
| 922 | // Avoid traversing for Load operand with high number of users. |
| 923 | if (++UsesVisited > MaxNumUsesTraversed) |
| 924 | return false; |
| 925 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); |
| 926 | // If there are escaping uses of invariant.start instruction, the load maybe |
| 927 | // non-invariant. |
| 928 | if (!II || II->getIntrinsicID() != Intrinsic::invariant_start || |
Davide Italiano | 79eb3b0 | 2017-05-16 22:38:40 +0000 | [diff] [blame] | 929 | !II->use_empty()) |
Anna Thomas | 7f4b26e | 2017-02-02 13:22:03 +0000 | [diff] [blame] | 930 | continue; |
| 931 | unsigned InvariantSizeInBits = |
| 932 | cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8; |
| 933 | // Confirm the invariant.start location size contains the load operand size |
| 934 | // in bits. Also, the invariant.start should dominate the load, and we |
| 935 | // should not hoist the load out of a loop that contains this dominating |
| 936 | // invariant.start. |
| 937 | if (LocSizeInBits <= InvariantSizeInBits && |
| 938 | DT->properlyDominates(II->getParent(), CurLoop->getHeader())) |
| 939 | return true; |
| 940 | } |
| 941 | |
| 942 | return false; |
| 943 | } |
| 944 | |
Philip Reames | 09de470 | 2018-08-02 00:54:14 +0000 | [diff] [blame] | 945 | namespace { |
| 946 | /// Return true if-and-only-if we know how to (mechanically) both hoist and |
| 947 | /// sink a given instruction out of a loop. Does not address legality |
| 948 | /// concerns such as aliasing or speculation safety. |
| 949 | bool isHoistableAndSinkableInst(Instruction &I) { |
| 950 | // Only these instructions are hoistable/sinkable. |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 951 | return (isa<LoadInst>(I) || isa<StoreInst>(I) || |
| 952 | isa<CallInst>(I) || isa<FenceInst>(I) || |
Philip Reames | 09de470 | 2018-08-02 00:54:14 +0000 | [diff] [blame] | 953 | isa<BinaryOperator>(I) || isa<CastInst>(I) || |
| 954 | isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || |
| 955 | isa<CmpInst>(I) || isa<InsertElementInst>(I) || |
| 956 | isa<ExtractElementInst>(I) || isa<ShuffleVectorInst>(I) || |
| 957 | isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)); |
| 958 | } |
Philip Reames | 3b35aaa | 2018-08-06 22:07:37 +0000 | [diff] [blame] | 959 | /// Return true if all of the alias sets within this AST are known not to |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 960 | /// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop. |
| 961 | bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU, |
| 962 | const Loop *L) { |
| 963 | if (CurAST) { |
| 964 | for (AliasSet &AS : *CurAST) { |
| 965 | if (!AS.isForwardingAliasSet() && AS.isMod()) { |
| 966 | return false; |
| 967 | } |
Philip Reames | 3b35aaa | 2018-08-06 22:07:37 +0000 | [diff] [blame] | 968 | } |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 969 | return true; |
| 970 | } else { /*MSSAU*/ |
| 971 | for (auto *BB : L->getBlocks()) |
| 972 | if (MSSAU->getMemorySSA()->getBlockDefs(BB)) |
| 973 | return false; |
| 974 | return true; |
Philip Reames | 3b35aaa | 2018-08-06 22:07:37 +0000 | [diff] [blame] | 975 | } |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 976 | } |
| 977 | |
| 978 | /// Return true if I is the only Instruction with a MemoryAccess in L. |
| 979 | bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, |
| 980 | const MemorySSAUpdater *MSSAU) { |
| 981 | for (auto *BB : L->getBlocks()) |
| 982 | if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) { |
| 983 | int NotAPhi = 0; |
| 984 | for (const auto &Acc : *Accs) { |
| 985 | if (isa<MemoryPhi>(&Acc)) |
| 986 | continue; |
| 987 | const auto *MUD = cast<MemoryUseOrDef>(&Acc); |
| 988 | if (MUD->getMemoryInst() != I || NotAPhi++ == 1) |
| 989 | return false; |
| 990 | } |
| 991 | } |
Philip Reames | 3b35aaa | 2018-08-06 22:07:37 +0000 | [diff] [blame] | 992 | return true; |
| 993 | } |
Philip Reames | 09de470 | 2018-08-02 00:54:14 +0000 | [diff] [blame] | 994 | } |
| 995 | |
Dehao Chen | b94c09ba | 2016-10-27 16:30:08 +0000 | [diff] [blame] | 996 | bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, |
| 997 | Loop *CurLoop, AliasSetTracker *CurAST, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 998 | MemorySSAUpdater *MSSAU, |
Philip Reames | 32cb80b | 2018-08-02 04:08:04 +0000 | [diff] [blame] | 999 | bool TargetExecutesOncePerLoop, |
Adam Nemet | 81941b3 | 2017-01-11 04:39:45 +0000 | [diff] [blame] | 1000 | OptimizationRemarkEmitter *ORE) { |
Philip Reames | 09de470 | 2018-08-02 00:54:14 +0000 | [diff] [blame] | 1001 | // If we don't understand the instruction, bail early. |
| 1002 | if (!isHoistableAndSinkableInst(I)) |
| 1003 | return false; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1004 | |
| 1005 | MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr; |
| 1006 | |
Chris Lattner | 65c1193 | 2003-12-09 19:32:44 +0000 | [diff] [blame] | 1007 | // Loads have extra constraints we have to verify before we can hoist them. |
| 1008 | if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { |
Eli Friedman | 91386c7 | 2011-08-15 20:52:09 +0000 | [diff] [blame] | 1009 | if (!LI->isUnordered()) |
Max Kazantsev | 0c8dd05 | 2017-10-11 07:26:45 +0000 | [diff] [blame] | 1010 | return false; // Don't sink/hoist volatile or ordered atomic loads! |
Chris Lattner | 65c1193 | 2003-12-09 19:32:44 +0000 | [diff] [blame] | 1011 | |
Chris Lattner | 8a8fb90 | 2008-07-23 05:06:28 +0000 | [diff] [blame] | 1012 | // Loads from constant memory are always safe to move, even if they end up |
| 1013 | // in the same alias set as something that ends up being modified. |
Dan Gohman | cbc6ebb | 2009-11-19 19:00:10 +0000 | [diff] [blame] | 1014 | if (AA->pointsToConstantMemory(LI->getOperand(0))) |
Chris Lattner | 8a8fb90 | 2008-07-23 05:06:28 +0000 | [diff] [blame] | 1015 | return true; |
Philip Reames | 5a3f5f7 | 2014-10-21 00:13:20 +0000 | [diff] [blame] | 1016 | if (LI->getMetadata(LLVMContext::MD_invariant_load)) |
Pete Cooper | 9ee2209 | 2011-11-08 19:30:00 +0000 | [diff] [blame] | 1017 | return true; |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1018 | |
Philip Reames | 32cb80b | 2018-08-02 04:08:04 +0000 | [diff] [blame] | 1019 | if (LI->isAtomic() && !TargetExecutesOncePerLoop) |
| 1020 | return false; // Don't risk duplicating unordered loads |
Max Kazantsev | 0c8dd05 | 2017-10-11 07:26:45 +0000 | [diff] [blame] | 1021 | |
Anna Thomas | 7f4b26e | 2017-02-02 13:22:03 +0000 | [diff] [blame] | 1022 | // This checks for an invariant.start dominating the load. |
| 1023 | if (isLoadInvariantInLoop(LI, DT, CurLoop)) |
| 1024 | return true; |
| 1025 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1026 | bool Invalidated; |
| 1027 | if (CurAST) |
| 1028 | Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST, |
| 1029 | CurLoop, AA); |
| 1030 | else |
| 1031 | Invalidated = pointerInvalidatedByLoopWithMSSA( |
| 1032 | MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop); |
Adam Nemet | 81941b3 | 2017-01-11 04:39:45 +0000 | [diff] [blame] | 1033 | // Check loop-invariant address because this may also be a sinkable load |
| 1034 | // whose address is not necessarily loop-invariant. |
| 1035 | if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand())) |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1036 | ORE->emit([&]() { |
| 1037 | return OptimizationRemarkMissed( |
| 1038 | DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI) |
| 1039 | << "failed to move load with loop-invariant address " |
| 1040 | "because the loop may invalidate its value"; |
| 1041 | }); |
Adam Nemet | 81941b3 | 2017-01-11 04:39:45 +0000 | [diff] [blame] | 1042 | |
| 1043 | return !Invalidated; |
Chris Lattner | 20cda26 | 2004-03-15 04:11:30 +0000 | [diff] [blame] | 1044 | } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { |
Eli Friedman | 942e1c1 | 2011-05-27 18:37:52 +0000 | [diff] [blame] | 1045 | // Don't sink or hoist dbg info; it's legal, but not useful. |
Dehao Chen | 4b5e7f7 | 2016-09-02 01:59:27 +0000 | [diff] [blame] | 1046 | if (isa<DbgInfoIntrinsic>(I)) |
Eli Friedman | 942e1c1 | 2011-05-27 18:37:52 +0000 | [diff] [blame] | 1047 | return false; |
| 1048 | |
David Majnemer | 42a0730 | 2016-01-04 03:37:39 +0000 | [diff] [blame] | 1049 | // Don't sink calls which can throw. |
| 1050 | if (CI->mayThrow()) |
| 1051 | return false; |
| 1052 | |
Philip Reames | 1c0fde6 | 2018-08-24 19:13:39 +0000 | [diff] [blame] | 1053 | using namespace PatternMatch; |
| 1054 | if (match(CI, m_Intrinsic<Intrinsic::assume>())) |
| 1055 | // Assumes don't actually alias anything or throw |
| 1056 | return true; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1057 | |
Eli Friedman | 942e1c1 | 2011-05-27 18:37:52 +0000 | [diff] [blame] | 1058 | // Handle simple cases by querying alias analysis. |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 1059 | FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); |
| 1060 | if (Behavior == FMRB_DoesNotAccessMemory) |
Duncan Sands | 68b6f50 | 2007-12-01 07:51:45 +0000 | [diff] [blame] | 1061 | return true; |
Dan Gohman | 0f17507 | 2010-11-09 19:58:21 +0000 | [diff] [blame] | 1062 | if (AliasAnalysis::onlyReadsMemory(Behavior)) { |
Philip Reames | 5f99423 | 2015-09-21 22:27:59 +0000 | [diff] [blame] | 1063 | // A readonly argmemonly function only reads from memory pointed to by |
| 1064 | // it's arguments with arbitrary offsets. If we can prove there are no |
| 1065 | // writes to this memory in the loop, we can hoist or sink. |
| 1066 | if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 1067 | // TODO: expand to writeable arguments |
Philip Reames | 5f99423 | 2015-09-21 22:27:59 +0000 | [diff] [blame] | 1068 | for (Value *Op : CI->arg_operands()) |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1069 | if (Op->getType()->isPointerTy()) { |
| 1070 | bool Invalidated; |
| 1071 | if (CurAST) |
| 1072 | Invalidated = pointerInvalidatedByLoop( |
George Burgess IV | 6ef8002 | 2018-10-10 21:28:44 +0000 | [diff] [blame] | 1073 | MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()), |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1074 | CurAST, CurLoop, AA); |
| 1075 | else |
| 1076 | Invalidated = pointerInvalidatedByLoopWithMSSA( |
| 1077 | MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop); |
| 1078 | if (Invalidated) |
| 1079 | return false; |
| 1080 | } |
Philip Reames | 5f99423 | 2015-09-21 22:27:59 +0000 | [diff] [blame] | 1081 | return true; |
| 1082 | } |
Philip Reames | 3b35aaa | 2018-08-06 22:07:37 +0000 | [diff] [blame] | 1083 | |
Duncan Sands | 68b6f50 | 2007-12-01 07:51:45 +0000 | [diff] [blame] | 1084 | // If this call only reads from memory and there are no writes to memory |
| 1085 | // in the loop, we can hoist or sink the call as appropriate. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1086 | if (isReadOnly(CurAST, MSSAU, CurLoop)) |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1087 | return true; |
Chris Lattner | 20cda26 | 2004-03-15 04:11:30 +0000 | [diff] [blame] | 1088 | } |
| 1089 | |
Nadav Rotem | 03dcd85 | 2012-09-04 10:25:04 +0000 | [diff] [blame] | 1090 | // FIXME: This should use mod/ref information to see if we can hoist or |
| 1091 | // sink the call. |
Dehao Chen | 4b5e7f7 | 2016-09-02 01:59:27 +0000 | [diff] [blame] | 1092 | |
Chris Lattner | 20cda26 | 2004-03-15 04:11:30 +0000 | [diff] [blame] | 1093 | return false; |
Philip Reames | ca256d9 | 2018-08-09 20:18:42 +0000 | [diff] [blame] | 1094 | } else if (auto *FI = dyn_cast<FenceInst>(&I)) { |
| 1095 | // Fences alias (most) everything to provide ordering. For the moment, |
| 1096 | // just give up if there are any other memory operations in the loop. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1097 | if (CurAST) { |
| 1098 | auto Begin = CurAST->begin(); |
| 1099 | assert(Begin != CurAST->end() && "must contain FI"); |
| 1100 | if (std::next(Begin) != CurAST->end()) |
| 1101 | // constant memory for instance, TODO: handle better |
| 1102 | return false; |
| 1103 | auto *UniqueI = Begin->getUniqueInstruction(); |
| 1104 | if (!UniqueI) |
| 1105 | // other memory op, give up |
| 1106 | return false; |
| 1107 | (void)FI; // suppress unused variable warning |
| 1108 | assert(UniqueI == FI && "AS must contain FI"); |
| 1109 | return true; |
| 1110 | } else // MSSAU |
| 1111 | return isOnlyMemoryAccess(FI, CurLoop, MSSAU); |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 1112 | } else if (auto *SI = dyn_cast<StoreInst>(&I)) { |
| 1113 | if (!SI->isUnordered()) |
| 1114 | return false; // Don't sink/hoist volatile or ordered atomic store! |
| 1115 | |
| 1116 | // We can only hoist a store that we can prove writes a value which is not |
| 1117 | // read or overwritten within the loop. For those cases, we fallback to |
Philip Reames | 1887c40 | 2018-08-29 22:09:21 +0000 | [diff] [blame] | 1118 | // load store promotion instead. TODO: We can extend this to cases where |
| 1119 | // there is exactly one write to the location and that write dominates an |
| 1120 | // arbitrary number of reads in the loop. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1121 | if (CurAST) { |
| 1122 | auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI)); |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 1123 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1124 | if (AS.isRef() || !AS.isMustAlias()) |
| 1125 | // Quick exit test, handled by the full path below as well. |
| 1126 | return false; |
| 1127 | auto *UniqueI = AS.getUniqueInstruction(); |
| 1128 | if (!UniqueI) |
| 1129 | // other memory op, give up |
| 1130 | return false; |
| 1131 | assert(UniqueI == SI && "AS must contain SI"); |
| 1132 | return true; |
| 1133 | } else { // MSSAU |
| 1134 | if (isOnlyMemoryAccess(SI, CurLoop, MSSAU)) |
| 1135 | return true; |
| 1136 | if (!EnableLicmCap) { |
| 1137 | auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI); |
| 1138 | if (MSSA->isLiveOnEntryDef(Source) || |
| 1139 | !CurLoop->contains(Source->getBlock())) |
| 1140 | return true; |
| 1141 | } |
Philip Reames | f562fc8 | 2018-08-29 21:49:30 +0000 | [diff] [blame] | 1142 | return false; |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1143 | } |
Chris Lattner | 65c1193 | 2003-12-09 19:32:44 +0000 | [diff] [blame] | 1144 | } |
| 1145 | |
Philip Reames | 22b20a0 | 2018-08-09 03:44:28 +0000 | [diff] [blame] | 1146 | assert(!I.mayReadOrWriteMemory() && "unhandled aliasing"); |
| 1147 | |
Philip Reames | 32cb80b | 2018-08-02 04:08:04 +0000 | [diff] [blame] | 1148 | // We've established mechanical ability and aliasing, it's up to the caller |
| 1149 | // to check fault safety |
| 1150 | return true; |
Chris Lattner | aaaea51 | 2003-12-10 06:41:05 +0000 | [diff] [blame] | 1151 | } |
| 1152 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1153 | /// Returns true if a PHINode is a trivially replaceable with an |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1154 | /// Instruction. |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1155 | /// This is true when all incoming values are that instruction. |
| 1156 | /// This pattern occurs most often with LCSSA PHI nodes. |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1157 | /// |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1158 | static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 1159 | for (const Value *IncValue : PN.incoming_values()) |
| 1160 | if (IncValue != &I) |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1161 | return false; |
| 1162 | |
| 1163 | return true; |
| 1164 | } |
| 1165 | |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1166 | /// Return true if the instruction is free in the loop. |
| 1167 | static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, |
| 1168 | const TargetTransformInfo *TTI) { |
| 1169 | |
| 1170 | if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) { |
| 1171 | if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free) |
| 1172 | return false; |
| 1173 | // For a GEP, we cannot simply use getUserCost because currently it |
| 1174 | // optimistically assume that a GEP will fold into addressing mode |
| 1175 | // regardless of its users. |
| 1176 | const BasicBlock *BB = GEP->getParent(); |
| 1177 | for (const User *U : GEP->users()) { |
| 1178 | const Instruction *UI = cast<Instruction>(U); |
| 1179 | if (CurLoop->contains(UI) && |
| 1180 | (BB != UI->getParent() || |
| 1181 | (!isa<StoreInst>(UI) && !isa<LoadInst>(UI)))) |
| 1182 | return false; |
| 1183 | } |
| 1184 | return true; |
| 1185 | } else |
| 1186 | return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free; |
| 1187 | } |
| 1188 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1189 | /// Return true if the only users of this instruction are outside of |
| 1190 | /// the loop. If this is true, we can sink the instruction to the exit |
| 1191 | /// blocks of the loop. |
Chris Lattner | aaaea51 | 2003-12-10 06:41:05 +0000 | [diff] [blame] | 1192 | /// |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1193 | /// We also return true if the instruction could be folded away in lowering. |
| 1194 | /// (e.g., a GEP can be folded into a load as an addressing mode in the loop). |
| 1195 | static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, |
| 1196 | const LoopSafetyInfo *SafetyInfo, |
| 1197 | TargetTransformInfo *TTI, bool &FreeInLoop) { |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1198 | const auto &BlockColors = SafetyInfo->getBlockColors(); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1199 | bool IsFree = isFreeInLoop(I, CurLoop, TTI); |
Pete Cooper | 0cabcf2 | 2015-05-13 01:12:18 +0000 | [diff] [blame] | 1200 | for (const User *U : I.users()) { |
| 1201 | const Instruction *UI = cast<Instruction>(U); |
| 1202 | if (const PHINode *PN = dyn_cast<PHINode>(UI)) { |
David Majnemer | 42a0730 | 2016-01-04 03:37:39 +0000 | [diff] [blame] | 1203 | const BasicBlock *BB = PN->getParent(); |
| 1204 | // We cannot sink uses in catchswitches. |
| 1205 | if (isa<CatchSwitchInst>(BB->getTerminator())) |
| 1206 | return false; |
| 1207 | |
| 1208 | // We need to sink a callsite to a unique funclet. Avoid sinking if the |
| 1209 | // phi use is too muddled. |
| 1210 | if (isa<CallInst>(I)) |
| 1211 | if (!BlockColors.empty() && |
| 1212 | BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) |
| 1213 | return false; |
Chris Lattner | 34399dd | 2003-12-11 22:23:32 +0000 | [diff] [blame] | 1214 | } |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1215 | |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1216 | if (CurLoop->contains(UI)) { |
| 1217 | if (IsFree) { |
| 1218 | FreeInLoop = true; |
| 1219 | continue; |
| 1220 | } |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1221 | return false; |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1222 | } |
Chris Lattner | 34399dd | 2003-12-11 22:23:32 +0000 | [diff] [blame] | 1223 | } |
Chris Lattner | aaaea51 | 2003-12-10 06:41:05 +0000 | [diff] [blame] | 1224 | return true; |
| 1225 | } |
| 1226 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1227 | static Instruction *CloneInstructionInExitBlock( |
| 1228 | Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, |
| 1229 | const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) { |
David Majnemer | 42a0730 | 2016-01-04 03:37:39 +0000 | [diff] [blame] | 1230 | Instruction *New; |
| 1231 | if (auto *CI = dyn_cast<CallInst>(&I)) { |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1232 | const auto &BlockColors = SafetyInfo->getBlockColors(); |
David Majnemer | 42a0730 | 2016-01-04 03:37:39 +0000 | [diff] [blame] | 1233 | |
| 1234 | // Sinking call-sites need to be handled differently from other |
| 1235 | // instructions. The cloned call-site needs a funclet bundle operand |
| 1236 | // appropriate for it's location in the CFG. |
| 1237 | SmallVector<OperandBundleDef, 1> OpBundles; |
| 1238 | for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); |
| 1239 | BundleIdx != BundleEnd; ++BundleIdx) { |
| 1240 | OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); |
| 1241 | if (Bundle.getTagID() == LLVMContext::OB_funclet) |
| 1242 | continue; |
| 1243 | |
| 1244 | OpBundles.emplace_back(Bundle); |
| 1245 | } |
| 1246 | |
| 1247 | if (!BlockColors.empty()) { |
| 1248 | const ColorVector &CV = BlockColors.find(&ExitBlock)->second; |
| 1249 | assert(CV.size() == 1 && "non-unique color for exit block!"); |
| 1250 | BasicBlock *BBColor = CV.front(); |
| 1251 | Instruction *EHPad = BBColor->getFirstNonPHI(); |
| 1252 | if (EHPad->isEHPad()) |
| 1253 | OpBundles.emplace_back("funclet", EHPad); |
| 1254 | } |
| 1255 | |
| 1256 | New = CallInst::Create(CI, OpBundles); |
| 1257 | } else { |
| 1258 | New = I.clone(); |
| 1259 | } |
| 1260 | |
Evgeniy Stepanov | d99cca2 | 2014-06-25 09:17:21 +0000 | [diff] [blame] | 1261 | ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1262 | if (!I.getName().empty()) |
| 1263 | New->setName(I.getName() + ".le"); |
Evgeniy Stepanov | d99cca2 | 2014-06-25 09:17:21 +0000 | [diff] [blame] | 1264 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1265 | MemoryAccess *OldMemAcc; |
| 1266 | if (MSSAU && (OldMemAcc = MSSAU->getMemorySSA()->getMemoryAccess(&I))) { |
| 1267 | // Create a new MemoryAccess and let MemorySSA set its defining access. |
| 1268 | MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB( |
| 1269 | New, nullptr, New->getParent(), MemorySSA::Beginning); |
| 1270 | if (NewMemAcc) { |
| 1271 | if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc)) |
| 1272 | MSSAU->insertDef(MemDef, /*RenameUses=*/true); |
| 1273 | else { |
| 1274 | auto *MemUse = cast<MemoryUse>(NewMemAcc); |
| 1275 | MSSAU->insertUse(MemUse); |
| 1276 | } |
| 1277 | } |
| 1278 | } |
| 1279 | |
Evgeniy Stepanov | d99cca2 | 2014-06-25 09:17:21 +0000 | [diff] [blame] | 1280 | // Build LCSSA PHI nodes for any in-loop operands. Note that this is |
| 1281 | // particularly cheap because we can rip off the PHI node that we're |
| 1282 | // replacing for the number and blocks of the predecessors. |
| 1283 | // OPT: If this shows up in a profile, we can instead finish sinking all |
| 1284 | // invariant instructions, and then walk their operands to re-establish |
| 1285 | // LCSSA. That will eliminate creating PHI nodes just to nuke them when |
| 1286 | // sinking bottom-up. |
| 1287 | for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; |
| 1288 | ++OI) |
| 1289 | if (Instruction *OInst = dyn_cast<Instruction>(*OI)) |
| 1290 | if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) |
| 1291 | if (!OLoop->contains(&PN)) { |
| 1292 | PHINode *OpPN = |
| 1293 | PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1294 | OInst->getName() + ".lcssa", &ExitBlock.front()); |
Evgeniy Stepanov | d99cca2 | 2014-06-25 09:17:21 +0000 | [diff] [blame] | 1295 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) |
| 1296 | OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); |
| 1297 | *OI = OpPN; |
| 1298 | } |
| 1299 | return New; |
| 1300 | } |
| 1301 | |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1302 | static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1303 | AliasSetTracker *AST, MemorySSAUpdater *MSSAU) { |
Max Kazantsev | 872bb74 | 2018-11-02 00:21:45 +0000 | [diff] [blame] | 1304 | if (AST) |
| 1305 | AST->deleteValue(&I); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1306 | if (MSSAU) |
| 1307 | MSSAU->removeMemoryAccess(&I); |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1308 | SafetyInfo.removeInstruction(&I); |
Max Kazantsev | 872bb74 | 2018-11-02 00:21:45 +0000 | [diff] [blame] | 1309 | I.eraseFromParent(); |
| 1310 | } |
| 1311 | |
Max Kazantsev | 9883d1e | 2018-11-09 05:39:04 +0000 | [diff] [blame] | 1312 | static void moveInstructionBefore(Instruction &I, Instruction &Dest, |
| 1313 | ICFLoopSafetyInfo &SafetyInfo) { |
| 1314 | SafetyInfo.removeInstruction(&I); |
Max Kazantsev | 4615a50 | 2019-01-09 07:28:13 +0000 | [diff] [blame] | 1315 | SafetyInfo.insertInstructionTo(&I, Dest.getParent()); |
Max Kazantsev | 9883d1e | 2018-11-09 05:39:04 +0000 | [diff] [blame] | 1316 | I.moveBefore(&Dest); |
| 1317 | } |
| 1318 | |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1319 | static Instruction *sinkThroughTriviallyReplaceablePHI( |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1320 | PHINode *TPN, Instruction *I, LoopInfo *LI, |
| 1321 | SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1322 | const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, |
| 1323 | MemorySSAUpdater *MSSAU) { |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1324 | assert(isTriviallyReplaceablePHI(*TPN, *I) && |
| 1325 | "Expect only trivially replaceable PHI"); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1326 | BasicBlock *ExitBlock = TPN->getParent(); |
| 1327 | Instruction *New; |
| 1328 | auto It = SunkCopies.find(ExitBlock); |
| 1329 | if (It != SunkCopies.end()) |
| 1330 | New = It->second; |
| 1331 | else |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1332 | New = SunkCopies[ExitBlock] = CloneInstructionInExitBlock( |
| 1333 | *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1334 | return New; |
| 1335 | } |
| 1336 | |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1337 | static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) { |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1338 | BasicBlock *BB = PN->getParent(); |
| 1339 | if (!BB->canSplitPredecessors()) |
| 1340 | return false; |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1341 | // It's not impossible to split EHPad blocks, but if BlockColors already exist |
| 1342 | // it require updating BlockColors for all offspring blocks accordingly. By |
| 1343 | // skipping such corner case, we can make updating BlockColors after splitting |
| 1344 | // predecessor fairly simple. |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1345 | if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad()) |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1346 | return false; |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1347 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 1348 | BasicBlock *BBPred = *PI; |
| 1349 | if (isa<IndirectBrInst>(BBPred->getTerminator())) |
| 1350 | return false; |
| 1351 | } |
| 1352 | return true; |
| 1353 | } |
| 1354 | |
| 1355 | static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1356 | LoopInfo *LI, const Loop *CurLoop, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1357 | LoopSafetyInfo *SafetyInfo, |
| 1358 | MemorySSAUpdater *MSSAU) { |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1359 | #ifndef NDEBUG |
| 1360 | SmallVector<BasicBlock *, 32> ExitBlocks; |
| 1361 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
| 1362 | SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), |
| 1363 | ExitBlocks.end()); |
| 1364 | #endif |
| 1365 | BasicBlock *ExitBB = PN->getParent(); |
| 1366 | assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block."); |
| 1367 | |
| 1368 | // Split predecessors of the loop exit to make instructions in the loop are |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1369 | // exposed to exit blocks through trivially replaceable PHIs while keeping the |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1370 | // loop in the canonical form where each predecessor of each exit block should |
| 1371 | // be contained within the loop. For example, this will convert the loop below |
| 1372 | // from |
| 1373 | // |
| 1374 | // LB1: |
| 1375 | // %v1 = |
| 1376 | // br %LE, %LB2 |
| 1377 | // LB2: |
| 1378 | // %v2 = |
| 1379 | // br %LE, %LB1 |
| 1380 | // LE: |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1381 | // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1382 | // |
| 1383 | // to |
| 1384 | // |
| 1385 | // LB1: |
| 1386 | // %v1 = |
| 1387 | // br %LE.split, %LB2 |
| 1388 | // LB2: |
| 1389 | // %v2 = |
| 1390 | // br %LE.split2, %LB1 |
| 1391 | // LE.split: |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1392 | // %p1 = phi [%v1, %LB1] <-- trivially replaceable |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1393 | // br %LE |
| 1394 | // LE.split2: |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1395 | // %p2 = phi [%v2, %LB2] <-- trivially replaceable |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1396 | // br %LE |
| 1397 | // LE: |
| 1398 | // %p = phi [%p1, %LE.split], [%p2, %LE.split2] |
| 1399 | // |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1400 | const auto &BlockColors = SafetyInfo->getBlockColors(); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1401 | SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB)); |
| 1402 | while (!PredBBs.empty()) { |
| 1403 | BasicBlock *PredBB = *PredBBs.begin(); |
| 1404 | assert(CurLoop->contains(PredBB) && |
| 1405 | "Expect all predecessors are in the loop"); |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1406 | if (PN->getBasicBlockIndex(PredBB) >= 0) { |
| 1407 | BasicBlock *NewPred = SplitBlockPredecessors( |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1408 | ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true); |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1409 | // Since we do not allow splitting EH-block with BlockColors in |
| 1410 | // canSplitPredecessors(), we can simply assign predecessor's color to |
| 1411 | // the new block. |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1412 | if (!BlockColors.empty()) |
Andrew Kaylor | a237866 | 2018-03-23 17:36:18 +0000 | [diff] [blame] | 1413 | // Grab a reference to the ColorVector to be inserted before getting the |
| 1414 | // reference to the vector we are copying because inserting the new |
| 1415 | // element in BlockColors might cause the map to be reallocated. |
Max Kazantsev | 8d56be7 | 2018-10-16 08:07:14 +0000 | [diff] [blame] | 1416 | SafetyInfo->copyColors(NewPred, PredBB); |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1417 | } |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1418 | PredBBs.remove(PredBB); |
| 1419 | } |
| 1420 | } |
| 1421 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1422 | /// When an instruction is found to only be used outside of the loop, this |
| 1423 | /// function moves it to the exit blocks and patches up SSA form as needed. |
Chris Lattner | 9184601 | 2003-12-19 08:18:16 +0000 | [diff] [blame] | 1424 | /// This method is guaranteed to remove the original instruction from its |
| 1425 | /// position, and may either delete it or move it to outside of the loop. |
Chris Lattner | aaaea51 | 2003-12-10 06:41:05 +0000 | [diff] [blame] | 1426 | /// |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1427 | static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1428 | const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1429 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE, |
| 1430 | bool FreeInLoop) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1431 | LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1432 | ORE->emit([&]() { |
| 1433 | return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I) |
| 1434 | << "sinking " << ore::NV("Inst", &I); |
| 1435 | }); |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1436 | bool Changed = false; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1437 | if (isa<LoadInst>(I)) |
| 1438 | ++NumMovedLoads; |
| 1439 | else if (isa<CallInst>(I)) |
| 1440 | ++NumMovedCalls; |
Chris Lattner | 55c2113 | 2003-12-10 20:43:29 +0000 | [diff] [blame] | 1441 | ++NumSunk; |
Chris Lattner | 55c2113 | 2003-12-10 20:43:29 +0000 | [diff] [blame] | 1442 | |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1443 | // Iterate over users to be ready for actual sinking. Replace users via |
| 1444 | // unrechable blocks with undef and make all user PHIs trivially replcable. |
| 1445 | SmallPtrSet<Instruction *, 8> VisitedUsers; |
| 1446 | for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) { |
| 1447 | auto *User = cast<Instruction>(*UI); |
| 1448 | Use &U = UI.getUse(); |
| 1449 | ++UI; |
| 1450 | |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1451 | if (VisitedUsers.count(User) || CurLoop->contains(User)) |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1452 | continue; |
| 1453 | |
| 1454 | if (!DT->isReachableFromEntry(User->getParent())) { |
Jun Bum Lim | 0f90672 | 2017-11-17 20:38:25 +0000 | [diff] [blame] | 1455 | U = UndefValue::get(I.getType()); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1456 | Changed = true; |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1457 | continue; |
| 1458 | } |
| 1459 | |
| 1460 | // The user must be a PHI node. |
| 1461 | PHINode *PN = cast<PHINode>(User); |
| 1462 | |
| 1463 | // Surprisingly, instructions can be used outside of loops without any |
| 1464 | // exits. This can only happen in PHI nodes if the incoming block is |
| 1465 | // unreachable. |
| 1466 | BasicBlock *BB = PN->getIncomingBlock(U); |
| 1467 | if (!DT->isReachableFromEntry(BB)) { |
| 1468 | U = UndefValue::get(I.getType()); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1469 | Changed = true; |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1470 | continue; |
| 1471 | } |
| 1472 | |
| 1473 | VisitedUsers.insert(PN); |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1474 | if (isTriviallyReplaceablePHI(*PN, I)) |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1475 | continue; |
| 1476 | |
Jun Bum Lim | 144eb59 | 2018-02-12 17:56:55 +0000 | [diff] [blame] | 1477 | if (!canSplitPredecessors(PN, SafetyInfo)) |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1478 | return Changed; |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1479 | |
| 1480 | // Split predecessors of the PHI so that we can make users trivially |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1481 | // replaceable. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1482 | splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1483 | |
| 1484 | // Should rebuild the iterators, as they may be invalidated by |
| 1485 | // splitPredecessorsOfLoopExit(). |
| 1486 | UI = I.user_begin(); |
| 1487 | UE = I.user_end(); |
| 1488 | } |
| 1489 | |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1490 | if (VisitedUsers.empty()) |
| 1491 | return Changed; |
| 1492 | |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1493 | #ifndef NDEBUG |
| 1494 | SmallVector<BasicBlock *, 32> ExitBlocks; |
| 1495 | CurLoop->getUniqueExitBlocks(ExitBlocks); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1496 | SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1497 | ExitBlocks.end()); |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1498 | #endif |
Chandler Carruth | 8765cf7 | 2014-01-25 04:07:24 +0000 | [diff] [blame] | 1499 | |
Evgeniy Stepanov | 10280da | 2014-06-25 07:54:58 +0000 | [diff] [blame] | 1500 | // Clones of this instruction. Don't create more than one per exit block! |
| 1501 | SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; |
| 1502 | |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1503 | // If this instruction is only used outside of the loop, then all users are |
| 1504 | // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of |
| 1505 | // the instruction. |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1506 | SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end()); |
| 1507 | for (auto *UI : Users) { |
| 1508 | auto *User = cast<Instruction>(UI); |
| 1509 | |
| 1510 | if (CurLoop->contains(User)) |
| 1511 | continue; |
| 1512 | |
| 1513 | PHINode *PN = cast<PHINode>(User); |
Jun Bum Lim | f5fb3d7 | 2017-11-03 16:24:53 +0000 | [diff] [blame] | 1514 | assert(ExitBlockSet.count(PN->getParent()) && |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1515 | "The LCSSA PHI is not in an exit block!"); |
Alina Sbirlea | 0e15501 | 2018-07-02 18:53:40 +0000 | [diff] [blame] | 1516 | // The PHI must be trivially replaceable. |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1517 | Instruction *New = sinkThroughTriviallyReplaceablePHI( |
| 1518 | PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU); |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1519 | PN->replaceAllUsesWith(New); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1520 | eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr); |
Jun Bum Lim | 44c58d3 | 2017-12-15 20:33:24 +0000 | [diff] [blame] | 1521 | Changed = true; |
Chris Lattner | cd96b4d | 2010-08-29 04:28:20 +0000 | [diff] [blame] | 1522 | } |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1523 | return Changed; |
Chris Lattner | aaaea51 | 2003-12-10 06:41:05 +0000 | [diff] [blame] | 1524 | } |
Chris Lattner | 6443769 | 2002-09-29 21:46:09 +0000 | [diff] [blame] | 1525 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1526 | /// When an instruction is found to only use loop invariant operands that |
| 1527 | /// is safe to hoist, this instruction is called to do the dirty work. |
Chris Lattner | f64f2d3 | 2002-09-26 16:52:07 +0000 | [diff] [blame] | 1528 | /// |
Max Kazantsev | 68290f8 | 2018-08-15 02:49:12 +0000 | [diff] [blame] | 1529 | static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 1530 | BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1531 | MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) { |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 1532 | LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << I |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1533 | << "\n"); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1534 | ORE->emit([&]() { |
| 1535 | return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting " |
| 1536 | << ore::NV("Inst", &I); |
| 1537 | }); |
Sanjoy Das | 7a2e2be | 2016-01-28 15:51:58 +0000 | [diff] [blame] | 1538 | |
| 1539 | // Metadata can be dependent on conditions we are hoisting above. |
| 1540 | // Conservatively strip all metadata on the instruction unless we were |
| 1541 | // guaranteed to execute I if we entered the loop, in which case the metadata |
| 1542 | // is valid in the loop preheader. |
| 1543 | if (I.hasMetadataOtherThanDebugLoc() && |
| 1544 | // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning |
| 1545 | // time in isGuaranteedToExecute if we don't actually have anything to |
| 1546 | // drop. It is a compile time optimization, not required for correctness. |
Max Kazantsev | c8466f9 | 2018-10-16 06:34:53 +0000 | [diff] [blame] | 1547 | !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop)) |
Sanjoy Das | 7a2e2be | 2016-01-28 15:51:58 +0000 | [diff] [blame] | 1548 | I.dropUnknownNonDebugMetadata(); |
| 1549 | |
John Brawn | a7eb2c8 | 2018-11-29 17:10:00 +0000 | [diff] [blame] | 1550 | if (isa<PHINode>(I)) |
| 1551 | // Move the new node to the end of the phi list in the destination block. |
| 1552 | moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo); |
| 1553 | else |
| 1554 | // Move the new node to the destination block, before its terminator. |
| 1555 | moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo); |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1556 | if (MSSAU) { |
| 1557 | // If moving, I just moved a load or store, so update MemorySSA. |
| 1558 | MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>( |
| 1559 | MSSAU->getMemorySSA()->getMemoryAccess(&I)); |
| 1560 | if (OldMemAcc) |
| 1561 | MSSAU->moveToPlace(OldMemAcc, Dest, MemorySSA::End); |
| 1562 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1563 | |
Wolfgang Pieb | c17a279 | 2017-01-06 18:38:57 +0000 | [diff] [blame] | 1564 | // Do not retain debug locations when we are moving instructions to different |
| 1565 | // basic blocks, because we want to avoid jumpy line tables. Calls, however, |
| 1566 | // need to retain their debug locs because they may be inlined. |
| 1567 | // FIXME: How do we retain source locations without causing poor debugging |
| 1568 | // behavior? |
| 1569 | if (!isa<CallInst>(I)) |
| 1570 | I.setDebugLoc(DebugLoc()); |
| 1571 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1572 | if (isa<LoadInst>(I)) |
| 1573 | ++NumMovedLoads; |
| 1574 | else if (isa<CallInst>(I)) |
| 1575 | ++NumMovedCalls; |
Chris Lattner | 718b221 | 2002-09-26 16:38:03 +0000 | [diff] [blame] | 1576 | ++NumHoisted; |
Chris Lattner | 6ec05f5 | 2002-05-10 22:44:58 +0000 | [diff] [blame] | 1577 | } |
| 1578 | |
Sanjoy Das | f8a0db5 | 2015-05-18 18:07:00 +0000 | [diff] [blame] | 1579 | /// Only sink or hoist an instruction if it is not a trapping instruction, |
| 1580 | /// or if the instruction is known not to trap when moved to the preheader. |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1581 | /// or if it is a trapping instruction and is guaranteed to execute. |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1582 | static bool isSafeToExecuteUnconditionally(Instruction &Inst, |
Pete Cooper | 0cabcf2 | 2015-05-13 01:12:18 +0000 | [diff] [blame] | 1583 | const DominatorTree *DT, |
| 1584 | const Loop *CurLoop, |
Evgeniy Stepanov | 122f984 | 2016-06-10 20:03:17 +0000 | [diff] [blame] | 1585 | const LoopSafetyInfo *SafetyInfo, |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1586 | OptimizationRemarkEmitter *ORE, |
Philip Reames | b47b9c2 | 2015-05-22 02:14:05 +0000 | [diff] [blame] | 1587 | const Instruction *CtxI) { |
Sean Silva | 45835e7 | 2016-07-02 23:47:27 +0000 | [diff] [blame] | 1588 | if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT)) |
Eli Friedman | b8f6a4f | 2009-07-17 04:28:42 +0000 | [diff] [blame] | 1589 | return true; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1590 | |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1591 | bool GuaranteedToExecute = |
Max Kazantsev | c8466f9 | 2018-10-16 06:34:53 +0000 | [diff] [blame] | 1592 | SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop); |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1593 | |
| 1594 | if (!GuaranteedToExecute) { |
| 1595 | auto *LI = dyn_cast<LoadInst>(&Inst); |
| 1596 | if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand())) |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1597 | ORE->emit([&]() { |
| 1598 | return OptimizationRemarkMissed( |
| 1599 | DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI) |
| 1600 | << "failed to hoist load with loop-invariant address " |
| 1601 | "because load is conditionally executed"; |
| 1602 | }); |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1603 | } |
| 1604 | |
| 1605 | return GuaranteedToExecute; |
Eli Friedman | 0cdc148 | 2011-07-20 21:37:47 +0000 | [diff] [blame] | 1606 | } |
| 1607 | |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1608 | namespace { |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1609 | class LoopPromoter : public LoadAndStorePromoter { |
| 1610 | Value *SomePtr; // Designated pointer to store to. |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1611 | const SmallSetVector<Value *, 8> &PointerMustAliases; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1612 | SmallVectorImpl<BasicBlock *> &LoopExitBlocks; |
| 1613 | SmallVectorImpl<Instruction *> &LoopInsertPts; |
| 1614 | PredIteratorCache &PredCache; |
| 1615 | AliasSetTracker &AST; |
| 1616 | LoopInfo &LI; |
| 1617 | DebugLoc DL; |
| 1618 | int Alignment; |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1619 | bool UnorderedAtomic; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1620 | AAMDNodes AATags; |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1621 | ICFLoopSafetyInfo &SafetyInfo; |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1622 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1623 | Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { |
| 1624 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 1625 | if (Loop *L = LI.getLoopFor(I->getParent())) |
| 1626 | if (!L->contains(BB)) { |
| 1627 | // We need to create an LCSSA PHI node for the incoming value and |
| 1628 | // store that. |
| 1629 | PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), |
| 1630 | I->getName() + ".lcssa", &BB->front()); |
| 1631 | for (BasicBlock *Pred : PredCache.get(BB)) |
| 1632 | PN->addIncoming(I, Pred); |
| 1633 | return PN; |
| 1634 | } |
| 1635 | return V; |
| 1636 | } |
Chandler Carruth | fc25854 | 2014-02-11 12:52:27 +0000 | [diff] [blame] | 1637 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1638 | public: |
| 1639 | LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1640 | const SmallSetVector<Value *, 8> &PMA, |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1641 | SmallVectorImpl<BasicBlock *> &LEB, |
| 1642 | SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, |
| 1643 | AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1644 | bool UnorderedAtomic, const AAMDNodes &AATags, |
| 1645 | ICFLoopSafetyInfo &SafetyInfo) |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1646 | : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), |
| 1647 | LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1648 | LI(li), DL(std::move(dl)), Alignment(alignment), |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1649 | UnorderedAtomic(UnorderedAtomic), AATags(AATags), SafetyInfo(SafetyInfo) |
| 1650 | {} |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1651 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1652 | bool isInstInList(Instruction *I, |
| 1653 | const SmallVectorImpl<Instruction *> &) const override { |
| 1654 | Value *Ptr; |
| 1655 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) |
| 1656 | Ptr = LI->getOperand(0); |
| 1657 | else |
| 1658 | Ptr = cast<StoreInst>(I)->getPointerOperand(); |
| 1659 | return PointerMustAliases.count(Ptr); |
| 1660 | } |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1661 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1662 | void doExtraRewritesBeforeFinalDeletion() const override { |
| 1663 | // Insert stores after in the loop exit blocks. Each exit block gets a |
| 1664 | // store of the live-out values that feed them. Since we've already told |
| 1665 | // the SSA updater about the defs in the loop and the preheader |
| 1666 | // definition, it is all set and we can start using it. |
| 1667 | for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { |
| 1668 | BasicBlock *ExitBlock = LoopExitBlocks[i]; |
| 1669 | Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); |
| 1670 | LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); |
| 1671 | Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); |
| 1672 | Instruction *InsertPos = LoopInsertPts[i]; |
| 1673 | StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1674 | if (UnorderedAtomic) |
| 1675 | NewSI->setOrdering(AtomicOrdering::Unordered); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1676 | NewSI->setAlignment(Alignment); |
| 1677 | NewSI->setDebugLoc(DL); |
| 1678 | if (AATags) |
| 1679 | NewSI->setAAMetadata(AATags); |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1680 | } |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1681 | } |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1682 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1683 | void replaceLoadWithValue(LoadInst *LI, Value *V) const override { |
| 1684 | // Update alias analysis. |
| 1685 | AST.copyValue(LI, V); |
| 1686 | } |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1687 | void instructionDeleted(Instruction *I) const override { |
| 1688 | SafetyInfo.removeInstruction(I); |
| 1689 | AST.deleteValue(I); |
| 1690 | } |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1691 | }; |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1692 | |
| 1693 | |
| 1694 | /// Return true iff we can prove that a caller of this function can not inspect |
| 1695 | /// the contents of the provided object in a well defined program. |
| 1696 | bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) { |
| 1697 | if (isa<AllocaInst>(Object)) |
| 1698 | // Since the alloca goes out of scope, we know the caller can't retain a |
| 1699 | // reference to it and be well defined. Thus, we don't need to check for |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1700 | // capture. |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1701 | return true; |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1702 | |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1703 | // For all other objects we need to know that the caller can't possibly |
| 1704 | // have gotten a reference to the object. There are two components of |
| 1705 | // that: |
| 1706 | // 1) Object can't be escaped by this function. This is what |
| 1707 | // PointerMayBeCaptured checks. |
| 1708 | // 2) Object can't have been captured at definition site. For this, we |
| 1709 | // need to know the return value is noalias. At the moment, we use a |
| 1710 | // weaker condition and handle only AllocLikeFunctions (which are |
| 1711 | // known to be noalias). TODO |
| 1712 | return isAllocLikeFn(Object, TLI) && |
| 1713 | !PointerMayBeCaptured(Object, true, true); |
| 1714 | } |
| 1715 | |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1716 | } // namespace |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1717 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1718 | /// Try to promote memory values to scalars by sinking stores out of the |
| 1719 | /// loop and moving loads to before the loop. We do this by looping over |
| 1720 | /// the stores in the loop, looking for stores to Must pointers which are |
| 1721 | /// loop invariant. |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 1722 | /// |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1723 | bool llvm::promoteLoopAccessesToScalars( |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1724 | const SmallSetVector<Value *, 8> &PointerMustAliases, |
| 1725 | SmallVectorImpl<BasicBlock *> &ExitBlocks, |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1726 | SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC, |
| 1727 | LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1728 | Loop *CurLoop, AliasSetTracker *CurAST, ICFLoopSafetyInfo *SafetyInfo, |
Adam Nemet | 358433c | 2017-01-11 04:39:35 +0000 | [diff] [blame] | 1729 | OptimizationRemarkEmitter *ORE) { |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1730 | // Verify inputs. |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1731 | assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && |
| 1732 | CurAST != nullptr && SafetyInfo != nullptr && |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1733 | "Unexpected Input to promoteLoopAccessesToScalars"); |
Sanjay Patel | 9913322 | 2016-01-13 23:01:57 +0000 | [diff] [blame] | 1734 | |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1735 | Value *SomePtr = *PointerMustAliases.begin(); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1736 | BasicBlock *Preheader = CurLoop->getLoopPreheader(); |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 1737 | |
Anna Thomas | 5ac72f9 | 2018-03-13 19:38:45 +0000 | [diff] [blame] | 1738 | // It is not safe to promote a load/store from the loop if the load/store is |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1739 | // conditional. For example, turning: |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 1740 | // |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1741 | // for () { if (c) *P += 1; } |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 1742 | // |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1743 | // into: |
| 1744 | // |
| 1745 | // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; |
| 1746 | // |
| 1747 | // is not safe, because *P may only be valid to access if 'c' is true. |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1748 | // |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1749 | // The safety property divides into two parts: |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1750 | // p1) The memory may not be dereferenceable on entry to the loop. In this |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1751 | // case, we can't insert the required load in the preheader. |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1752 | // p2) The memory model does not allow us to insert a store along any dynamic |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1753 | // path which did not originally have one. |
| 1754 | // |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1755 | // If at least one store is guaranteed to execute, both properties are |
| 1756 | // satisfied, and promotion is legal. |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1757 | // |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1758 | // This, however, is not a necessary condition. Even if no store/load is |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1759 | // guaranteed to execute, we can still establish these properties. |
| 1760 | // We can establish (p1) by proving that hoisting the load into the preheader |
| 1761 | // is safe (i.e. proving dereferenceability on all paths through the loop). We |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1762 | // can use any access within the alias set to prove dereferenceability, |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1763 | // since they're all must alias. |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1764 | // |
| 1765 | // There are two ways establish (p2): |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1766 | // a) Prove the location is thread-local. In this case the memory model |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1767 | // requirement does not apply, and stores are safe to insert. |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1768 | // b) Prove a store dominates every exit block. In this case, if an exit |
| 1769 | // blocks is reached, the original dynamic path would have taken us through |
| 1770 | // the store, so inserting a store into the exit block is safe. Note that this |
| 1771 | // is different from the store being guaranteed to execute. For instance, |
| 1772 | // if an exception is thrown on the first iteration of the loop, the original |
| 1773 | // store is never executed, but the exit blocks are not executed either. |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1774 | |
| 1775 | bool DereferenceableInPH = false; |
| 1776 | bool SafeToInsertStore = false; |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1777 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1778 | SmallVector<Instruction *, 64> LoopUses; |
Chris Lattner | 45d67d6 | 2003-02-24 03:52:32 +0000 | [diff] [blame] | 1779 | |
Tobias Grosser | 4a5d9a9 | 2011-07-06 19:19:55 +0000 | [diff] [blame] | 1780 | // We start with an alignment of one and try to find instructions that allow |
| 1781 | // us to prove better alignment. |
| 1782 | unsigned Alignment = 1; |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1783 | // Keep track of which types of access we see |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1784 | bool SawUnorderedAtomic = false; |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1785 | bool SawNotAtomic = false; |
Hal Finkel | cc39b67 | 2014-07-24 12:16:19 +0000 | [diff] [blame] | 1786 | AAMDNodes AATags; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1787 | |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1788 | const DataLayout &MDL = Preheader->getModule()->getDataLayout(); |
| 1789 | |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1790 | bool IsKnownThreadLocalObject = false; |
Max Kazantsev | 530b8d1 | 2018-08-15 05:55:43 +0000 | [diff] [blame] | 1791 | if (SafetyInfo->anyBlockMayThrow()) { |
Eli Friedman | ee89505 | 2016-06-05 22:13:52 +0000 | [diff] [blame] | 1792 | // If a loop can throw, we have to insert a store along each unwind edge. |
| 1793 | // That said, we can't actually make the unwind edge explicit. Therefore, |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1794 | // we have to prove that the store is dead along the unwind edge. We do |
| 1795 | // this by proving that the caller can't have a reference to the object |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1796 | // after return and thus can't possibly load from the object. |
Xin Tong | 5ee40ba | 2017-01-19 19:31:40 +0000 | [diff] [blame] | 1797 | Value *Object = GetUnderlyingObject(SomePtr, MDL); |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1798 | if (!isKnownNonEscaping(Object, TLI)) |
| 1799 | return false; |
| 1800 | // Subtlety: Alloca's aren't visible to callers, but *are* potentially |
| 1801 | // visible to other threads if captured and used during their lifetimes. |
| 1802 | IsKnownThreadLocalObject = !isa<AllocaInst>(Object); |
Eli Friedman | ee89505 | 2016-06-05 22:13:52 +0000 | [diff] [blame] | 1803 | } |
| 1804 | |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1805 | // Check that all of the pointers in the alias set have the same type. We |
| 1806 | // cannot (yet) promote a memory location that is loaded and stored in |
Hal Finkel | cc39b67 | 2014-07-24 12:16:19 +0000 | [diff] [blame] | 1807 | // different sizes. While we are at it, collect alignment and AA info. |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1808 | for (Value *ASIV : PointerMustAliases) { |
Chris Lattner | f12c08d | 2008-05-22 00:53:38 +0000 | [diff] [blame] | 1809 | // Check that all of the pointers in the alias set have the same type. We |
| 1810 | // cannot (yet) promote a memory location that is loaded and stored in |
| 1811 | // different sizes. |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1812 | if (SomePtr->getType() != ASIV->getType()) |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1813 | return false; |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1814 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1815 | for (User *U : ASIV->users()) { |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1816 | // Ignore instructions that are outside the loop. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1817 | Instruction *UI = dyn_cast<Instruction>(U); |
| 1818 | if (!UI || !CurLoop->contains(UI)) |
Chris Lattner | f12c08d | 2008-05-22 00:53:38 +0000 | [diff] [blame] | 1819 | continue; |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1820 | |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1821 | // If there is an non-load/store instruction in the loop, we can't promote |
| 1822 | // it. |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1823 | if (LoadInst *Load = dyn_cast<LoadInst>(UI)) { |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1824 | if (!Load->isUnordered()) |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1825 | return false; |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1826 | |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1827 | SawUnorderedAtomic |= Load->isAtomic(); |
| 1828 | SawNotAtomic |= !Load->isAtomic(); |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1829 | |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1830 | if (!DereferenceableInPH) |
| 1831 | DereferenceableInPH = isSafeToExecuteUnconditionally( |
Adam Nemet | e2aaf3a | 2017-01-11 04:39:49 +0000 | [diff] [blame] | 1832 | *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator()); |
Sanjay Patel | 9f49b68 | 2016-01-08 22:05:03 +0000 | [diff] [blame] | 1833 | } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { |
Chris Lattner | 408a684 | 2010-12-19 05:57:25 +0000 | [diff] [blame] | 1834 | // Stores *of* the pointer are not interesting, only stores *to* the |
| 1835 | // pointer. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1836 | if (UI->getOperand(1) != ASIV) |
Chris Lattner | 408a684 | 2010-12-19 05:57:25 +0000 | [diff] [blame] | 1837 | continue; |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1838 | if (!Store->isUnordered()) |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1839 | return false; |
Eli Friedman | 0cdc148 | 2011-07-20 21:37:47 +0000 | [diff] [blame] | 1840 | |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1841 | SawUnorderedAtomic |= Store->isAtomic(); |
| 1842 | SawNotAtomic |= !Store->isAtomic(); |
| 1843 | |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1844 | // If the store is guaranteed to execute, both properties are satisfied. |
| 1845 | // We may want to check if a store is guaranteed to execute even if we |
| 1846 | // already know that promotion is safe, since it may have higher |
| 1847 | // alignment than any other guaranteed stores, in which case we can |
| 1848 | // raise the alignment on the promoted store. |
Sanjay Patel | 9f49b68 | 2016-01-08 22:05:03 +0000 | [diff] [blame] | 1849 | unsigned InstAlignment = Store->getAlignment(); |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1850 | if (!InstAlignment) |
| 1851 | InstAlignment = |
| 1852 | MDL.getABITypeAlignment(Store->getValueOperand()->getType()); |
| 1853 | |
| 1854 | if (!DereferenceableInPH || !SafeToInsertStore || |
| 1855 | (InstAlignment > Alignment)) { |
Max Kazantsev | c8466f9 | 2018-10-16 06:34:53 +0000 | [diff] [blame] | 1856 | if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) { |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1857 | DereferenceableInPH = true; |
| 1858 | SafeToInsertStore = true; |
| 1859 | Alignment = std::max(Alignment, InstAlignment); |
Eli Friedman | 0cdc148 | 2011-07-20 21:37:47 +0000 | [diff] [blame] | 1860 | } |
Anna Thomas | 6715135 | 2016-06-24 12:38:45 +0000 | [diff] [blame] | 1861 | } |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1862 | |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1863 | // If a store dominates all exit blocks, it is safe to sink. |
| 1864 | // As explained above, if an exit block was executed, a dominating |
Fangrui Song | 956ee79 | 2018-03-30 22:22:31 +0000 | [diff] [blame] | 1865 | // store must have been executed at least once, so we are not |
Michael Kuperstein | c9acad1 | 2017-01-05 20:42:06 +0000 | [diff] [blame] | 1866 | // introducing stores on paths that did not have them. |
| 1867 | // Note that this only looks at explicit exit blocks. If we ever |
| 1868 | // start sinking stores into unwind edges (see above), this will break. |
| 1869 | if (!SafeToInsertStore) |
| 1870 | SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) { |
| 1871 | return DT->dominates(Store->getParent(), Exit); |
| 1872 | }); |
| 1873 | |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1874 | // If the store is not guaranteed to execute, we may still get |
| 1875 | // deref info through it. |
| 1876 | if (!DereferenceableInPH) { |
| 1877 | DereferenceableInPH = isDereferenceableAndAlignedPointer( |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1878 | Store->getPointerOperand(), Store->getAlignment(), MDL, |
Sean Silva | 45835e7 | 2016-07-02 23:47:27 +0000 | [diff] [blame] | 1879 | Preheader->getTerminator(), DT); |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1880 | } |
Chris Lattner | be90190 | 2010-09-06 05:11:24 +0000 | [diff] [blame] | 1881 | } else |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1882 | return false; // Not a load or store. |
Tobias Grosser | 4a5d9a9 | 2011-07-06 19:19:55 +0000 | [diff] [blame] | 1883 | |
Hal Finkel | cc39b67 | 2014-07-24 12:16:19 +0000 | [diff] [blame] | 1884 | // Merge the AA tags. |
Chris Lattner | f5cca68 | 2012-12-31 08:37:17 +0000 | [diff] [blame] | 1885 | if (LoopUses.empty()) { |
Hal Finkel | cc39b67 | 2014-07-24 12:16:19 +0000 | [diff] [blame] | 1886 | // On the first load/store, just take its AA tags. |
| 1887 | UI->getAAMetadata(AATags); |
| 1888 | } else if (AATags) { |
| 1889 | UI->getAAMetadata(AATags, /* Merge = */ true); |
Chris Lattner | f5cca68 | 2012-12-31 08:37:17 +0000 | [diff] [blame] | 1890 | } |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1891 | |
| 1892 | LoopUses.push_back(UI); |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1893 | } |
| 1894 | } |
Tobias Grosser | 4a5d9a9 | 2011-07-06 19:19:55 +0000 | [diff] [blame] | 1895 | |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1896 | // If we found both an unordered atomic instruction and a non-atomic memory |
| 1897 | // access, bail. We can't blindly promote non-atomic to atomic since we |
| 1898 | // might not be able to lower the result. We can't downgrade since that |
| 1899 | // would violate memory model. Also, align 0 is an error for atomics. |
| 1900 | if (SawUnorderedAtomic && SawNotAtomic) |
| 1901 | return false; |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1902 | |
| 1903 | // If we couldn't prove we can hoist the load, bail. |
| 1904 | if (!DereferenceableInPH) |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1905 | return false; |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1906 | |
| 1907 | // We know we can hoist the load, but don't have a guaranteed store. |
| 1908 | // Check whether the location is thread-local. If it is, then we can insert |
| 1909 | // stores along paths which originally didn't have them without violating the |
| 1910 | // memory model. |
| 1911 | if (!SafeToInsertStore) { |
Philip Reames | 21cc2fa | 2017-10-26 21:00:15 +0000 | [diff] [blame] | 1912 | if (IsKnownThreadLocalObject) |
Xin Tong | 5ee40ba | 2017-01-19 19:31:40 +0000 | [diff] [blame] | 1913 | SafeToInsertStore = true; |
| 1914 | else { |
| 1915 | Value *Object = GetUnderlyingObject(SomePtr, MDL); |
| 1916 | SafeToInsertStore = |
Alina Sbirlea | 80b806b | 2017-09-12 21:18:44 +0000 | [diff] [blame] | 1917 | (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) && |
| 1918 | !PointerMayBeCaptured(Object, true, true); |
Xin Tong | 5ee40ba | 2017-01-19 19:31:40 +0000 | [diff] [blame] | 1919 | } |
Philip Reames | b54c8e6 | 2016-03-09 22:59:30 +0000 | [diff] [blame] | 1920 | } |
Michael Kuperstein | ff36bae | 2016-12-29 23:11:19 +0000 | [diff] [blame] | 1921 | |
Michael Kuperstein | 62b98c3 | 2016-12-30 00:39:00 +0000 | [diff] [blame] | 1922 | // If we've still failed to prove we can sink the store, give up. |
| 1923 | if (!SafeToInsertStore) |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1924 | return false; |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1925 | |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1926 | // Otherwise, this is safe to promote, lets do it! |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1927 | LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr |
| 1928 | << '\n'); |
Vivek Pandya | 9590658 | 2017-10-11 17:12:59 +0000 | [diff] [blame] | 1929 | ORE->emit([&]() { |
| 1930 | return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", |
| 1931 | LoopUses[0]) |
| 1932 | << "Moving accesses to memory location out of the loop"; |
| 1933 | }); |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1934 | ++NumPromoted; |
| 1935 | |
Eli Friedman | ddf7f55 | 2011-05-27 20:31:51 +0000 | [diff] [blame] | 1936 | // Grab a debug location for the inserted loads/stores; given that the |
| 1937 | // inserted loads/stores have little relation to the original loads/stores, |
| 1938 | // this code just arbitrarily picks a location from one, since any debug |
| 1939 | // location is better than none. |
| 1940 | DebugLoc DL = LoopUses[0]->getDebugLoc(); |
| 1941 | |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1942 | // We use the SSAUpdater interface to insert phi nodes as required. |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1943 | SmallVector<PHINode *, 16> NewPHIs; |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1944 | SSAUpdater SSA(&NewPHIs); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1945 | LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1946 | InsertPts, PIC, *CurAST, *LI, DL, Alignment, |
Max Kazantsev | 69f6dfa | 2018-11-06 02:44:49 +0000 | [diff] [blame] | 1947 | SawUnorderedAtomic, AATags, *SafetyInfo); |
Tobias Grosser | a3928f5 | 2011-07-06 19:20:02 +0000 | [diff] [blame] | 1948 | |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1949 | // Set up the preheader to have a definition of the value. It is the live-out |
| 1950 | // value from the preheader that uses in the loop will use. |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1951 | LoadInst *PreheaderLoad = new LoadInst( |
| 1952 | SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator()); |
Philip Reames | b2bca7e | 2017-02-14 01:38:31 +0000 | [diff] [blame] | 1953 | if (SawUnorderedAtomic) |
| 1954 | PreheaderLoad->setOrdering(AtomicOrdering::Unordered); |
Tobias Grosser | 4a5d9a9 | 2011-07-06 19:19:55 +0000 | [diff] [blame] | 1955 | PreheaderLoad->setAlignment(Alignment); |
Eli Friedman | ddf7f55 | 2011-05-27 20:31:51 +0000 | [diff] [blame] | 1956 | PreheaderLoad->setDebugLoc(DL); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 1957 | if (AATags) |
| 1958 | PreheaderLoad->setAAMetadata(AATags); |
Chris Lattner | 1dc98b4 | 2010-08-29 06:43:52 +0000 | [diff] [blame] | 1959 | SSA.AddAvailableValue(Preheader, PreheaderLoad); |
| 1960 | |
Chris Lattner | b68ec5c | 2011-01-15 00:12:35 +0000 | [diff] [blame] | 1961 | // Rewrite all the loads in the loop and remember all the definitions from |
| 1962 | // stores in the loop. |
| 1963 | Promoter.run(LoopUses); |
Eli Friedman | c5f22a7 | 2011-04-07 01:35:06 +0000 | [diff] [blame] | 1964 | |
| 1965 | // If the SSAUpdater didn't use the load in the preheader, just zap it now. |
| 1966 | if (PreheaderLoad->use_empty()) |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 1967 | eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, nullptr); |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 1968 | |
Michael Kuperstein | 4a86a19 | 2016-12-30 00:43:22 +0000 | [diff] [blame] | 1969 | return true; |
Chris Lattner | a51fa88 | 2002-08-22 21:39:55 +0000 | [diff] [blame] | 1970 | } |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 1971 | |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1972 | /// Returns an owning pointer to an alias set which incorporates aliasing info |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 1973 | /// from L and all subloops of L. |
Xinliang David Li | cbb5e02 | 2016-08-11 22:34:00 +0000 | [diff] [blame] | 1974 | /// FIXME: In new pass manager, there is no helper function to handle loop |
| 1975 | /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 1976 | /// from scratch for every loop. Hook up with the helper functions when |
| 1977 | /// available in the new pass manager to avoid redundant computation. |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 1978 | std::unique_ptr<AliasSetTracker> |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 1979 | LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI, |
| 1980 | AliasAnalysis *AA) { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 1981 | std::unique_ptr<AliasSetTracker> CurAST; |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 1982 | SmallVector<Loop *, 4> RecomputeLoops; |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1983 | for (Loop *InnerL : L->getSubLoops()) { |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 1984 | auto MapI = LoopToAliasSetMap.find(InnerL); |
| 1985 | // If the AST for this inner loop is missing it may have been merged into |
| 1986 | // some other loop's AST and then that loop unrolled, and so we need to |
| 1987 | // recompute it. |
| 1988 | if (MapI == LoopToAliasSetMap.end()) { |
| 1989 | RecomputeLoops.push_back(InnerL); |
| 1990 | continue; |
| 1991 | } |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 1992 | std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second); |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1993 | |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 1994 | if (CurAST) { |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1995 | // What if InnerLoop was modified by other passes ? |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1996 | // Once we've incorporated the inner loop's AST into ours, we don't need |
| 1997 | // the subloop's anymore. |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 1998 | CurAST->add(*InnerAST); |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 1999 | } else { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2000 | CurAST = std::move(InnerAST); |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 2001 | } |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 2002 | LoopToAliasSetMap.erase(MapI); |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 2003 | } |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2004 | if (!CurAST) |
| 2005 | CurAST = make_unique<AliasSetTracker>(*AA); |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 2006 | |
| 2007 | // Add everything from the sub loops that are no longer directly available. |
| 2008 | for (Loop *InnerL : RecomputeLoops) |
Serguei Katkov | 5f4a9e9 | 2018-09-11 04:07:36 +0000 | [diff] [blame] | 2009 | for (BasicBlock *BB : InnerL->blocks()) |
| 2010 | CurAST->add(*BB); |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 2011 | |
Serguei Katkov | 5f4a9e9 | 2018-09-11 04:07:36 +0000 | [diff] [blame] | 2012 | // And merge in this loop (without anything from inner loops). |
| 2013 | for (BasicBlock *BB : L->blocks()) |
| 2014 | if (LI->getLoopFor(BB) == L) |
| 2015 | CurAST->add(*BB); |
Chandler Carruth | ad8cb38 | 2016-02-27 04:34:07 +0000 | [diff] [blame] | 2016 | |
Roman Gareev | 036c088 | 2016-02-15 14:48:50 +0000 | [diff] [blame] | 2017 | return CurAST; |
| 2018 | } |
| 2019 | |
Ashutosh Nema | 4780262 | 2015-08-13 11:18:35 +0000 | [diff] [blame] | 2020 | /// Simple analysis hook. Clone alias set info. |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2021 | /// |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 2022 | void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, |
| 2023 | Loop *L) { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2024 | auto ASTIt = LICM.getLoopToAliasSetMap().find(L); |
| 2025 | if (ASTIt == LICM.getLoopToAliasSetMap().end()) |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 2026 | return; |
| 2027 | |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2028 | ASTIt->second->copyValue(From, To); |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 2029 | } |
| 2030 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2031 | /// Simple Analysis hook. Delete value V from alias set |
| 2032 | /// |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 2033 | void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2034 | auto ASTIt = LICM.getLoopToAliasSetMap().find(L); |
| 2035 | if (ASTIt == LICM.getLoopToAliasSetMap().end()) |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 2036 | return; |
| 2037 | |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2038 | ASTIt->second->deleteValue(V); |
Devang Patel | b98a097 | 2007-07-31 08:01:41 +0000 | [diff] [blame] | 2039 | } |
David Peixotto | 0d4d5e6 | 2014-09-24 16:48:31 +0000 | [diff] [blame] | 2040 | |
| 2041 | /// Simple Analysis hook. Delete value L from alias set map. |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2042 | /// |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 2043 | void LegacyLICMPass::deleteAnalysisLoop(Loop *L) { |
Marcello Maggioni | 883fe45 | 2018-08-21 20:30:14 +0000 | [diff] [blame] | 2044 | if (!LICM.getLoopToAliasSetMap().count(L)) |
David Peixotto | 0d4d5e6 | 2014-09-24 16:48:31 +0000 | [diff] [blame] | 2045 | return; |
| 2046 | |
Dehao Chen | 9cba1f4 | 2016-07-12 22:37:48 +0000 | [diff] [blame] | 2047 | LICM.getLoopToAliasSetMap().erase(L); |
David Peixotto | 0d4d5e6 | 2014-09-24 16:48:31 +0000 | [diff] [blame] | 2048 | } |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2049 | |
Anna Thomas | 1962621 | 2018-08-17 13:44:00 +0000 | [diff] [blame] | 2050 | static bool pointerInvalidatedByLoop(MemoryLocation MemLoc, |
| 2051 | AliasSetTracker *CurAST, Loop *CurLoop, |
| 2052 | AliasAnalysis *AA) { |
| 2053 | // First check to see if any of the basic blocks in CurLoop invalidate *V. |
| 2054 | bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod(); |
| 2055 | |
| 2056 | if (!isInvalidatedAccordingToAST || !LICMN2Theshold) |
| 2057 | return isInvalidatedAccordingToAST; |
| 2058 | |
| 2059 | // Check with a diagnostic analysis if we can refine the information above. |
| 2060 | // This is to identify the limitations of using the AST. |
| 2061 | // The alias set mechanism used by LICM has a major weakness in that it |
| 2062 | // combines all things which may alias into a single set *before* asking |
| 2063 | // modref questions. As a result, a single readonly call within a loop will |
| 2064 | // collapse all loads and stores into a single alias set and report |
| 2065 | // invalidation if the loop contains any store. For example, readonly calls |
| 2066 | // with deopt states have this form and create a general alias set with all |
| 2067 | // loads and stores. In order to get any LICM in loops containing possible |
| 2068 | // deopt states we need a more precise invalidation of checking the mod ref |
| 2069 | // info of each instruction within the loop and LI. This has a complexity of |
| 2070 | // O(N^2), so currently, it is used only as a diagnostic tool since the |
| 2071 | // default value of LICMN2Threshold is zero. |
| 2072 | |
| 2073 | // Don't look at nested loops. |
| 2074 | if (CurLoop->begin() != CurLoop->end()) |
| 2075 | return true; |
| 2076 | |
| 2077 | int N = 0; |
| 2078 | for (BasicBlock *BB : CurLoop->getBlocks()) |
| 2079 | for (Instruction &I : *BB) { |
| 2080 | if (N >= LICMN2Theshold) { |
| 2081 | LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for " |
| 2082 | << *(MemLoc.Ptr) << "\n"); |
| 2083 | return true; |
| 2084 | } |
| 2085 | N++; |
| 2086 | auto Res = AA->getModRefInfo(&I, MemLoc); |
| 2087 | if (isModSet(Res)) { |
| 2088 | LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for " |
| 2089 | << *(MemLoc.Ptr) << "\n"); |
| 2090 | return true; |
| 2091 | } |
| 2092 | } |
| 2093 | LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n"); |
| 2094 | return false; |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2095 | } |
| 2096 | |
Alina Sbirlea | cae12ed | 2019-01-10 19:29:04 +0000 | [diff] [blame] | 2097 | static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU, |
| 2098 | Loop *CurLoop) { |
| 2099 | MemoryAccess *Source; |
| 2100 | // See declaration of EnableLicmCap for usage details. |
| 2101 | if (EnableLicmCap) |
| 2102 | Source = MU->getDefiningAccess(); |
| 2103 | else |
| 2104 | Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU); |
| 2105 | return !MSSA->isLiveOnEntryDef(Source) && |
| 2106 | CurLoop->contains(Source->getBlock()); |
| 2107 | } |
| 2108 | |
Hal Finkel | 3d4269a | 2015-02-22 18:35:32 +0000 | [diff] [blame] | 2109 | /// Little predicate that returns true if the specified basic block is in |
| 2110 | /// a subloop of the current one, not the current one itself. |
| 2111 | /// |
| 2112 | static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { |
| 2113 | assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); |
| 2114 | return LI->getLoopFor(BB) != CurLoop; |
| 2115 | } |