blob: e9ea5ed9648cd598a22592652441ba47a7fbe9eb [file] [log] [blame]
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohman79618d12009-01-15 22:01:38 +000013// This pass is not intended to be a replacement or a complete alternative
14// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15// constructs that are not exposed before lowering and instruction selection.
16//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000017//===----------------------------------------------------------------------===//
18
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000019#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000024#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000027#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Matthias Braun88e21312015-06-13 03:42:11 +000030#include "llvm/CodeGen/TargetSchedule.h"
Evan Chengb35afca2011-10-12 21:33:49 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000032#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "machine-licm"
42
Evan Chengb35afca2011-10-12 21:33:49 +000043static cl::opt<bool>
44AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000046 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000047
Hal Finkel0709f512015-01-08 22:10:48 +000048static cl::opt<bool>
49HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
52
Daniel Jasper15e69542015-03-14 10:58:38 +000053static cl::opt<bool>
54SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
58
Evan Cheng44436302010-10-16 02:20:26 +000059STATISTIC(NumHoisted,
60 "Number of machine instructions hoisted out of loops");
61STATISTIC(NumLowRP,
62 "Number of instructions hoisted in low reg pressure situation");
63STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
65STATISTIC(NumCSEed,
66 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000067STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000069
Bill Wendlingfb706bc2007-12-07 21:42:31 +000070namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000071 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000072 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000073 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000074 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000075 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000076 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +000077 TargetSchedModel SchedModel;
Andrew Trickc40815d2012-02-08 21:23:03 +000078 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000079
Bill Wendlingfb706bc2007-12-07 21:42:31 +000080 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000081 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000082 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000083 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000084
Bill Wendlingfb706bc2007-12-07 21:42:31 +000085 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000086 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000087 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000088 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000089 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000090
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000091 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
93
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
96 ExitBlocks.end();
97 }
98
Evan Chengd62719c2010-10-14 01:16:09 +000099 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000100 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000101 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000102
Daniel Jasper274928f2015-04-14 11:56:25 +0000103 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000104 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000105 SmallVector<unsigned, 8> RegLimit;
106
Evan Cheng44436302010-10-16 02:20:26 +0000107 // Register pressure on path leading from loop preheader to current BB.
108 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
109
Dale Johannesen329d4742010-07-29 17:45:24 +0000110 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000111 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000112
Evan Chengf192ca02011-10-11 23:48:44 +0000113 enum {
114 SpeculateFalse = 0,
115 SpeculateTrue = 1,
116 SpeculateUnknown = 2
117 };
118
Devang Patel453d4012011-10-11 18:09:58 +0000119 // If a MBB does not dominate loop exiting blocks then it may not safe
120 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000121 // Tri-state: 0 - false, 1 - true, 2 - unknown
122 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000123
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000124 public:
125 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000126 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000127 MachineFunctionPass(ID), PreRegAlloc(true) {
128 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
129 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000130
131 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000132 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
134 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000135
Craig Topper4584cd52014-03-07 09:26:03 +0000136 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000137
Craig Topper4584cd52014-03-07 09:26:03 +0000138 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000139 AU.addRequired<MachineLoopInfo>();
140 AU.addRequired<MachineDominatorTree>();
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000141 AU.addRequired<AliasAnalysis>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000142 AU.addPreserved<MachineLoopInfo>();
143 AU.addPreserved<MachineDominatorTree>();
144 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000145 }
Evan Cheng399660c2009-02-05 08:45:46 +0000146
Craig Topper4584cd52014-03-07 09:26:03 +0000147 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000148 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000149 RegPressure.clear();
150 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000151 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000152 CSEMap.clear();
153 }
154
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000155 private:
Evan Cheng058b9f02010-04-08 01:03:47 +0000156 /// CandidateInfo - Keep track of information about hoisting candidates.
157 struct CandidateInfo {
158 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000159 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000160 int FI;
161 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000163 };
164
165 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
166 /// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000167 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000168
169 /// HoistPostRA - When an instruction is found to only use loop invariant
170 /// operands that is safe to hoist, this instruction is called to do the
171 /// dirty work.
172 void HoistPostRA(MachineInstr *MI, unsigned Def);
173
174 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
175 /// gather register def and frame object update information.
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000176 void ProcessMI(MachineInstr *MI,
177 BitVector &PhysRegDefs,
178 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000179 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000180 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000181
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000182 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
183 /// current loop.
184 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000185
Evan Cheng0a2aff22010-04-13 18:16:00 +0000186 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner0b7ae202010-07-12 00:00:35 +0000187 /// candidate for LICM. e.g. If the instruction is a call, then it's
188 /// obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000189 bool IsLICMCandidate(MachineInstr &I);
190
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000191 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000192 /// invariant. I.e., all virtual register operands are defined outside of
193 /// the loop, physical registers aren't accessed (explicitly or implicitly),
194 /// and the instruction is hoistable.
Andrew Trick5209c732012-02-08 21:23:00 +0000195 ///
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000196 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000197
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000198 /// HasLoopPHIUse - Return true if the specified instruction is used by any
199 /// phi node in the current loop.
200 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000201
Evan Cheng63c76082010-10-19 18:58:51 +0000202 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
203 /// and an use in the current loop, return true if the target considered
204 /// it 'high'.
Evan Chenge96b8d72010-10-26 02:08:50 +0000205 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
206 unsigned Reg) const;
207
208 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000209
Evan Cheng87066f02010-10-20 22:03:58 +0000210 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
211 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng44436302010-10-16 02:20:26 +0000212 /// register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +0000213 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
214 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000215
216 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
217 /// the current block and update their register pressures to reflect the
218 /// effect of hoisting MI from the current block to the preheader.
219 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000220
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000221 /// IsProfitableToHoist - Return true if it is potentially profitable to
222 /// hoist the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000223 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000224
Devang Patel453d4012011-10-11 18:09:58 +0000225 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
226 /// If not then a load from this mbb may not be safe to hoist.
227 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
228
Pete Cooper1eed5b52011-12-22 02:05:40 +0000229 void EnterScope(MachineBasicBlock *MBB);
230
231 void ExitScope(MachineBasicBlock *MBB);
232
233 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
234 /// dominator tree node if its a leaf or all of its children are done. Walk
235 /// up the dominator tree to destroy ancestors which are now done.
236 void ExitScopeIfDone(MachineDomTreeNode *Node,
237 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
238 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
239
240 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
241 /// blocks dominated by the specified header block, and that are in the
242 /// current loop) in depth first order w.r.t the DominatorTree. This allows
243 /// us to visit definitions before uses, allowing us to hoist a loop body in
244 /// one pass without iteration.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000245 ///
Pete Cooper1eed5b52011-12-22 02:05:40 +0000246 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
247 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000248
Daniel Jasper15e69542015-03-14 10:58:38 +0000249 /// SinkIntoLoop - Sink instructions into loops if profitable. This
250 /// especially tries to prevent register spills caused by register pressure
251 /// if there is little to no overhead moving instructions into loops.
252 void SinkIntoLoop();
253
Evan Cheng44436302010-10-16 02:20:26 +0000254 /// InitRegPressure - Find all virtual register references that are liveout
255 /// of the preheader to initialize the starting "register pressure". Note
256 /// this does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000257 void InitRegPressure(MachineBasicBlock *BB);
258
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000259 /// calcRegisterCost - Calculate the additional register pressure that the
260 /// registers used in MI cause.
261 ///
262 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
263 /// figure out which usages are live-ins.
264 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
265 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
266 bool ConsiderSeen,
267 bool ConsiderUnseenAsDef);
268
Evan Cheng87066f02010-10-20 22:03:58 +0000269 /// UpdateRegPressure - Update estimate of register pressure after the
270 /// specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000271 void UpdateRegPressure(const MachineInstr *MI,
272 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000273
Dan Gohman104f57c2009-10-29 17:47:20 +0000274 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
275 /// the load itself could be hoisted. Return the unfolded and hoistable
276 /// load, or null if the load couldn't be unfolded or if it wouldn't
277 /// be hoistable.
278 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
279
Evan Cheng7ff83192009-11-07 03:52:02 +0000280 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
281 /// duplicate of MI. Return this instruction if it's found.
282 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
283 std::vector<const MachineInstr*> &PrevMIs);
284
Evan Cheng921152f2009-11-05 00:51:13 +0000285 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
286 /// the preheader that compute the same value. If it's found, do a RAU on
287 /// with the definition of the existing instruction rather than hoisting
288 /// the instruction to the preheader.
289 bool EliminateCSE(MachineInstr *MI,
290 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
291
Evan Chengaf138952011-10-12 00:09:14 +0000292 /// MayCSE - Return true if the given instruction will be CSE'd if it's
293 /// hoisted out of the loop.
294 bool MayCSE(MachineInstr *MI);
295
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000296 /// Hoist - When an instruction is found to only use loop invariant operands
297 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng87066f02010-10-20 22:03:58 +0000298 /// It returns true if the instruction is hoisted.
299 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000300
301 /// InitCSEMap - Initialize the CSE map with instructions that are in the
302 /// current loop preheader that may become duplicates of instructions that
303 /// are hoisted out of the loop.
304 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000305
306 /// getCurPreheader - Get the preheader for the current loop, splitting
307 /// a critical edge if needed.
308 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000309 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000310} // end anonymous namespace
311
Dan Gohmand78c4002008-05-13 00:00:25 +0000312char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000313char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000314INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
315 "Machine Loop Invariant Code Motion", false, false)
316INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
317INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
318INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
319INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000320 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000321
Dan Gohman3570f812010-06-22 17:25:57 +0000322/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
323/// loop that has a unique predecessor.
324static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000325 // Check whether this loop even has a unique predecessor.
326 if (!CurLoop->getLoopPredecessor())
327 return false;
328 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000329 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000330 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000331 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000332 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000333 return true;
334}
335
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000336bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000337 if (skipOptnoneFunction(*MF.getFunction()))
338 return false;
339
Evan Cheng032f3262010-05-29 00:06:36 +0000340 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000341 const TargetSubtargetInfo &ST = MF.getSubtarget();
342 TII = ST.getInstrInfo();
343 TLI = ST.getTargetLowering();
344 TRI = ST.getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000345 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000346 MRI = &MF.getRegInfo();
Matthias Braun88e21312015-06-13 03:42:11 +0000347 SchedModel.init(ST.getSchedModel(), &ST, TII);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000348
Andrew Trickc40815d2012-02-08 21:23:03 +0000349 PreRegAlloc = MRI->isSSA();
350
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000351 if (PreRegAlloc)
352 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
353 else
354 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000355 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000356
Evan Chengd62719c2010-10-14 01:16:09 +0000357 if (PreRegAlloc) {
358 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000359 unsigned NumRPS = TRI->getNumRegPressureSets();
360 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000361 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000362 RegLimit.resize(NumRPS);
363 for (unsigned i = 0, e = NumRPS; i != e; ++i)
364 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000365 }
366
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000367 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000368 MLI = &getAnalysis<MachineLoopInfo>();
369 DT = &getAnalysis<MachineDominatorTree>();
370 AA = &getAnalysis<AliasAnalysis>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000371
Dan Gohman7929c442010-07-09 18:49:45 +0000372 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
373 while (!Worklist.empty()) {
374 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000375 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000376 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000377
Evan Cheng058b9f02010-04-08 01:03:47 +0000378 // If this is done before regalloc, only visit outer-most preheader-sporting
379 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000380 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
381 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000382 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000383 }
Dan Gohman79618d12009-01-15 22:01:38 +0000384
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000385 CurLoop->getExitBlocks(ExitBlocks);
386
Evan Cheng6ea59492010-04-07 00:41:17 +0000387 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000388 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000389 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000390 // CSEMap is initialized for loop header when the first instruction is
391 // being hoisted.
392 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000393 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000394 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000395 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000396
397 if (SinkInstsToAvoidSpills)
398 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000399 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000400 }
401
402 return Changed;
403}
404
Evan Cheng058b9f02010-04-08 01:03:47 +0000405/// InstructionStoresToFI - Return true if instruction stores to the
406/// specified frame.
407static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
408 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
409 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000410 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000411 continue;
412 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000413 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000414 if (Value->getFrameIndex() == FI)
415 return true;
416 }
417 }
418 return false;
419}
420
421/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
422/// gather register def and frame object update information.
423void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000424 BitVector &PhysRegDefs,
425 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000426 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000427 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000428 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000429 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000430 unsigned Def = 0;
431 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
432 const MachineOperand &MO = MI->getOperand(i);
433 if (MO.isFI()) {
434 // Remember if the instruction stores to the frame index.
435 int FI = MO.getIndex();
436 if (!StoredFIs.count(FI) &&
437 MFI->isSpillSlotObjectIndex(FI) &&
438 InstructionStoresToFI(MI, FI))
439 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000440 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000441 continue;
442 }
443
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000444 // We can't hoist an instruction defining a physreg that is clobbered in
445 // the loop.
446 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000447 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000448 continue;
449 }
450
Evan Cheng058b9f02010-04-08 01:03:47 +0000451 if (!MO.isReg())
452 continue;
453 unsigned Reg = MO.getReg();
454 if (!Reg)
455 continue;
456 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
457 "Not expecting virtual register!");
458
Evan Cheng0a2aff22010-04-13 18:16:00 +0000459 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000460 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000461 // If it's using a non-loop-invariant register, then it's obviously not
462 // safe to hoist.
463 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000464 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000465 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000466
467 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000468 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
469 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000470 if (!MO.isDead())
471 // Non-dead implicit def? This cannot be hoisted.
472 RuledOut = true;
473 // No need to check if a dead implicit def is also defined by
474 // another instruction.
475 continue;
476 }
477
478 // FIXME: For now, avoid instructions with multiple defs, unless
479 // it's a dead implicit def.
480 if (Def)
481 RuledOut = true;
482 else
483 Def = Reg;
484
485 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000486 // register, then this is not safe. Two defs is indicated by setting a
487 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000488 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000489 if (PhysRegDefs.test(*AS))
490 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000491 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000492 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000493 if (PhysRegClobbers.test(Reg))
494 // MI defined register is seen defined by another instruction in
495 // the loop, it cannot be a LICM candidate.
496 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000497 }
498
Evan Cheng0a2aff22010-04-13 18:16:00 +0000499 // Only consider reloads for now and remats which do not have register
500 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000501 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000502 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000503 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000504 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
505 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000506 }
507}
508
509/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
510/// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000511void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000512 MachineBasicBlock *Preheader = getCurPreheader();
513 if (!Preheader)
514 return;
515
Evan Cheng6ea59492010-04-07 00:41:17 +0000516 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000517 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
518 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000519
Evan Cheng058b9f02010-04-08 01:03:47 +0000520 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000521 SmallSet<int, 32> StoredFIs;
522
523 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000524 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000525 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000526 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
527 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000528
529 // If the header of the loop containing this basic block is a landing pad,
530 // then don't try to hoist instructions out of this loop.
531 const MachineLoop *ML = MLI->getLoopFor(BB);
532 if (ML && ML->getHeader()->isLandingPad()) continue;
533
Evan Cheng6ea59492010-04-07 00:41:17 +0000534 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000535 // FIXME: That means a reload that're reused in successor block(s) will not
536 // be LICM'ed.
Dan Gohman9d2d0532010-04-13 16:57:55 +0000537 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Cheng6ea59492010-04-07 00:41:17 +0000538 E = BB->livein_end(); I != E; ++I) {
539 unsigned Reg = *I;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000540 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
541 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000542 }
543
Evan Chengf192ca02011-10-11 23:48:44 +0000544 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000545 for (MachineBasicBlock::iterator
546 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000547 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000548 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000549 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000550 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000551
Evan Cheng7fede872012-03-27 01:50:58 +0000552 // Gather the registers read / clobbered by the terminator.
553 BitVector TermRegs(NumRegs);
554 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
555 if (TI != Preheader->end()) {
556 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
557 const MachineOperand &MO = TI->getOperand(i);
558 if (!MO.isReg())
559 continue;
560 unsigned Reg = MO.getReg();
561 if (!Reg)
562 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000563 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
564 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000565 }
566 }
567
Evan Cheng6ea59492010-04-07 00:41:17 +0000568 // Now evaluate whether the potential candidates qualify.
569 // 1. Check if the candidate defined register is defined by another
570 // instruction in the loop.
571 // 2. If the candidate is a load from stack slot (always true for now),
572 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000573 // 3. Make sure candidate def should not clobber
574 // registers read by the terminator. Similarly its def should not be
575 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000576 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000577 if (Candidates[i].FI != INT_MIN &&
578 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000579 continue;
580
Evan Cheng7fede872012-03-27 01:50:58 +0000581 unsigned Def = Candidates[i].Def;
582 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000583 bool Safe = true;
584 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000585 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
586 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000587 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000588 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000589 unsigned Reg = MO.getReg();
590 if (PhysRegDefs.test(Reg) ||
591 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000592 // If it's using a non-loop-invariant register, then it's obviously
593 // not safe to hoist.
594 Safe = false;
595 break;
596 }
597 }
598 if (Safe)
599 HoistPostRA(MI, Candidates[i].Def);
600 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000601 }
602}
603
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000604/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
605/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000606void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000607 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000608 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
609 MachineBasicBlock *BB = Blocks[i];
610 if (!BB->isLiveIn(Reg))
611 BB->addLiveIn(Reg);
612 for (MachineBasicBlock::iterator
613 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
614 MachineInstr *MI = &*MII;
615 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
616 MachineOperand &MO = MI->getOperand(i);
617 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
618 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
619 MO.setIsKill(false);
620 }
621 }
622 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000623}
624
625/// HoistPostRA - When an instruction is found to only use loop invariant
626/// operands that is safe to hoist, this instruction is called to do the
627/// dirty work.
628void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000629 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000630
Evan Cheng6ea59492010-04-07 00:41:17 +0000631 // Now move the instructions to the predecessor, inserting it before any
632 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000633 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
634 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000635
636 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000637 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000638 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000639
Andrew Trick5209c732012-02-08 21:23:00 +0000640 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000641 // loop invariant must be kept live throughout the whole loop. This is
642 // important to ensure later passes do not scavenge the def register.
643 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000644
645 ++NumPostRAHoisted;
646 Changed = true;
647}
648
Devang Patel453d4012011-10-11 18:09:58 +0000649// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
650// If not then a load from this mbb may not be safe to hoist.
651bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000652 if (SpeculationState != SpeculateUnknown)
653 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000654
Devang Patel453d4012011-10-11 18:09:58 +0000655 if (BB != CurLoop->getHeader()) {
656 // Check loop exiting blocks.
657 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
658 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
659 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
660 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000661 SpeculationState = SpeculateTrue;
662 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000663 }
664 }
665
Evan Chengf192ca02011-10-11 23:48:44 +0000666 SpeculationState = SpeculateFalse;
667 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000668}
669
Pete Cooper1eed5b52011-12-22 02:05:40 +0000670void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
671 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000672
Pete Cooper1eed5b52011-12-22 02:05:40 +0000673 // Remember livein register pressure.
674 BackTrace.push_back(RegPressure);
675}
Bill Wendling918cea22011-10-12 02:58:01 +0000676
Pete Cooper1eed5b52011-12-22 02:05:40 +0000677void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
678 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
679 BackTrace.pop_back();
680}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000681
Pete Cooper1eed5b52011-12-22 02:05:40 +0000682/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
683/// dominator tree node if its a leaf or all of its children are done. Walk
684/// up the dominator tree to destroy ancestors which are now done.
685void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000686 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
687 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000688 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000689 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000690
Pete Cooper1eed5b52011-12-22 02:05:40 +0000691 // Pop scope.
692 ExitScope(Node->getBlock());
693
694 // Now traverse upwards to pop ancestors whose offsprings are all done.
695 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
696 unsigned Left = --OpenChildren[Parent];
697 if (Left != 0)
698 break;
699 ExitScope(Parent->getBlock());
700 Node = Parent;
701 }
702}
703
704/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
705/// blocks dominated by the specified header block, and that are in the
706/// current loop) in depth first order w.r.t the DominatorTree. This allows
707/// us to visit definitions before uses, allowing us to hoist a loop body in
708/// one pass without iteration.
709///
710void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000711 MachineBasicBlock *Preheader = getCurPreheader();
712 if (!Preheader)
713 return;
714
Pete Cooper1eed5b52011-12-22 02:05:40 +0000715 SmallVector<MachineDomTreeNode*, 32> Scopes;
716 SmallVector<MachineDomTreeNode*, 8> WorkList;
717 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
718 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
719
720 // Perform a DFS walk to determine the order of visit.
721 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000722 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000723 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000724 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000725 MachineBasicBlock *BB = Node->getBlock();
726
727 // If the header of the loop containing this basic block is a landing pad,
728 // then don't try to hoist instructions out of this loop.
729 const MachineLoop *ML = MLI->getLoopFor(BB);
730 if (ML && ML->getHeader()->isLandingPad())
731 continue;
732
733 // If this subregion is not in the top level loop at all, exit.
734 if (!CurLoop->contains(BB))
735 continue;
736
737 Scopes.push_back(Node);
738 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
739 unsigned NumChildren = Children.size();
740
741 // Don't hoist things out of a large switch statement. This often causes
742 // code to be hoisted that wasn't going to be executed, and increases
743 // register pressure in a situation where it's likely to matter.
744 if (BB->succ_size() >= 25)
745 NumChildren = 0;
746
747 OpenChildren[Node] = NumChildren;
748 // Add children in reverse order as then the next popped worklist node is
749 // the first child of this node. This means we ultimately traverse the
750 // DOM tree in exactly the same order as if we'd recursed.
751 for (int i = (int)NumChildren-1; i >= 0; --i) {
752 MachineDomTreeNode *Child = Children[i];
753 ParentMap[Child] = Node;
754 WorkList.push_back(Child);
755 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000756 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000757
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000758 if (Scopes.size() == 0)
759 return;
760
761 // Compute registers which are livein into the loop headers.
762 RegSeen.clear();
763 BackTrace.clear();
764 InitRegPressure(Preheader);
765
Pete Cooper1eed5b52011-12-22 02:05:40 +0000766 // Now perform LICM.
767 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
768 MachineDomTreeNode *Node = Scopes[i];
769 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000770
Pete Cooper1eed5b52011-12-22 02:05:40 +0000771 EnterScope(MBB);
772
773 // Process the block
774 SpeculationState = SpeculateUnknown;
775 for (MachineBasicBlock::iterator
776 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
777 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
778 MachineInstr *MI = &*MII;
779 if (!Hoist(MI, Preheader))
780 UpdateRegPressure(MI);
781 MII = NextMII;
782 }
783
784 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
785 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000786 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000787}
788
Daniel Jasper15e69542015-03-14 10:58:38 +0000789void MachineLICM::SinkIntoLoop() {
790 MachineBasicBlock *Preheader = getCurPreheader();
791 if (!Preheader)
792 return;
793
794 SmallVector<MachineInstr *, 8> Candidates;
795 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
796 I != Preheader->instr_end(); ++I) {
797 // We need to ensure that we can safely move this instruction into the loop.
798 // As such, it must not have side-effects, e.g. such as a call has.
799 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
800 Candidates.push_back(I);
801 }
802
803 for (MachineInstr *I : Candidates) {
804 const MachineOperand &MO = I->getOperand(0);
805 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
806 continue;
807 if (!MRI->hasOneDef(MO.getReg()))
808 continue;
809 bool CanSink = true;
810 MachineBasicBlock *B = nullptr;
811 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
812 // FIXME: Come up with a proper cost model that estimates whether sinking
813 // the instruction (and thus possibly executing it on every loop
814 // iteration) is more expensive than a register.
815 // For now assumes that copies are cheap and thus almost always worth it.
816 if (!MI.isCopy()) {
817 CanSink = false;
818 break;
819 }
820 if (!B) {
821 B = MI.getParent();
822 continue;
823 }
824 B = DT->findNearestCommonDominator(B, MI.getParent());
825 if (!B) {
826 CanSink = false;
827 break;
828 }
829 }
830 if (!CanSink || !B || B == Preheader)
831 continue;
832 B->splice(B->getFirstNonPHI(), Preheader, I);
833 }
834}
835
Evan Cheng87066f02010-10-20 22:03:58 +0000836static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
837 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
838}
839
Evan Cheng44436302010-10-16 02:20:26 +0000840/// InitRegPressure - Find all virtual register references that are liveout of
841/// the preheader to initialize the starting "register pressure". Note this
842/// does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000843void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000844 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000845
Evan Cheng87066f02010-10-20 22:03:58 +0000846 // If the preheader has only a single predecessor and it ends with a
847 // fallthrough or an unconditional branch, then scan its predecessor for live
848 // defs as well. This happens whenever the preheader is created by splitting
849 // the critical edge from the loop predecessor to the loop header.
850 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000851 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000852 SmallVector<MachineOperand, 4> Cond;
853 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
854 InitRegPressure(*BB->pred_begin());
855 }
856
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000857 for (const MachineInstr &MI : *BB)
858 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000859}
860
Evan Cheng87066f02010-10-20 22:03:58 +0000861/// UpdateRegPressure - Update estimate of register pressure after the
862/// specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000863void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
864 bool ConsiderUnseenAsDef) {
865 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000866 for (const auto &RPIdAndCost : Cost) {
867 unsigned Class = RPIdAndCost.first;
868 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000869 RegPressure[Class] = 0;
870 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000871 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000872 }
873}
Evan Chengd62719c2010-10-14 01:16:09 +0000874
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000875DenseMap<unsigned, int>
876MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
877 bool ConsiderUnseenAsDef) {
878 DenseMap<unsigned, int> Cost;
879 if (MI->isImplicitDef())
880 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000881 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
882 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000883 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000884 continue;
885 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000886 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000887 continue;
888
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000889 // FIXME: It seems bad to use RegSeen only for some of these calculations.
890 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000891 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
892
893 RegClassWeight W = TRI->getRegClassWeight(RC);
894 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000895 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000896 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000897 else {
898 bool isKill = isOperandKill(MO, MRI);
899 if (isNew && !isKill && ConsiderUnseenAsDef)
900 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000901 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000902 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000903 RCCost = -W.RegWeight;
904 }
905 if (RCCost == 0)
906 continue;
907 const int *PS = TRI->getRegClassPressureSets(RC);
908 for (; *PS != -1; ++PS) {
909 if (Cost.find(*PS) == Cost.end())
910 Cost[*PS] = RCCost;
911 else
912 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000913 }
Evan Chengd62719c2010-10-14 01:16:09 +0000914 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000915 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000916}
917
Andrew Trick5209c732012-02-08 21:23:00 +0000918/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel1d8ab462011-10-20 17:42:23 +0000919/// loads from global offset table or constant pool.
920static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000921 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000922 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000923 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000924 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
925 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
926 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000927 }
928 }
929 return false;
930}
931
Evan Cheng0a2aff22010-04-13 18:16:00 +0000932/// IsLICMCandidate - Returns true if the instruction may be a suitable
933/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
934/// not safe to hoist it.
935bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000936 // Check if it's safe to move the instruction.
937 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000938 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000939 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000940
941 // If it is load then check if it is guaranteed to execute by making sure that
942 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000943 // the loop which does not execute this load, so we can't hoist it. Loads
944 // from constant memory are not safe to speculate all the time, for example
945 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000946 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000947 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000948 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000949 return false;
950
Evan Cheng0a2aff22010-04-13 18:16:00 +0000951 return true;
952}
953
954/// IsLoopInvariantInst - Returns true if the instruction is loop
955/// invariant. I.e., all virtual register operands are defined outside of the
956/// loop, physical registers aren't accessed explicitly, and there are no side
957/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000958///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000959bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
960 if (!IsLICMCandidate(I))
961 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000962
Bill Wendling70613b82008-05-12 19:38:32 +0000963 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000964 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
965 const MachineOperand &MO = I.getOperand(i);
966
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000967 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000968 continue;
969
Dan Gohman79618d12009-01-15 22:01:38 +0000970 unsigned Reg = MO.getReg();
971 if (Reg == 0) continue;
972
973 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000974 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000975 if (MO.isUse()) {
976 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000977 // and we can freely move its uses. Alternatively, if it's allocatable,
978 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000979 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000980 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000981 // Otherwise it's safe to move.
982 continue;
983 } else if (!MO.isDead()) {
984 // A def that isn't dead. We can't move it.
985 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000986 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
987 // If the reg is live into the loop, we can't hoist an instruction
988 // which would clobber it.
989 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000990 }
991 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000992
993 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000994 continue;
995
Evan Chengd62719c2010-10-14 01:16:09 +0000996 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000997 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000998
999 // If the loop contains the definition of an operand, then the instruction
1000 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001001 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001002 return false;
1003 }
1004
1005 // If we got this far, the instruction is loop invariant!
1006 return true;
1007}
1008
Evan Cheng399660c2009-02-05 08:45:46 +00001009
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001010/// HasLoopPHIUse - Return true if the specified instruction is used by a
1011/// phi node and hoisting it could cause a copy to be inserted.
1012bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1013 SmallVector<const MachineInstr*, 8> Work(1, MI);
1014 do {
1015 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +00001016 for (const MachineOperand &MO : MI->operands()) {
1017 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001018 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00001019 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001020 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1021 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001022 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001023 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001024 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001025 // A PHI inside the loop causes a copy because the live range of Reg is
1026 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001027 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001028 return true;
1029 // A PHI in an exit block can cause a copy to be inserted if the PHI
1030 // has multiple predecessors in the loop with different values.
1031 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001032 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001033 return true;
1034 continue;
1035 }
1036 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001037 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1038 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001039 }
Evan Chengef42bea2011-04-11 21:09:18 +00001040 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001041 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001042 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001043}
1044
Evan Cheng63c76082010-10-19 18:58:51 +00001045/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1046/// and an use in the current loop, return true if the target considered
1047/// it 'high'.
1048bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +00001049 unsigned DefIdx, unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +00001050 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001051 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001052
Owen Andersonb36376e2014-03-17 19:36:09 +00001053 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1054 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001055 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001056 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001057 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001058 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1059 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001060 if (!MO.isReg() || !MO.isUse())
1061 continue;
1062 unsigned MOReg = MO.getReg();
1063 if (MOReg != Reg)
1064 continue;
1065
Matthias Braun88e21312015-06-13 03:42:11 +00001066 if (TII->hasHighOperandLatency(SchedModel, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001067 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001068 }
1069
Evan Cheng63c76082010-10-19 18:58:51 +00001070 // Only look at the first in loop use.
1071 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001072 }
1073
Evan Cheng63c76082010-10-19 18:58:51 +00001074 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001075}
1076
Evan Chenge96b8d72010-10-26 02:08:50 +00001077/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1078/// the operand latency between its def and a use is one or less.
1079bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001080 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001081 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001082
1083 bool isCheap = false;
1084 unsigned NumDefs = MI.getDesc().getNumDefs();
1085 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1086 MachineOperand &DefMO = MI.getOperand(i);
1087 if (!DefMO.isReg() || !DefMO.isDef())
1088 continue;
1089 --NumDefs;
1090 unsigned Reg = DefMO.getReg();
1091 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1092 continue;
1093
Matthias Braun88e21312015-06-13 03:42:11 +00001094 if (!TII->hasLowDefLatency(SchedModel, &MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001095 return false;
1096 isCheap = true;
1097 }
1098
1099 return isCheap;
1100}
1101
Evan Cheng87066f02010-10-20 22:03:58 +00001102/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng44436302010-10-16 02:20:26 +00001103/// if hoisting an instruction of the given cost matrix can cause high
1104/// register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +00001105bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001106 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001107 for (const auto &RPIdAndCost : Cost) {
1108 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001109 continue;
1110
Daniel Jasper274928f2015-04-14 11:56:25 +00001111 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001112 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001113
1114 // Don't hoist cheap instructions if they would increase register pressure,
1115 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001116 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001117 return true;
1118
Daniel Jasperefece522015-04-03 16:19:48 +00001119 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001120 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001121 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001122 }
1123
1124 return false;
1125}
1126
Evan Cheng87066f02010-10-20 22:03:58 +00001127/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1128/// current block and update their register pressures to reflect the effect
1129/// of hoisting MI from the current block to the preheader.
1130void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001131 // First compute the 'cost' of the instruction, i.e. its contribution
1132 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001133 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1134 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001135
1136 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001137 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001138 for (const auto &RPIdAndCost : Cost)
1139 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001140}
1141
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001142/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1143/// the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001144bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001145 if (MI.isImplicitDef())
1146 return true;
1147
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001148 // Besides removing computation from the loop, hoisting an instruction has
1149 // these effects:
1150 //
1151 // - The value defined by the instruction becomes live across the entire
1152 // loop. This increases register pressure in the loop.
1153 //
1154 // - If the value is used by a PHI in the loop, a copy will be required for
1155 // lowering the PHI after extending the live range.
1156 //
1157 // - When hoisting the last use of a value in the loop, that value no longer
1158 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001159
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001160 bool CheapInstr = IsCheapInstruction(MI);
1161 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001162
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001163 // Don't hoist a cheap instruction if it would create a copy in the loop.
1164 if (CheapInstr && CreatesCopy) {
1165 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1166 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001167 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001168
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001169 // Rematerializable instructions should always be hoisted since the register
1170 // allocator can just pull them down again when needed.
1171 if (TII->isTriviallyReMaterializable(&MI, AA))
1172 return true;
1173
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001174 // FIXME: If there are long latency loop-invariant instructions inside the
1175 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001176 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1177 const MachineOperand &MO = MI.getOperand(i);
1178 if (!MO.isReg() || MO.isImplicit())
1179 continue;
1180 unsigned Reg = MO.getReg();
1181 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1182 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001183 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1184 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1185 ++NumHighLatency;
1186 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001187 }
1188 }
1189
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001190 // Estimate register pressure to determine whether to LICM the instruction.
1191 // In low register pressure situation, we can be more aggressive about
1192 // hoisting. Also, favors hoisting long latency instructions even in
1193 // moderately high pressure situation.
1194 // Cheap instructions will only be hoisted if they don't increase register
1195 // pressure at all.
1196 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1197 /*ConsiderUnseenAsDef=*/false);
1198
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001199 // Visit BBs from header to current BB, if hoisting this doesn't cause
1200 // high register pressure, then it's safe to proceed.
1201 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1202 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1203 ++NumLowRP;
1204 return true;
1205 }
1206
1207 // Don't risk increasing register pressure if it would create copies.
1208 if (CreatesCopy) {
1209 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001210 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001211 }
1212
1213 // Do not "speculate" in high register pressure situation. If an
1214 // instruction is not guaranteed to be executed in the loop, it's best to be
1215 // conservative.
1216 if (AvoidSpeculation &&
1217 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1218 DEBUG(dbgs() << "Won't speculate: " << MI);
1219 return false;
1220 }
1221
1222 // High register pressure situation, only hoist if the instruction is going
1223 // to be remat'ed.
1224 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1225 !MI.isInvariantLoad(AA)) {
1226 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1227 return false;
1228 }
Evan Cheng399660c2009-02-05 08:45:46 +00001229
1230 return true;
1231}
1232
Dan Gohman104f57c2009-10-29 17:47:20 +00001233MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001234 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001235 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001236 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001237
Dan Gohman104f57c2009-10-29 17:47:20 +00001238 // If not, we may be able to unfold a load and hoist that.
1239 // First test whether the instruction is loading from an amenable
1240 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001241 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001242 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001243
Dan Gohman104f57c2009-10-29 17:47:20 +00001244 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001245 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001246 unsigned NewOpc =
1247 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1248 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001249 /*UnfoldStore=*/false,
1250 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001251 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001252 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001253 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001254 MachineFunction &MF = *MI->getParent()->getParent();
1255 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001256 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001257 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001258
Dan Gohman104f57c2009-10-29 17:47:20 +00001259 SmallVector<MachineInstr *, 2> NewMIs;
1260 bool Success =
1261 TII->unfoldMemoryOperand(MF, MI, Reg,
1262 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1263 NewMIs);
1264 (void)Success;
1265 assert(Success &&
1266 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1267 "succeeded!");
1268 assert(NewMIs.size() == 2 &&
1269 "Unfolded a load into multiple instructions!");
1270 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001271 MachineBasicBlock::iterator Pos = MI;
1272 MBB->insert(Pos, NewMIs[0]);
1273 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001274 // If unfolding produced a load that wasn't loop-invariant or profitable to
1275 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001276 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001277 NewMIs[0]->eraseFromParent();
1278 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001279 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001280 }
Evan Cheng87066f02010-10-20 22:03:58 +00001281
1282 // Update register pressure for the unfolded instruction.
1283 UpdateRegPressure(NewMIs[1]);
1284
Dan Gohman104f57c2009-10-29 17:47:20 +00001285 // Otherwise we successfully unfolded a load that we can hoist.
1286 MI->eraseFromParent();
1287 return NewMIs[0];
1288}
1289
Evan Chengf42b5af2009-11-03 21:40:02 +00001290void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1291 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1292 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001293 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001294 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001295 }
1296}
1297
Evan Cheng7ff83192009-11-07 03:52:02 +00001298const MachineInstr*
1299MachineLICM::LookForDuplicate(const MachineInstr *MI,
1300 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001301 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1302 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001303 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001304 return PrevMI;
1305 }
Craig Topperc0196b12014-04-14 00:51:57 +00001306 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001307}
1308
1309bool MachineLICM::EliminateCSE(MachineInstr *MI,
1310 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001311 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1312 // the undef property onto uses.
1313 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001314 return false;
1315
1316 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001317 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001318
1319 // Replace virtual registers defined by MI by their counterparts defined
1320 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001321 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001322 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1323 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001324
1325 // Physical registers may not differ here.
1326 assert((!MO.isReg() || MO.getReg() == 0 ||
1327 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1328 MO.getReg() == Dup->getOperand(i).getReg()) &&
1329 "Instructions with different phys regs are not identical!");
1330
1331 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001332 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1333 Defs.push_back(i);
1334 }
1335
1336 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1337 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1338 unsigned Idx = Defs[i];
1339 unsigned Reg = MI->getOperand(Idx).getReg();
1340 unsigned DupReg = Dup->getOperand(Idx).getReg();
1341 OrigRCs.push_back(MRI->getRegClass(DupReg));
1342
1343 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1344 // Restore old RCs if more than one defs.
1345 for (unsigned j = 0; j != i; ++j)
1346 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1347 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001348 }
Evan Cheng921152f2009-11-05 00:51:13 +00001349 }
Evan Chengaa563df2011-10-17 19:50:12 +00001350
1351 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1352 unsigned Idx = Defs[i];
1353 unsigned Reg = MI->getOperand(Idx).getReg();
1354 unsigned DupReg = Dup->getOperand(Idx).getReg();
1355 MRI->replaceRegWith(Reg, DupReg);
1356 MRI->clearKillFlags(DupReg);
1357 }
1358
Evan Cheng7ff83192009-11-07 03:52:02 +00001359 MI->eraseFromParent();
1360 ++NumCSEed;
1361 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001362 }
1363 return false;
1364}
1365
Evan Chengaf138952011-10-12 00:09:14 +00001366/// MayCSE - Return true if the given instruction will be CSE'd if it's
1367/// hoisted out of the loop.
1368bool MachineLICM::MayCSE(MachineInstr *MI) {
1369 unsigned Opcode = MI->getOpcode();
1370 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1371 CI = CSEMap.find(Opcode);
1372 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1373 // the undef property onto uses.
1374 if (CI == CSEMap.end() || MI->isImplicitDef())
1375 return false;
1376
Craig Topperc0196b12014-04-14 00:51:57 +00001377 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001378}
1379
Bill Wendling70613b82008-05-12 19:38:32 +00001380/// Hoist - When an instruction is found to use only loop invariant operands
1381/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001382///
Evan Cheng87066f02010-10-20 22:03:58 +00001383bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001384 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001385 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001386 // If not, try unfolding a hoistable load.
1387 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001388 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001389 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001390
Dan Gohman79618d12009-01-15 22:01:38 +00001391 // Now move the instructions to the predecessor, inserting it before any
1392 // terminator instructions.
1393 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001394 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001395 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001396 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001397 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001398 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001399 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001400 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001401 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001402 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001403
Evan Chengf42b5af2009-11-03 21:40:02 +00001404 // If this is the first instruction being hoisted to the preheader,
1405 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001406 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001407 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001408 FirstInLoop = false;
1409 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001410
Evan Cheng399660c2009-02-05 08:45:46 +00001411 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001412 unsigned Opcode = MI->getOpcode();
1413 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1414 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001415 if (!EliminateCSE(MI, CI)) {
1416 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001417 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001418
Evan Cheng87066f02010-10-20 22:03:58 +00001419 // Update register pressure for BBs from header to this block.
1420 UpdateBackTraceRegPressure(MI);
1421
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001422 // Clear the kill flags of any register this instruction defines,
1423 // since they may need to be live throughout the entire loop
1424 // rather than just live for part of it.
1425 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1426 MachineOperand &MO = MI->getOperand(i);
1427 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001428 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001429 }
1430
Evan Cheng399660c2009-02-05 08:45:46 +00001431 // Add to the CSE map.
1432 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001433 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001434 else
1435 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001436 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001437
Dan Gohman79618d12009-01-15 22:01:38 +00001438 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001439 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001440
1441 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001442}
Dan Gohman3570f812010-06-22 17:25:57 +00001443
1444MachineBasicBlock *MachineLICM::getCurPreheader() {
1445 // Determine the block to which to hoist instructions. If we can't find a
1446 // suitable loop predecessor, we can't do any hoisting.
1447
1448 // If we've tried to get a preheader and failed, don't try again.
1449 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001450 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001451
1452 if (!CurPreheader) {
1453 CurPreheader = CurLoop->getLoopPreheader();
1454 if (!CurPreheader) {
1455 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1456 if (!Pred) {
1457 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001458 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001459 }
1460
1461 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1462 if (!CurPreheader) {
1463 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001464 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001465 }
1466 }
1467 }
1468 return CurPreheader;
1469}