blob: 2f65a2ec25fdd1ac02d32db06a5a96bb25df7a95 [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 does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000023#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/AliasAnalysis.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000028#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000031#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000033#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Cheng8264e272011-06-29 01:14:12 +000034#include "llvm/MC/MCInstrItineraries.h"
Evan Chengb35afca2011-10-12 21:33:49 +000035#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000036#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000037#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetMachine.h"
41#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000042#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000043using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "machine-licm"
46
Evan Chengb35afca2011-10-12 21:33:49 +000047static cl::opt<bool>
48AvoidSpeculation("avoid-speculation",
49 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000050 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000051
Hal Finkel0709f512015-01-08 22:10:48 +000052static cl::opt<bool>
53HoistCheapInsts("hoist-cheap-insts",
54 cl::desc("MachineLICM should hoist even cheap instructions"),
55 cl::init(false), cl::Hidden);
56
Daniel Jasper15e69542015-03-14 10:58:38 +000057static cl::opt<bool>
58SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
59 cl::desc("MachineLICM should sink instructions into "
60 "loops to avoid register spills"),
61 cl::init(false), cl::Hidden);
62
Evan Cheng44436302010-10-16 02:20:26 +000063STATISTIC(NumHoisted,
64 "Number of machine instructions hoisted out of loops");
65STATISTIC(NumLowRP,
66 "Number of instructions hoisted in low reg pressure situation");
67STATISTIC(NumHighLatency,
68 "Number of high latency instructions hoisted");
69STATISTIC(NumCSEed,
70 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000071STATISTIC(NumPostRAHoisted,
72 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000073
Bill Wendlingfb706bc2007-12-07 21:42:31 +000074namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000075 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000076 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000077 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000078 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000079 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000080 MachineRegisterInfo *MRI;
81 const InstrItineraryData *InstrItins;
Andrew Trickc40815d2012-02-08 21:23:03 +000082 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000083
Bill Wendlingfb706bc2007-12-07 21:42:31 +000084 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000085 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000086 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000087 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000088
Bill Wendlingfb706bc2007-12-07 21:42:31 +000089 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000090 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000091 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000092 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000093 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000094
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000095 // Exit blocks for CurLoop.
96 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
97
98 bool isExitBlock(const MachineBasicBlock *MBB) const {
99 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
100 ExitBlocks.end();
101 }
102
Evan Chengd62719c2010-10-14 01:16:09 +0000103 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000104 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000105 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000106
107 // Register pressure "limit" per register class. If the pressure
108 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000109 SmallVector<unsigned, 8> RegLimit;
110
Evan Cheng44436302010-10-16 02:20:26 +0000111 // Register pressure on path leading from loop preheader to current BB.
112 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
113
Dale Johannesen329d4742010-07-29 17:45:24 +0000114 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000115 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000116
Evan Chengf192ca02011-10-11 23:48:44 +0000117 enum {
118 SpeculateFalse = 0,
119 SpeculateTrue = 1,
120 SpeculateUnknown = 2
121 };
122
Devang Patel453d4012011-10-11 18:09:58 +0000123 // If a MBB does not dominate loop exiting blocks then it may not safe
124 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000125 // Tri-state: 0 - false, 1 - true, 2 - unknown
126 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000127
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000128 public:
129 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000130 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000131 MachineFunctionPass(ID), PreRegAlloc(true) {
132 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
133 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000134
135 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000136 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
137 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
138 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000139
Craig Topper4584cd52014-03-07 09:26:03 +0000140 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000141
Craig Topper4584cd52014-03-07 09:26:03 +0000142 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000143 AU.addRequired<MachineLoopInfo>();
144 AU.addRequired<MachineDominatorTree>();
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000145 AU.addRequired<AliasAnalysis>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000146 AU.addPreserved<MachineLoopInfo>();
147 AU.addPreserved<MachineDominatorTree>();
148 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000149 }
Evan Cheng399660c2009-02-05 08:45:46 +0000150
Craig Topper4584cd52014-03-07 09:26:03 +0000151 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000152 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000153 RegPressure.clear();
154 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000155 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000156 CSEMap.clear();
157 }
158
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000159 private:
Evan Cheng058b9f02010-04-08 01:03:47 +0000160 /// CandidateInfo - Keep track of information about hoisting candidates.
161 struct CandidateInfo {
162 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000163 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000164 int FI;
165 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
166 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000167 };
168
169 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
170 /// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000171 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000172
173 /// HoistPostRA - When an instruction is found to only use loop invariant
174 /// operands that is safe to hoist, this instruction is called to do the
175 /// dirty work.
176 void HoistPostRA(MachineInstr *MI, unsigned Def);
177
178 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
179 /// gather register def and frame object update information.
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000180 void ProcessMI(MachineInstr *MI,
181 BitVector &PhysRegDefs,
182 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000183 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000184 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000185
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000186 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
187 /// current loop.
188 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000189
Evan Cheng0a2aff22010-04-13 18:16:00 +0000190 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner0b7ae202010-07-12 00:00:35 +0000191 /// candidate for LICM. e.g. If the instruction is a call, then it's
192 /// obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000193 bool IsLICMCandidate(MachineInstr &I);
194
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000195 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000196 /// invariant. I.e., all virtual register operands are defined outside of
197 /// the loop, physical registers aren't accessed (explicitly or implicitly),
198 /// and the instruction is hoistable.
Andrew Trick5209c732012-02-08 21:23:00 +0000199 ///
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000200 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000201
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000202 /// HasLoopPHIUse - Return true if the specified instruction is used by any
203 /// phi node in the current loop.
204 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000205
Evan Cheng63c76082010-10-19 18:58:51 +0000206 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
207 /// and an use in the current loop, return true if the target considered
208 /// it 'high'.
Evan Chenge96b8d72010-10-26 02:08:50 +0000209 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
210 unsigned Reg) const;
211
212 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000213
Evan Cheng87066f02010-10-20 22:03:58 +0000214 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
215 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng44436302010-10-16 02:20:26 +0000216 /// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +0000217 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000218
219 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
220 /// the current block and update their register pressures to reflect the
221 /// effect of hoisting MI from the current block to the preheader.
222 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000223
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000224 /// IsProfitableToHoist - Return true if it is potentially profitable to
225 /// hoist the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000226 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000227
Devang Patel453d4012011-10-11 18:09:58 +0000228 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
229 /// If not then a load from this mbb may not be safe to hoist.
230 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
231
Pete Cooper1eed5b52011-12-22 02:05:40 +0000232 void EnterScope(MachineBasicBlock *MBB);
233
234 void ExitScope(MachineBasicBlock *MBB);
235
236 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
237 /// dominator tree node if its a leaf or all of its children are done. Walk
238 /// up the dominator tree to destroy ancestors which are now done.
239 void ExitScopeIfDone(MachineDomTreeNode *Node,
240 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
241 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
242
243 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
244 /// blocks dominated by the specified header block, and that are in the
245 /// current loop) in depth first order w.r.t the DominatorTree. This allows
246 /// us to visit definitions before uses, allowing us to hoist a loop body in
247 /// one pass without iteration.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000248 ///
Pete Cooper1eed5b52011-12-22 02:05:40 +0000249 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
250 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000251
Daniel Jasper15e69542015-03-14 10:58:38 +0000252 /// SinkIntoLoop - Sink instructions into loops if profitable. This
253 /// especially tries to prevent register spills caused by register pressure
254 /// if there is little to no overhead moving instructions into loops.
255 void SinkIntoLoop();
256
Evan Cheng90da66b2011-09-01 01:45:00 +0000257 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
258 /// index, return the ID and cost of its representative register class by
259 /// reference.
260 void getRegisterClassIDAndCost(const MachineInstr *MI,
261 unsigned Reg, unsigned OpIdx,
262 unsigned &RCId, unsigned &RCCost) const;
263
Evan Cheng44436302010-10-16 02:20:26 +0000264 /// InitRegPressure - Find all virtual register references that are liveout
265 /// of the preheader to initialize the starting "register pressure". Note
266 /// this does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000267 void InitRegPressure(MachineBasicBlock *BB);
268
Evan Cheng87066f02010-10-20 22:03:58 +0000269 /// UpdateRegPressure - Update estimate of register pressure after the
270 /// specified instruction.
271 void UpdateRegPressure(const MachineInstr *MI);
Evan Chengd62719c2010-10-14 01:16:09 +0000272
Dan Gohman104f57c2009-10-29 17:47:20 +0000273 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
274 /// the load itself could be hoisted. Return the unfolded and hoistable
275 /// load, or null if the load couldn't be unfolded or if it wouldn't
276 /// be hoistable.
277 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
278
Evan Cheng7ff83192009-11-07 03:52:02 +0000279 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
280 /// duplicate of MI. Return this instruction if it's found.
281 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
282 std::vector<const MachineInstr*> &PrevMIs);
283
Evan Cheng921152f2009-11-05 00:51:13 +0000284 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
285 /// the preheader that compute the same value. If it's found, do a RAU on
286 /// with the definition of the existing instruction rather than hoisting
287 /// the instruction to the preheader.
288 bool EliminateCSE(MachineInstr *MI,
289 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
290
Evan Chengaf138952011-10-12 00:09:14 +0000291 /// MayCSE - Return true if the given instruction will be CSE'd if it's
292 /// hoisted out of the loop.
293 bool MayCSE(MachineInstr *MI);
294
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000295 /// Hoist - When an instruction is found to only use loop invariant operands
296 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng87066f02010-10-20 22:03:58 +0000297 /// It returns true if the instruction is hoisted.
298 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000299
300 /// InitCSEMap - Initialize the CSE map with instructions that are in the
301 /// current loop preheader that may become duplicates of instructions that
302 /// are hoisted out of the loop.
303 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000304
305 /// getCurPreheader - Get the preheader for the current loop, splitting
306 /// a critical edge if needed.
307 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000308 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000309} // end anonymous namespace
310
Dan Gohmand78c4002008-05-13 00:00:25 +0000311char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000312char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000313INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
314 "Machine Loop Invariant Code Motion", false, false)
315INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
316INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
317INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
318INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000319 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000320
Dan Gohman3570f812010-06-22 17:25:57 +0000321/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
322/// loop that has a unique predecessor.
323static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000324 // Check whether this loop even has a unique predecessor.
325 if (!CurLoop->getLoopPredecessor())
326 return false;
327 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000328 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000329 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000330 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000331 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000332 return true;
333}
334
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000335bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000336 if (skipOptnoneFunction(*MF.getFunction()))
337 return false;
338
Evan Cheng032f3262010-05-29 00:06:36 +0000339 Changed = FirstInLoop = false;
Eric Christopherb65c7b92014-10-14 06:26:57 +0000340 TII = MF.getSubtarget().getInstrInfo();
341 TLI = MF.getSubtarget().getTargetLowering();
342 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000343 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000344 MRI = &MF.getRegInfo();
Eric Christopherb65c7b92014-10-14 06:26:57 +0000345 InstrItins = MF.getSubtarget().getInstrItineraryData();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000346
Andrew Trickc40815d2012-02-08 21:23:03 +0000347 PreRegAlloc = MRI->isSSA();
348
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000349 if (PreRegAlloc)
350 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
351 else
352 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000353 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000354
Evan Chengd62719c2010-10-14 01:16:09 +0000355 if (PreRegAlloc) {
356 // Estimate register pressure during pre-regalloc pass.
357 unsigned NumRC = TRI->getNumRegClasses();
358 RegPressure.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000359 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000360 RegLimit.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000361 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
362 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +0000363 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Chengd62719c2010-10-14 01:16:09 +0000364 }
365
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000366 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000367 MLI = &getAnalysis<MachineLoopInfo>();
368 DT = &getAnalysis<MachineDominatorTree>();
369 AA = &getAnalysis<AliasAnalysis>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000370
Dan Gohman7929c442010-07-09 18:49:45 +0000371 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
372 while (!Worklist.empty()) {
373 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000374 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000375 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000376
Evan Cheng058b9f02010-04-08 01:03:47 +0000377 // If this is done before regalloc, only visit outer-most preheader-sporting
378 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000379 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
380 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000381 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000382 }
Dan Gohman79618d12009-01-15 22:01:38 +0000383
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000384 CurLoop->getExitBlocks(ExitBlocks);
385
Evan Cheng6ea59492010-04-07 00:41:17 +0000386 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000387 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000388 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000389 // CSEMap is initialized for loop header when the first instruction is
390 // being hoisted.
391 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000392 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000393 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000394 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000395
396 if (SinkInstsToAvoidSpills)
397 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000398 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000399 }
400
401 return Changed;
402}
403
Evan Cheng058b9f02010-04-08 01:03:47 +0000404/// InstructionStoresToFI - Return true if instruction stores to the
405/// specified frame.
406static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
407 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
408 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000409 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000410 continue;
411 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000412 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000413 if (Value->getFrameIndex() == FI)
414 return true;
415 }
416 }
417 return false;
418}
419
420/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
421/// gather register def and frame object update information.
422void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000423 BitVector &PhysRegDefs,
424 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000425 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000426 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000427 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000428 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000429 unsigned Def = 0;
430 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
431 const MachineOperand &MO = MI->getOperand(i);
432 if (MO.isFI()) {
433 // Remember if the instruction stores to the frame index.
434 int FI = MO.getIndex();
435 if (!StoredFIs.count(FI) &&
436 MFI->isSpillSlotObjectIndex(FI) &&
437 InstructionStoresToFI(MI, FI))
438 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000439 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000440 continue;
441 }
442
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000443 // We can't hoist an instruction defining a physreg that is clobbered in
444 // the loop.
445 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000446 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000447 continue;
448 }
449
Evan Cheng058b9f02010-04-08 01:03:47 +0000450 if (!MO.isReg())
451 continue;
452 unsigned Reg = MO.getReg();
453 if (!Reg)
454 continue;
455 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
456 "Not expecting virtual register!");
457
Evan Cheng0a2aff22010-04-13 18:16:00 +0000458 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000459 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000460 // If it's using a non-loop-invariant register, then it's obviously not
461 // safe to hoist.
462 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000463 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000464 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000465
466 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000467 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
468 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000469 if (!MO.isDead())
470 // Non-dead implicit def? This cannot be hoisted.
471 RuledOut = true;
472 // No need to check if a dead implicit def is also defined by
473 // another instruction.
474 continue;
475 }
476
477 // FIXME: For now, avoid instructions with multiple defs, unless
478 // it's a dead implicit def.
479 if (Def)
480 RuledOut = true;
481 else
482 Def = Reg;
483
484 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000485 // register, then this is not safe. Two defs is indicated by setting a
486 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000487 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000488 if (PhysRegDefs.test(*AS))
489 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000490 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000491 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000492 if (PhysRegClobbers.test(Reg))
493 // MI defined register is seen defined by another instruction in
494 // the loop, it cannot be a LICM candidate.
495 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000496 }
497
Evan Cheng0a2aff22010-04-13 18:16:00 +0000498 // Only consider reloads for now and remats which do not have register
499 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000500 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000501 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000502 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000503 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
504 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000505 }
506}
507
508/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
509/// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000510void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000511 MachineBasicBlock *Preheader = getCurPreheader();
512 if (!Preheader)
513 return;
514
Evan Cheng6ea59492010-04-07 00:41:17 +0000515 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000516 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
517 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000518
Evan Cheng058b9f02010-04-08 01:03:47 +0000519 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000520 SmallSet<int, 32> StoredFIs;
521
522 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000523 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000524 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000525 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
526 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000527
528 // If the header of the loop containing this basic block is a landing pad,
529 // then don't try to hoist instructions out of this loop.
530 const MachineLoop *ML = MLI->getLoopFor(BB);
531 if (ML && ML->getHeader()->isLandingPad()) continue;
532
Evan Cheng6ea59492010-04-07 00:41:17 +0000533 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000534 // FIXME: That means a reload that're reused in successor block(s) will not
535 // be LICM'ed.
Dan Gohman9d2d0532010-04-13 16:57:55 +0000536 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Cheng6ea59492010-04-07 00:41:17 +0000537 E = BB->livein_end(); I != E; ++I) {
538 unsigned Reg = *I;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000539 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
540 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000541 }
542
Evan Chengf192ca02011-10-11 23:48:44 +0000543 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000544 for (MachineBasicBlock::iterator
545 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000546 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000547 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000548 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000549 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000550
Evan Cheng7fede872012-03-27 01:50:58 +0000551 // Gather the registers read / clobbered by the terminator.
552 BitVector TermRegs(NumRegs);
553 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
554 if (TI != Preheader->end()) {
555 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
556 const MachineOperand &MO = TI->getOperand(i);
557 if (!MO.isReg())
558 continue;
559 unsigned Reg = MO.getReg();
560 if (!Reg)
561 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000562 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
563 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000564 }
565 }
566
Evan Cheng6ea59492010-04-07 00:41:17 +0000567 // Now evaluate whether the potential candidates qualify.
568 // 1. Check if the candidate defined register is defined by another
569 // instruction in the loop.
570 // 2. If the candidate is a load from stack slot (always true for now),
571 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000572 // 3. Make sure candidate def should not clobber
573 // registers read by the terminator. Similarly its def should not be
574 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000575 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000576 if (Candidates[i].FI != INT_MIN &&
577 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000578 continue;
579
Evan Cheng7fede872012-03-27 01:50:58 +0000580 unsigned Def = Candidates[i].Def;
581 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000582 bool Safe = true;
583 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000584 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
585 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000586 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000587 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000588 unsigned Reg = MO.getReg();
589 if (PhysRegDefs.test(Reg) ||
590 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000591 // If it's using a non-loop-invariant register, then it's obviously
592 // not safe to hoist.
593 Safe = false;
594 break;
595 }
596 }
597 if (Safe)
598 HoistPostRA(MI, Candidates[i].Def);
599 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000600 }
601}
602
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000603/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
604/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000605void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000606 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000607 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
608 MachineBasicBlock *BB = Blocks[i];
609 if (!BB->isLiveIn(Reg))
610 BB->addLiveIn(Reg);
611 for (MachineBasicBlock::iterator
612 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
613 MachineInstr *MI = &*MII;
614 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
615 MachineOperand &MO = MI->getOperand(i);
616 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
617 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
618 MO.setIsKill(false);
619 }
620 }
621 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000622}
623
624/// HoistPostRA - When an instruction is found to only use loop invariant
625/// operands that is safe to hoist, this instruction is called to do the
626/// dirty work.
627void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000628 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000629
Evan Cheng6ea59492010-04-07 00:41:17 +0000630 // Now move the instructions to the predecessor, inserting it before any
631 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000632 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
633 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000634
635 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000636 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000637 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000638
Andrew Trick5209c732012-02-08 21:23:00 +0000639 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000640 // loop invariant must be kept live throughout the whole loop. This is
641 // important to ensure later passes do not scavenge the def register.
642 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000643
644 ++NumPostRAHoisted;
645 Changed = true;
646}
647
Devang Patel453d4012011-10-11 18:09:58 +0000648// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
649// If not then a load from this mbb may not be safe to hoist.
650bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000651 if (SpeculationState != SpeculateUnknown)
652 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000653
Devang Patel453d4012011-10-11 18:09:58 +0000654 if (BB != CurLoop->getHeader()) {
655 // Check loop exiting blocks.
656 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
657 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
658 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
659 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000660 SpeculationState = SpeculateTrue;
661 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000662 }
663 }
664
Evan Chengf192ca02011-10-11 23:48:44 +0000665 SpeculationState = SpeculateFalse;
666 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000667}
668
Pete Cooper1eed5b52011-12-22 02:05:40 +0000669void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
670 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000671
Pete Cooper1eed5b52011-12-22 02:05:40 +0000672 // Remember livein register pressure.
673 BackTrace.push_back(RegPressure);
674}
Bill Wendling918cea22011-10-12 02:58:01 +0000675
Pete Cooper1eed5b52011-12-22 02:05:40 +0000676void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
677 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
678 BackTrace.pop_back();
679}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000680
Pete Cooper1eed5b52011-12-22 02:05:40 +0000681/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
682/// dominator tree node if its a leaf or all of its children are done. Walk
683/// up the dominator tree to destroy ancestors which are now done.
684void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000685 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
686 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000687 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000688 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000689
Pete Cooper1eed5b52011-12-22 02:05:40 +0000690 // Pop scope.
691 ExitScope(Node->getBlock());
692
693 // Now traverse upwards to pop ancestors whose offsprings are all done.
694 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
695 unsigned Left = --OpenChildren[Parent];
696 if (Left != 0)
697 break;
698 ExitScope(Parent->getBlock());
699 Node = Parent;
700 }
701}
702
703/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
704/// blocks dominated by the specified header block, and that are in the
705/// current loop) in depth first order w.r.t the DominatorTree. This allows
706/// us to visit definitions before uses, allowing us to hoist a loop body in
707/// one pass without iteration.
708///
709void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000710 MachineBasicBlock *Preheader = getCurPreheader();
711 if (!Preheader)
712 return;
713
Pete Cooper1eed5b52011-12-22 02:05:40 +0000714 SmallVector<MachineDomTreeNode*, 32> Scopes;
715 SmallVector<MachineDomTreeNode*, 8> WorkList;
716 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
717 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
718
719 // Perform a DFS walk to determine the order of visit.
720 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000721 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000722 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000723 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000724 MachineBasicBlock *BB = Node->getBlock();
725
726 // If the header of the loop containing this basic block is a landing pad,
727 // then don't try to hoist instructions out of this loop.
728 const MachineLoop *ML = MLI->getLoopFor(BB);
729 if (ML && ML->getHeader()->isLandingPad())
730 continue;
731
732 // If this subregion is not in the top level loop at all, exit.
733 if (!CurLoop->contains(BB))
734 continue;
735
736 Scopes.push_back(Node);
737 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
738 unsigned NumChildren = Children.size();
739
740 // Don't hoist things out of a large switch statement. This often causes
741 // code to be hoisted that wasn't going to be executed, and increases
742 // register pressure in a situation where it's likely to matter.
743 if (BB->succ_size() >= 25)
744 NumChildren = 0;
745
746 OpenChildren[Node] = NumChildren;
747 // Add children in reverse order as then the next popped worklist node is
748 // the first child of this node. This means we ultimately traverse the
749 // DOM tree in exactly the same order as if we'd recursed.
750 for (int i = (int)NumChildren-1; i >= 0; --i) {
751 MachineDomTreeNode *Child = Children[i];
752 ParentMap[Child] = Node;
753 WorkList.push_back(Child);
754 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000755 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000756
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000757 if (Scopes.size() == 0)
758 return;
759
760 // Compute registers which are livein into the loop headers.
761 RegSeen.clear();
762 BackTrace.clear();
763 InitRegPressure(Preheader);
764
Pete Cooper1eed5b52011-12-22 02:05:40 +0000765 // Now perform LICM.
766 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
767 MachineDomTreeNode *Node = Scopes[i];
768 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000769
Pete Cooper1eed5b52011-12-22 02:05:40 +0000770 EnterScope(MBB);
771
772 // Process the block
773 SpeculationState = SpeculateUnknown;
774 for (MachineBasicBlock::iterator
775 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
776 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
777 MachineInstr *MI = &*MII;
778 if (!Hoist(MI, Preheader))
779 UpdateRegPressure(MI);
780 MII = NextMII;
781 }
782
783 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
784 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000785 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000786}
787
Daniel Jasper15e69542015-03-14 10:58:38 +0000788void MachineLICM::SinkIntoLoop() {
789 MachineBasicBlock *Preheader = getCurPreheader();
790 if (!Preheader)
791 return;
792
793 SmallVector<MachineInstr *, 8> Candidates;
794 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
795 I != Preheader->instr_end(); ++I) {
796 // We need to ensure that we can safely move this instruction into the loop.
797 // As such, it must not have side-effects, e.g. such as a call has.
798 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
799 Candidates.push_back(I);
800 }
801
802 for (MachineInstr *I : Candidates) {
803 const MachineOperand &MO = I->getOperand(0);
804 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
805 continue;
806 if (!MRI->hasOneDef(MO.getReg()))
807 continue;
808 bool CanSink = true;
809 MachineBasicBlock *B = nullptr;
810 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
811 // FIXME: Come up with a proper cost model that estimates whether sinking
812 // the instruction (and thus possibly executing it on every loop
813 // iteration) is more expensive than a register.
814 // For now assumes that copies are cheap and thus almost always worth it.
815 if (!MI.isCopy()) {
816 CanSink = false;
817 break;
818 }
819 if (!B) {
820 B = MI.getParent();
821 continue;
822 }
823 B = DT->findNearestCommonDominator(B, MI.getParent());
824 if (!B) {
825 CanSink = false;
826 break;
827 }
828 }
829 if (!CanSink || !B || B == Preheader)
830 continue;
831 B->splice(B->getFirstNonPHI(), Preheader, I);
832 }
833}
834
Evan Cheng87066f02010-10-20 22:03:58 +0000835static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
836 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
837}
838
Evan Cheng90da66b2011-09-01 01:45:00 +0000839/// getRegisterClassIDAndCost - For a given MI, register, and the operand
840/// index, return the ID and cost of its representative register class.
841void
842MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
843 unsigned Reg, unsigned OpIdx,
844 unsigned &RCId, unsigned &RCCost) const {
845 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Patrik Hagglund05394352012-12-13 18:45:35 +0000846 MVT VT = *RC->vt_begin();
Owen Andersonca2f78a2011-11-16 01:02:57 +0000847 if (VT == MVT::Untyped) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000848 RCId = RC->getID();
849 RCCost = 1;
850 } else {
851 RCId = TLI->getRepRegClassFor(VT)->getID();
852 RCCost = TLI->getRepRegClassCostFor(VT);
853 }
854}
Andrew Trick5209c732012-02-08 21:23:00 +0000855
Evan Cheng44436302010-10-16 02:20:26 +0000856/// InitRegPressure - Find all virtual register references that are liveout of
857/// the preheader to initialize the starting "register pressure". Note this
858/// does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000859void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000860 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000861
Evan Cheng87066f02010-10-20 22:03:58 +0000862 // If the preheader has only a single predecessor and it ends with a
863 // fallthrough or an unconditional branch, then scan its predecessor for live
864 // defs as well. This happens whenever the preheader is created by splitting
865 // the critical edge from the loop predecessor to the loop header.
866 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000867 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000868 SmallVector<MachineOperand, 4> Cond;
869 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
870 InitRegPressure(*BB->pred_begin());
871 }
872
Evan Chengd62719c2010-10-14 01:16:09 +0000873 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
874 MII != E; ++MII) {
875 MachineInstr *MI = &*MII;
876 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
877 const MachineOperand &MO = MI->getOperand(i);
878 if (!MO.isReg() || MO.isImplicit())
879 continue;
880 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000881 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000882 continue;
Evan Chengd62719c2010-10-14 01:16:09 +0000883
David Blaikie70573dc2014-11-19 07:49:26 +0000884 bool isNew = RegSeen.insert(Reg).second;
Evan Cheng90da66b2011-09-01 01:45:00 +0000885 unsigned RCId, RCCost;
886 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng44436302010-10-16 02:20:26 +0000887 if (MO.isDef())
Evan Cheng90da66b2011-09-01 01:45:00 +0000888 RegPressure[RCId] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000889 else {
Evan Cheng87066f02010-10-20 22:03:58 +0000890 bool isKill = isOperandKill(MO, MRI);
891 if (isNew && !isKill)
Evan Cheng44436302010-10-16 02:20:26 +0000892 // Haven't seen this, it must be a livein.
Evan Cheng90da66b2011-09-01 01:45:00 +0000893 RegPressure[RCId] += RCCost;
Evan Cheng87066f02010-10-20 22:03:58 +0000894 else if (!isNew && isKill)
Evan Cheng90da66b2011-09-01 01:45:00 +0000895 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000896 }
Evan Chengd62719c2010-10-14 01:16:09 +0000897 }
898 }
899}
900
Evan Cheng87066f02010-10-20 22:03:58 +0000901/// UpdateRegPressure - Update estimate of register pressure after the
902/// specified instruction.
903void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
904 if (MI->isImplicitDef())
905 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000906
Evan Cheng87066f02010-10-20 22:03:58 +0000907 SmallVector<unsigned, 4> Defs;
Evan Chengd62719c2010-10-14 01:16:09 +0000908 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
909 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000910 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000911 continue;
912 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000913 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000914 continue;
915
David Blaikie70573dc2014-11-19 07:49:26 +0000916 bool isNew = RegSeen.insert(Reg).second;
Evan Cheng63c76082010-10-19 18:58:51 +0000917 if (MO.isDef())
918 Defs.push_back(Reg);
Evan Cheng87066f02010-10-20 22:03:58 +0000919 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000920 unsigned RCId, RCCost;
921 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +0000922 if (RCCost > RegPressure[RCId])
923 RegPressure[RCId] = 0;
924 else
Evan Cheng63c76082010-10-19 18:58:51 +0000925 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000926 }
Evan Chengd62719c2010-10-14 01:16:09 +0000927 }
Evan Chengd62719c2010-10-14 01:16:09 +0000928
Evan Cheng90da66b2011-09-01 01:45:00 +0000929 unsigned Idx = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000930 while (!Defs.empty()) {
931 unsigned Reg = Defs.pop_back_val();
Evan Cheng90da66b2011-09-01 01:45:00 +0000932 unsigned RCId, RCCost;
933 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Chengd62719c2010-10-14 01:16:09 +0000934 RegPressure[RCId] += RCCost;
Evan Cheng90da66b2011-09-01 01:45:00 +0000935 ++Idx;
Evan Chengd62719c2010-10-14 01:16:09 +0000936 }
937}
938
Andrew Trick5209c732012-02-08 21:23:00 +0000939/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel1d8ab462011-10-20 17:42:23 +0000940/// loads from global offset table or constant pool.
941static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000942 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000943 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000944 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000945 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
946 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
947 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000948 }
949 }
950 return false;
951}
952
Evan Cheng0a2aff22010-04-13 18:16:00 +0000953/// IsLICMCandidate - Returns true if the instruction may be a suitable
954/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
955/// not safe to hoist it.
956bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000957 // Check if it's safe to move the instruction.
958 bool DontMoveAcrossStore = true;
959 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000960 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000961
962 // If it is load then check if it is guaranteed to execute by making sure that
963 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000964 // the loop which does not execute this load, so we can't hoist it. Loads
965 // from constant memory are not safe to speculate all the time, for example
966 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000967 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000968 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000969 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000970 return false;
971
Evan Cheng0a2aff22010-04-13 18:16:00 +0000972 return true;
973}
974
975/// IsLoopInvariantInst - Returns true if the instruction is loop
976/// invariant. I.e., all virtual register operands are defined outside of the
977/// loop, physical registers aren't accessed explicitly, and there are no side
978/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000979///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000980bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
981 if (!IsLICMCandidate(I))
982 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000983
Bill Wendling70613b82008-05-12 19:38:32 +0000984 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000985 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
986 const MachineOperand &MO = I.getOperand(i);
987
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000988 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000989 continue;
990
Dan Gohman79618d12009-01-15 22:01:38 +0000991 unsigned Reg = MO.getReg();
992 if (Reg == 0) continue;
993
994 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000995 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000996 if (MO.isUse()) {
997 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000998 // and we can freely move its uses. Alternatively, if it's allocatable,
999 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +00001000 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +00001001 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001002 // Otherwise it's safe to move.
1003 continue;
1004 } else if (!MO.isDead()) {
1005 // A def that isn't dead. We can't move it.
1006 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +00001007 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1008 // If the reg is live into the loop, we can't hoist an instruction
1009 // which would clobber it.
1010 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001011 }
1012 }
Bill Wendlingcd01e892008-08-20 20:32:05 +00001013
1014 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001015 continue;
1016
Evan Chengd62719c2010-10-14 01:16:09 +00001017 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +00001018 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001019
1020 // If the loop contains the definition of an operand, then the instruction
1021 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001022 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001023 return false;
1024 }
1025
1026 // If we got this far, the instruction is loop invariant!
1027 return true;
1028}
1029
Evan Cheng399660c2009-02-05 08:45:46 +00001030
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001031/// HasLoopPHIUse - Return true if the specified instruction is used by a
1032/// phi node and hoisting it could cause a copy to be inserted.
1033bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1034 SmallVector<const MachineInstr*, 8> Work(1, MI);
1035 do {
1036 MI = Work.pop_back_val();
1037 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1038 if (!MO->isReg() || !MO->isDef())
1039 continue;
1040 unsigned Reg = MO->getReg();
1041 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1042 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001043 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001044 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001045 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001046 // A PHI inside the loop causes a copy because the live range of Reg is
1047 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001048 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001049 return true;
1050 // A PHI in an exit block can cause a copy to be inserted if the PHI
1051 // has multiple predecessors in the loop with different values.
1052 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001053 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001054 return true;
1055 continue;
1056 }
1057 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001058 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1059 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001060 }
Evan Chengef42bea2011-04-11 21:09:18 +00001061 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001062 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001063 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001064}
1065
Evan Cheng63c76082010-10-19 18:58:51 +00001066/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1067/// and an use in the current loop, return true if the target considered
1068/// it 'high'.
1069bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +00001070 unsigned DefIdx, unsigned Reg) const {
1071 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001072 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001073
Owen Andersonb36376e2014-03-17 19:36:09 +00001074 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1075 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001076 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001077 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001078 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001079 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1080 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001081 if (!MO.isReg() || !MO.isUse())
1082 continue;
1083 unsigned MOReg = MO.getReg();
1084 if (MOReg != Reg)
1085 continue;
1086
Owen Andersonb36376e2014-03-17 19:36:09 +00001087 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001088 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001089 }
1090
Evan Cheng63c76082010-10-19 18:58:51 +00001091 // Only look at the first in loop use.
1092 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001093 }
1094
Evan Cheng63c76082010-10-19 18:58:51 +00001095 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001096}
1097
Evan Chenge96b8d72010-10-26 02:08:50 +00001098/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1099/// the operand latency between its def and a use is one or less.
1100bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001101 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001102 return true;
1103 if (!InstrItins || InstrItins->isEmpty())
1104 return false;
1105
1106 bool isCheap = false;
1107 unsigned NumDefs = MI.getDesc().getNumDefs();
1108 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1109 MachineOperand &DefMO = MI.getOperand(i);
1110 if (!DefMO.isReg() || !DefMO.isDef())
1111 continue;
1112 --NumDefs;
1113 unsigned Reg = DefMO.getReg();
1114 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1115 continue;
1116
1117 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1118 return false;
1119 isCheap = true;
1120 }
1121
1122 return isCheap;
1123}
1124
Evan Cheng87066f02010-10-20 22:03:58 +00001125/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng44436302010-10-16 02:20:26 +00001126/// if hoisting an instruction of the given cost matrix can cause high
1127/// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001128bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1129 bool CheapInstr) {
Evan Cheng87066f02010-10-20 22:03:58 +00001130 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1131 CI != CE; ++CI) {
Andrew Trick5209c732012-02-08 21:23:00 +00001132 if (CI->second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001133 continue;
1134
1135 unsigned RCId = CI->first;
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001136 unsigned Limit = RegLimit[RCId];
1137 int Cost = CI->second;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001138
1139 // Don't hoist cheap instructions if they would increase register pressure,
1140 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001141 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001142 return true;
1143
Evan Cheng87066f02010-10-20 22:03:58 +00001144 for (unsigned i = BackTrace.size(); i != 0; --i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001145 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001146 if (RP[RCId] + Cost >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001147 return true;
1148 }
Evan Cheng44436302010-10-16 02:20:26 +00001149 }
1150
1151 return false;
1152}
1153
Evan Cheng87066f02010-10-20 22:03:58 +00001154/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1155/// current block and update their register pressures to reflect the effect
1156/// of hoisting MI from the current block to the preheader.
1157void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1158 if (MI->isImplicitDef())
1159 return;
1160
1161 // First compute the 'cost' of the instruction, i.e. its contribution
1162 // to register pressure.
1163 DenseMap<unsigned, int> Cost;
1164 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1165 const MachineOperand &MO = MI->getOperand(i);
1166 if (!MO.isReg() || MO.isImplicit())
1167 continue;
1168 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001169 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng87066f02010-10-20 22:03:58 +00001170 continue;
1171
Evan Cheng90da66b2011-09-01 01:45:00 +00001172 unsigned RCId, RCCost;
1173 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +00001174 if (MO.isDef()) {
1175 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1176 if (CI != Cost.end())
1177 CI->second += RCCost;
1178 else
1179 Cost.insert(std::make_pair(RCId, RCCost));
1180 } else if (isOperandKill(MO, MRI)) {
1181 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1182 if (CI != Cost.end())
1183 CI->second -= RCCost;
1184 else
1185 Cost.insert(std::make_pair(RCId, -RCCost));
1186 }
1187 }
1188
1189 // Update register pressure of blocks from loop header to current block.
1190 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001191 SmallVectorImpl<unsigned> &RP = BackTrace[i];
Evan Cheng87066f02010-10-20 22:03:58 +00001192 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1193 CI != CE; ++CI) {
1194 unsigned RCId = CI->first;
1195 RP[RCId] += CI->second;
1196 }
1197 }
1198}
1199
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001200/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1201/// the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001202bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001203 if (MI.isImplicitDef())
1204 return true;
1205
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001206 // Besides removing computation from the loop, hoisting an instruction has
1207 // these effects:
1208 //
1209 // - The value defined by the instruction becomes live across the entire
1210 // loop. This increases register pressure in the loop.
1211 //
1212 // - If the value is used by a PHI in the loop, a copy will be required for
1213 // lowering the PHI after extending the live range.
1214 //
1215 // - When hoisting the last use of a value in the loop, that value no longer
1216 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001217
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001218 bool CheapInstr = IsCheapInstruction(MI);
1219 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001220
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001221 // Don't hoist a cheap instruction if it would create a copy in the loop.
1222 if (CheapInstr && CreatesCopy) {
1223 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1224 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001225 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001226
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001227 // Rematerializable instructions should always be hoisted since the register
1228 // allocator can just pull them down again when needed.
1229 if (TII->isTriviallyReMaterializable(&MI, AA))
1230 return true;
1231
1232 // Estimate register pressure to determine whether to LICM the instruction.
1233 // In low register pressure situation, we can be more aggressive about
1234 // hoisting. Also, favors hoisting long latency instructions even in
1235 // moderately high pressure situation.
1236 // Cheap instructions will only be hoisted if they don't increase register
1237 // pressure at all.
1238 // FIXME: If there are long latency loop-invariant instructions inside the
1239 // loop at this point, why didn't the optimizer's LICM hoist them?
1240 DenseMap<unsigned, int> Cost;
1241 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1242 const MachineOperand &MO = MI.getOperand(i);
1243 if (!MO.isReg() || MO.isImplicit())
1244 continue;
1245 unsigned Reg = MO.getReg();
1246 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1247 continue;
1248
1249 unsigned RCId, RCCost;
1250 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1251 if (MO.isDef()) {
1252 if (HasHighOperandLatency(MI, i, Reg)) {
1253 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1254 ++NumHighLatency;
1255 return true;
1256 }
1257 Cost[RCId] += RCCost;
1258 } else if (isOperandKill(MO, MRI)) {
1259 // Is a virtual register use is a kill, hoisting it out of the loop
1260 // may actually reduce register pressure or be register pressure
1261 // neutral.
1262 Cost[RCId] -= RCCost;
1263 }
1264 }
1265
1266 // Visit BBs from header to current BB, if hoisting this doesn't cause
1267 // high register pressure, then it's safe to proceed.
1268 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1269 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1270 ++NumLowRP;
1271 return true;
1272 }
1273
1274 // Don't risk increasing register pressure if it would create copies.
1275 if (CreatesCopy) {
1276 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001277 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001278 }
1279
1280 // Do not "speculate" in high register pressure situation. If an
1281 // instruction is not guaranteed to be executed in the loop, it's best to be
1282 // conservative.
1283 if (AvoidSpeculation &&
1284 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1285 DEBUG(dbgs() << "Won't speculate: " << MI);
1286 return false;
1287 }
1288
1289 // High register pressure situation, only hoist if the instruction is going
1290 // to be remat'ed.
1291 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1292 !MI.isInvariantLoad(AA)) {
1293 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1294 return false;
1295 }
Evan Cheng399660c2009-02-05 08:45:46 +00001296
1297 return true;
1298}
1299
Dan Gohman104f57c2009-10-29 17:47:20 +00001300MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001301 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001302 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001303 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001304
Dan Gohman104f57c2009-10-29 17:47:20 +00001305 // If not, we may be able to unfold a load and hoist that.
1306 // First test whether the instruction is loading from an amenable
1307 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001308 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001309 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001310
Dan Gohman104f57c2009-10-29 17:47:20 +00001311 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001312 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001313 unsigned NewOpc =
1314 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1315 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001316 /*UnfoldStore=*/false,
1317 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001318 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001319 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001320 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001321 MachineFunction &MF = *MI->getParent()->getParent();
1322 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001323 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001324 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001325
Dan Gohman104f57c2009-10-29 17:47:20 +00001326 SmallVector<MachineInstr *, 2> NewMIs;
1327 bool Success =
1328 TII->unfoldMemoryOperand(MF, MI, Reg,
1329 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1330 NewMIs);
1331 (void)Success;
1332 assert(Success &&
1333 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1334 "succeeded!");
1335 assert(NewMIs.size() == 2 &&
1336 "Unfolded a load into multiple instructions!");
1337 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001338 MachineBasicBlock::iterator Pos = MI;
1339 MBB->insert(Pos, NewMIs[0]);
1340 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001341 // If unfolding produced a load that wasn't loop-invariant or profitable to
1342 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001343 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001344 NewMIs[0]->eraseFromParent();
1345 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001346 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001347 }
Evan Cheng87066f02010-10-20 22:03:58 +00001348
1349 // Update register pressure for the unfolded instruction.
1350 UpdateRegPressure(NewMIs[1]);
1351
Dan Gohman104f57c2009-10-29 17:47:20 +00001352 // Otherwise we successfully unfolded a load that we can hoist.
1353 MI->eraseFromParent();
1354 return NewMIs[0];
1355}
1356
Evan Chengf42b5af2009-11-03 21:40:02 +00001357void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1358 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1359 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001360 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001361 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001362 }
1363}
1364
Evan Cheng7ff83192009-11-07 03:52:02 +00001365const MachineInstr*
1366MachineLICM::LookForDuplicate(const MachineInstr *MI,
1367 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001368 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1369 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001370 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001371 return PrevMI;
1372 }
Craig Topperc0196b12014-04-14 00:51:57 +00001373 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001374}
1375
1376bool MachineLICM::EliminateCSE(MachineInstr *MI,
1377 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001378 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1379 // the undef property onto uses.
1380 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001381 return false;
1382
1383 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001384 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001385
1386 // Replace virtual registers defined by MI by their counterparts defined
1387 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001388 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001389 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1390 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001391
1392 // Physical registers may not differ here.
1393 assert((!MO.isReg() || MO.getReg() == 0 ||
1394 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1395 MO.getReg() == Dup->getOperand(i).getReg()) &&
1396 "Instructions with different phys regs are not identical!");
1397
1398 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001399 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1400 Defs.push_back(i);
1401 }
1402
1403 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1404 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1405 unsigned Idx = Defs[i];
1406 unsigned Reg = MI->getOperand(Idx).getReg();
1407 unsigned DupReg = Dup->getOperand(Idx).getReg();
1408 OrigRCs.push_back(MRI->getRegClass(DupReg));
1409
1410 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1411 // Restore old RCs if more than one defs.
1412 for (unsigned j = 0; j != i; ++j)
1413 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1414 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001415 }
Evan Cheng921152f2009-11-05 00:51:13 +00001416 }
Evan Chengaa563df2011-10-17 19:50:12 +00001417
1418 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1419 unsigned Idx = Defs[i];
1420 unsigned Reg = MI->getOperand(Idx).getReg();
1421 unsigned DupReg = Dup->getOperand(Idx).getReg();
1422 MRI->replaceRegWith(Reg, DupReg);
1423 MRI->clearKillFlags(DupReg);
1424 }
1425
Evan Cheng7ff83192009-11-07 03:52:02 +00001426 MI->eraseFromParent();
1427 ++NumCSEed;
1428 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001429 }
1430 return false;
1431}
1432
Evan Chengaf138952011-10-12 00:09:14 +00001433/// MayCSE - Return true if the given instruction will be CSE'd if it's
1434/// hoisted out of the loop.
1435bool MachineLICM::MayCSE(MachineInstr *MI) {
1436 unsigned Opcode = MI->getOpcode();
1437 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1438 CI = CSEMap.find(Opcode);
1439 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1440 // the undef property onto uses.
1441 if (CI == CSEMap.end() || MI->isImplicitDef())
1442 return false;
1443
Craig Topperc0196b12014-04-14 00:51:57 +00001444 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001445}
1446
Bill Wendling70613b82008-05-12 19:38:32 +00001447/// Hoist - When an instruction is found to use only loop invariant operands
1448/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001449///
Evan Cheng87066f02010-10-20 22:03:58 +00001450bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001451 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001452 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001453 // If not, try unfolding a hoistable load.
1454 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001455 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001456 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001457
Dan Gohman79618d12009-01-15 22:01:38 +00001458 // Now move the instructions to the predecessor, inserting it before any
1459 // terminator instructions.
1460 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001461 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001462 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001463 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001464 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001465 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001466 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001467 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001468 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001469 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001470
Evan Chengf42b5af2009-11-03 21:40:02 +00001471 // If this is the first instruction being hoisted to the preheader,
1472 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001473 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001474 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001475 FirstInLoop = false;
1476 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001477
Evan Cheng399660c2009-02-05 08:45:46 +00001478 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001479 unsigned Opcode = MI->getOpcode();
1480 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1481 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001482 if (!EliminateCSE(MI, CI)) {
1483 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001484 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001485
Evan Cheng87066f02010-10-20 22:03:58 +00001486 // Update register pressure for BBs from header to this block.
1487 UpdateBackTraceRegPressure(MI);
1488
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001489 // Clear the kill flags of any register this instruction defines,
1490 // since they may need to be live throughout the entire loop
1491 // rather than just live for part of it.
1492 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1493 MachineOperand &MO = MI->getOperand(i);
1494 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001495 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001496 }
1497
Evan Cheng399660c2009-02-05 08:45:46 +00001498 // Add to the CSE map.
1499 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001500 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001501 else
1502 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001503 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001504
Dan Gohman79618d12009-01-15 22:01:38 +00001505 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001506 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001507
1508 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001509}
Dan Gohman3570f812010-06-22 17:25:57 +00001510
1511MachineBasicBlock *MachineLICM::getCurPreheader() {
1512 // Determine the block to which to hoist instructions. If we can't find a
1513 // suitable loop predecessor, we can't do any hoisting.
1514
1515 // If we've tried to get a preheader and failed, don't try again.
1516 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001517 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001518
1519 if (!CurPreheader) {
1520 CurPreheader = CurLoop->getLoopPreheader();
1521 if (!CurPreheader) {
1522 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1523 if (!Pred) {
1524 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001525 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001526 }
1527
1528 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1529 if (!CurPreheader) {
1530 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001531 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001532 }
1533 }
1534 }
1535 return CurPreheader;
1536}