blob: 353a27b6cfb106046672e00e05c2d7fdaba3b8d0 [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
Evan Cheng44436302010-10-16 02:20:26 +000052STATISTIC(NumHoisted,
53 "Number of machine instructions hoisted out of loops");
54STATISTIC(NumLowRP,
55 "Number of instructions hoisted in low reg pressure situation");
56STATISTIC(NumHighLatency,
57 "Number of high latency instructions hoisted");
58STATISTIC(NumCSEed,
59 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000060STATISTIC(NumPostRAHoisted,
61 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000062
Bill Wendlingfb706bc2007-12-07 21:42:31 +000063namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000064 class MachineLICM : public MachineFunctionPass {
Bill Wendling5da19452008-01-02 19:32:43 +000065 const TargetMachine *TM;
Bill Wendling38236ef2007-12-11 23:27:51 +000066 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000067 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000068 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000069 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000070 MachineRegisterInfo *MRI;
71 const InstrItineraryData *InstrItins;
Andrew Trickc40815d2012-02-08 21:23:03 +000072 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000073
Bill Wendlingfb706bc2007-12-07 21:42:31 +000074 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000075 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000076 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000077 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000078
Bill Wendlingfb706bc2007-12-07 21:42:31 +000079 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000080 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000081 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000082 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000083 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000084
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000085 // Exit blocks for CurLoop.
86 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
87
88 bool isExitBlock(const MachineBasicBlock *MBB) const {
89 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
90 ExitBlocks.end();
91 }
92
Evan Chengd62719c2010-10-14 01:16:09 +000093 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +000094 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +000095 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +000096
97 // Register pressure "limit" per register class. If the pressure
98 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +000099 SmallVector<unsigned, 8> RegLimit;
100
Evan Cheng44436302010-10-16 02:20:26 +0000101 // Register pressure on path leading from loop preheader to current BB.
102 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
103
Dale Johannesen329d4742010-07-29 17:45:24 +0000104 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000105 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000106
Evan Chengf192ca02011-10-11 23:48:44 +0000107 enum {
108 SpeculateFalse = 0,
109 SpeculateTrue = 1,
110 SpeculateUnknown = 2
111 };
112
Devang Patel453d4012011-10-11 18:09:58 +0000113 // If a MBB does not dominate loop exiting blocks then it may not safe
114 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000115 // Tri-state: 0 - false, 1 - true, 2 - unknown
116 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000117
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000118 public:
119 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000120 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000121 MachineFunctionPass(ID), PreRegAlloc(true) {
122 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
123 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000124
125 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
127 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
128 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000129
Craig Topper4584cd52014-03-07 09:26:03 +0000130 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000131
Craig Topper4584cd52014-03-07 09:26:03 +0000132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000133 AU.addRequired<MachineLoopInfo>();
134 AU.addRequired<MachineDominatorTree>();
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000135 AU.addRequired<AliasAnalysis>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000136 AU.addPreserved<MachineLoopInfo>();
137 AU.addPreserved<MachineDominatorTree>();
138 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000139 }
Evan Cheng399660c2009-02-05 08:45:46 +0000140
Craig Topper4584cd52014-03-07 09:26:03 +0000141 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000142 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000143 RegPressure.clear();
144 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000145 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000146 CSEMap.clear();
147 }
148
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000149 private:
Evan Cheng058b9f02010-04-08 01:03:47 +0000150 /// CandidateInfo - Keep track of information about hoisting candidates.
151 struct CandidateInfo {
152 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000153 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000154 int FI;
155 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
156 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000157 };
158
159 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
160 /// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000161 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000162
163 /// HoistPostRA - When an instruction is found to only use loop invariant
164 /// operands that is safe to hoist, this instruction is called to do the
165 /// dirty work.
166 void HoistPostRA(MachineInstr *MI, unsigned Def);
167
168 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
169 /// gather register def and frame object update information.
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000170 void ProcessMI(MachineInstr *MI,
171 BitVector &PhysRegDefs,
172 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000173 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000174 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000175
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000176 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
177 /// current loop.
178 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000179
Evan Cheng0a2aff22010-04-13 18:16:00 +0000180 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner0b7ae202010-07-12 00:00:35 +0000181 /// candidate for LICM. e.g. If the instruction is a call, then it's
182 /// obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000183 bool IsLICMCandidate(MachineInstr &I);
184
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000185 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000186 /// invariant. I.e., all virtual register operands are defined outside of
187 /// the loop, physical registers aren't accessed (explicitly or implicitly),
188 /// and the instruction is hoistable.
Andrew Trick5209c732012-02-08 21:23:00 +0000189 ///
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000190 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000191
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000192 /// HasLoopPHIUse - Return true if the specified instruction is used by any
193 /// phi node in the current loop.
194 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000195
Evan Cheng63c76082010-10-19 18:58:51 +0000196 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
197 /// and an use in the current loop, return true if the target considered
198 /// it 'high'.
Evan Chenge96b8d72010-10-26 02:08:50 +0000199 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
200 unsigned Reg) const;
201
202 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000203
Evan Cheng87066f02010-10-20 22:03:58 +0000204 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
205 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng44436302010-10-16 02:20:26 +0000206 /// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +0000207 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000208
209 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
210 /// the current block and update their register pressures to reflect the
211 /// effect of hoisting MI from the current block to the preheader.
212 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000213
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000214 /// IsProfitableToHoist - Return true if it is potentially profitable to
215 /// hoist the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000216 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000217
Devang Patel453d4012011-10-11 18:09:58 +0000218 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
219 /// If not then a load from this mbb may not be safe to hoist.
220 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
221
Pete Cooper1eed5b52011-12-22 02:05:40 +0000222 void EnterScope(MachineBasicBlock *MBB);
223
224 void ExitScope(MachineBasicBlock *MBB);
225
226 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
227 /// dominator tree node if its a leaf or all of its children are done. Walk
228 /// up the dominator tree to destroy ancestors which are now done.
229 void ExitScopeIfDone(MachineDomTreeNode *Node,
230 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
231 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
232
233 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
234 /// blocks dominated by the specified header block, and that are in the
235 /// current loop) in depth first order w.r.t the DominatorTree. This allows
236 /// us to visit definitions before uses, allowing us to hoist a loop body in
237 /// one pass without iteration.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000238 ///
Pete Cooper1eed5b52011-12-22 02:05:40 +0000239 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
240 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000241
Evan Cheng90da66b2011-09-01 01:45:00 +0000242 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
243 /// index, return the ID and cost of its representative register class by
244 /// reference.
245 void getRegisterClassIDAndCost(const MachineInstr *MI,
246 unsigned Reg, unsigned OpIdx,
247 unsigned &RCId, unsigned &RCCost) const;
248
Evan Cheng44436302010-10-16 02:20:26 +0000249 /// InitRegPressure - Find all virtual register references that are liveout
250 /// of the preheader to initialize the starting "register pressure". Note
251 /// this does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000252 void InitRegPressure(MachineBasicBlock *BB);
253
Evan Cheng87066f02010-10-20 22:03:58 +0000254 /// UpdateRegPressure - Update estimate of register pressure after the
255 /// specified instruction.
256 void UpdateRegPressure(const MachineInstr *MI);
Evan Chengd62719c2010-10-14 01:16:09 +0000257
Dan Gohman104f57c2009-10-29 17:47:20 +0000258 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
259 /// the load itself could be hoisted. Return the unfolded and hoistable
260 /// load, or null if the load couldn't be unfolded or if it wouldn't
261 /// be hoistable.
262 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
263
Evan Cheng7ff83192009-11-07 03:52:02 +0000264 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
265 /// duplicate of MI. Return this instruction if it's found.
266 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
267 std::vector<const MachineInstr*> &PrevMIs);
268
Evan Cheng921152f2009-11-05 00:51:13 +0000269 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
270 /// the preheader that compute the same value. If it's found, do a RAU on
271 /// with the definition of the existing instruction rather than hoisting
272 /// the instruction to the preheader.
273 bool EliminateCSE(MachineInstr *MI,
274 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
275
Evan Chengaf138952011-10-12 00:09:14 +0000276 /// MayCSE - Return true if the given instruction will be CSE'd if it's
277 /// hoisted out of the loop.
278 bool MayCSE(MachineInstr *MI);
279
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000280 /// Hoist - When an instruction is found to only use loop invariant operands
281 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng87066f02010-10-20 22:03:58 +0000282 /// It returns true if the instruction is hoisted.
283 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000284
285 /// InitCSEMap - Initialize the CSE map with instructions that are in the
286 /// current loop preheader that may become duplicates of instructions that
287 /// are hoisted out of the loop.
288 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000289
290 /// getCurPreheader - Get the preheader for the current loop, splitting
291 /// a critical edge if needed.
292 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000293 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000294} // end anonymous namespace
295
Dan Gohmand78c4002008-05-13 00:00:25 +0000296char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000297char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000298INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
299 "Machine Loop Invariant Code Motion", false, false)
300INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
301INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
302INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
303INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000304 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000305
Dan Gohman3570f812010-06-22 17:25:57 +0000306/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
307/// loop that has a unique predecessor.
308static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000309 // Check whether this loop even has a unique predecessor.
310 if (!CurLoop->getLoopPredecessor())
311 return false;
312 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000313 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000314 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000315 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000316 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000317 return true;
318}
319
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000320bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000321 if (skipOptnoneFunction(*MF.getFunction()))
322 return false;
323
Evan Cheng032f3262010-05-29 00:06:36 +0000324 Changed = FirstInLoop = false;
Bill Wendling58bb4f12008-08-31 02:30:23 +0000325 TM = &MF.getTarget();
Eric Christopherd9134482014-08-04 21:25:23 +0000326 TII = TM->getSubtargetImpl()->getInstrInfo();
327 TLI = TM->getSubtargetImpl()->getTargetLowering();
328 TRI = TM->getSubtargetImpl()->getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000329 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000330 MRI = &MF.getRegInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000331 InstrItins = TM->getSubtargetImpl()->getInstrItineraryData();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000332
Andrew Trickc40815d2012-02-08 21:23:03 +0000333 PreRegAlloc = MRI->isSSA();
334
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000335 if (PreRegAlloc)
336 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
337 else
338 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000339 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000340
Evan Chengd62719c2010-10-14 01:16:09 +0000341 if (PreRegAlloc) {
342 // Estimate register pressure during pre-regalloc pass.
343 unsigned NumRC = TRI->getNumRegClasses();
344 RegPressure.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000345 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000346 RegLimit.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000347 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
348 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +0000349 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Chengd62719c2010-10-14 01:16:09 +0000350 }
351
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000352 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000353 MLI = &getAnalysis<MachineLoopInfo>();
354 DT = &getAnalysis<MachineDominatorTree>();
355 AA = &getAnalysis<AliasAnalysis>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000356
Dan Gohman7929c442010-07-09 18:49:45 +0000357 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
358 while (!Worklist.empty()) {
359 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000360 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000361 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000362
Evan Cheng058b9f02010-04-08 01:03:47 +0000363 // If this is done before regalloc, only visit outer-most preheader-sporting
364 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000365 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
366 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000367 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000368 }
Dan Gohman79618d12009-01-15 22:01:38 +0000369
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000370 CurLoop->getExitBlocks(ExitBlocks);
371
Evan Cheng6ea59492010-04-07 00:41:17 +0000372 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000373 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000374 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000375 // CSEMap is initialized for loop header when the first instruction is
376 // being hoisted.
377 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000378 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000379 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000380 CSEMap.clear();
381 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000382 }
383
384 return Changed;
385}
386
Evan Cheng058b9f02010-04-08 01:03:47 +0000387/// InstructionStoresToFI - Return true if instruction stores to the
388/// specified frame.
389static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
390 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
391 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000392 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000393 continue;
394 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000395 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000396 if (Value->getFrameIndex() == FI)
397 return true;
398 }
399 }
400 return false;
401}
402
403/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
404/// gather register def and frame object update information.
405void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000406 BitVector &PhysRegDefs,
407 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000408 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000409 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000410 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000411 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000412 unsigned Def = 0;
413 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
414 const MachineOperand &MO = MI->getOperand(i);
415 if (MO.isFI()) {
416 // Remember if the instruction stores to the frame index.
417 int FI = MO.getIndex();
418 if (!StoredFIs.count(FI) &&
419 MFI->isSpillSlotObjectIndex(FI) &&
420 InstructionStoresToFI(MI, FI))
421 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000422 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000423 continue;
424 }
425
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000426 // We can't hoist an instruction defining a physreg that is clobbered in
427 // the loop.
428 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000429 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000430 continue;
431 }
432
Evan Cheng058b9f02010-04-08 01:03:47 +0000433 if (!MO.isReg())
434 continue;
435 unsigned Reg = MO.getReg();
436 if (!Reg)
437 continue;
438 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
439 "Not expecting virtual register!");
440
Evan Cheng0a2aff22010-04-13 18:16:00 +0000441 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000442 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000443 // If it's using a non-loop-invariant register, then it's obviously not
444 // safe to hoist.
445 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000446 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000447 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000448
449 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000450 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
451 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000452 if (!MO.isDead())
453 // Non-dead implicit def? This cannot be hoisted.
454 RuledOut = true;
455 // No need to check if a dead implicit def is also defined by
456 // another instruction.
457 continue;
458 }
459
460 // FIXME: For now, avoid instructions with multiple defs, unless
461 // it's a dead implicit def.
462 if (Def)
463 RuledOut = true;
464 else
465 Def = Reg;
466
467 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000468 // register, then this is not safe. Two defs is indicated by setting a
469 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000470 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000471 if (PhysRegDefs.test(*AS))
472 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000473 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000474 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000475 if (PhysRegClobbers.test(Reg))
476 // MI defined register is seen defined by another instruction in
477 // the loop, it cannot be a LICM candidate.
478 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000479 }
480
Evan Cheng0a2aff22010-04-13 18:16:00 +0000481 // Only consider reloads for now and remats which do not have register
482 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000483 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000484 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000485 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000486 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
487 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000488 }
489}
490
491/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
492/// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000493void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000494 MachineBasicBlock *Preheader = getCurPreheader();
495 if (!Preheader)
496 return;
497
Evan Cheng6ea59492010-04-07 00:41:17 +0000498 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000499 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
500 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000501
Evan Cheng058b9f02010-04-08 01:03:47 +0000502 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000503 SmallSet<int, 32> StoredFIs;
504
505 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000506 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000507 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000508 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
509 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000510
511 // If the header of the loop containing this basic block is a landing pad,
512 // then don't try to hoist instructions out of this loop.
513 const MachineLoop *ML = MLI->getLoopFor(BB);
514 if (ML && ML->getHeader()->isLandingPad()) continue;
515
Evan Cheng6ea59492010-04-07 00:41:17 +0000516 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000517 // FIXME: That means a reload that're reused in successor block(s) will not
518 // be LICM'ed.
Dan Gohman9d2d0532010-04-13 16:57:55 +0000519 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Cheng6ea59492010-04-07 00:41:17 +0000520 E = BB->livein_end(); I != E; ++I) {
521 unsigned Reg = *I;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000522 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
523 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000524 }
525
Evan Chengf192ca02011-10-11 23:48:44 +0000526 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000527 for (MachineBasicBlock::iterator
528 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000529 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000530 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000531 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000532 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000533
Evan Cheng7fede872012-03-27 01:50:58 +0000534 // Gather the registers read / clobbered by the terminator.
535 BitVector TermRegs(NumRegs);
536 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
537 if (TI != Preheader->end()) {
538 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
539 const MachineOperand &MO = TI->getOperand(i);
540 if (!MO.isReg())
541 continue;
542 unsigned Reg = MO.getReg();
543 if (!Reg)
544 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000545 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
546 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000547 }
548 }
549
Evan Cheng6ea59492010-04-07 00:41:17 +0000550 // Now evaluate whether the potential candidates qualify.
551 // 1. Check if the candidate defined register is defined by another
552 // instruction in the loop.
553 // 2. If the candidate is a load from stack slot (always true for now),
554 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000555 // 3. Make sure candidate def should not clobber
556 // registers read by the terminator. Similarly its def should not be
557 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000558 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000559 if (Candidates[i].FI != INT_MIN &&
560 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000561 continue;
562
Evan Cheng7fede872012-03-27 01:50:58 +0000563 unsigned Def = Candidates[i].Def;
564 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000565 bool Safe = true;
566 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000567 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
568 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000569 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000570 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000571 unsigned Reg = MO.getReg();
572 if (PhysRegDefs.test(Reg) ||
573 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000574 // If it's using a non-loop-invariant register, then it's obviously
575 // not safe to hoist.
576 Safe = false;
577 break;
578 }
579 }
580 if (Safe)
581 HoistPostRA(MI, Candidates[i].Def);
582 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000583 }
584}
585
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000586/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
587/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000588void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000589 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000590 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
591 MachineBasicBlock *BB = Blocks[i];
592 if (!BB->isLiveIn(Reg))
593 BB->addLiveIn(Reg);
594 for (MachineBasicBlock::iterator
595 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
596 MachineInstr *MI = &*MII;
597 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
598 MachineOperand &MO = MI->getOperand(i);
599 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
600 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
601 MO.setIsKill(false);
602 }
603 }
604 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000605}
606
607/// HoistPostRA - When an instruction is found to only use loop invariant
608/// operands that is safe to hoist, this instruction is called to do the
609/// dirty work.
610void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000611 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000612
Evan Cheng6ea59492010-04-07 00:41:17 +0000613 // Now move the instructions to the predecessor, inserting it before any
614 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000615 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
616 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000617
618 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000619 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000620 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000621
Andrew Trick5209c732012-02-08 21:23:00 +0000622 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000623 // loop invariant must be kept live throughout the whole loop. This is
624 // important to ensure later passes do not scavenge the def register.
625 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000626
627 ++NumPostRAHoisted;
628 Changed = true;
629}
630
Devang Patel453d4012011-10-11 18:09:58 +0000631// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
632// If not then a load from this mbb may not be safe to hoist.
633bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000634 if (SpeculationState != SpeculateUnknown)
635 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000636
Devang Patel453d4012011-10-11 18:09:58 +0000637 if (BB != CurLoop->getHeader()) {
638 // Check loop exiting blocks.
639 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
640 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
641 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
642 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000643 SpeculationState = SpeculateTrue;
644 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000645 }
646 }
647
Evan Chengf192ca02011-10-11 23:48:44 +0000648 SpeculationState = SpeculateFalse;
649 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000650}
651
Pete Cooper1eed5b52011-12-22 02:05:40 +0000652void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
653 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000654
Pete Cooper1eed5b52011-12-22 02:05:40 +0000655 // Remember livein register pressure.
656 BackTrace.push_back(RegPressure);
657}
Bill Wendling918cea22011-10-12 02:58:01 +0000658
Pete Cooper1eed5b52011-12-22 02:05:40 +0000659void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
660 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
661 BackTrace.pop_back();
662}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000663
Pete Cooper1eed5b52011-12-22 02:05:40 +0000664/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
665/// dominator tree node if its a leaf or all of its children are done. Walk
666/// up the dominator tree to destroy ancestors which are now done.
667void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000668 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
669 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000670 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000671 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000672
Pete Cooper1eed5b52011-12-22 02:05:40 +0000673 // Pop scope.
674 ExitScope(Node->getBlock());
675
676 // Now traverse upwards to pop ancestors whose offsprings are all done.
677 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
678 unsigned Left = --OpenChildren[Parent];
679 if (Left != 0)
680 break;
681 ExitScope(Parent->getBlock());
682 Node = Parent;
683 }
684}
685
686/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
687/// blocks dominated by the specified header block, and that are in the
688/// current loop) in depth first order w.r.t the DominatorTree. This allows
689/// us to visit definitions before uses, allowing us to hoist a loop body in
690/// one pass without iteration.
691///
692void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
693 SmallVector<MachineDomTreeNode*, 32> Scopes;
694 SmallVector<MachineDomTreeNode*, 8> WorkList;
695 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
696 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
697
698 // Perform a DFS walk to determine the order of visit.
699 WorkList.push_back(HeaderN);
700 do {
701 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000702 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000703 MachineBasicBlock *BB = Node->getBlock();
704
705 // If the header of the loop containing this basic block is a landing pad,
706 // then don't try to hoist instructions out of this loop.
707 const MachineLoop *ML = MLI->getLoopFor(BB);
708 if (ML && ML->getHeader()->isLandingPad())
709 continue;
710
711 // If this subregion is not in the top level loop at all, exit.
712 if (!CurLoop->contains(BB))
713 continue;
714
715 Scopes.push_back(Node);
716 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
717 unsigned NumChildren = Children.size();
718
719 // Don't hoist things out of a large switch statement. This often causes
720 // code to be hoisted that wasn't going to be executed, and increases
721 // register pressure in a situation where it's likely to matter.
722 if (BB->succ_size() >= 25)
723 NumChildren = 0;
724
725 OpenChildren[Node] = NumChildren;
726 // Add children in reverse order as then the next popped worklist node is
727 // the first child of this node. This means we ultimately traverse the
728 // DOM tree in exactly the same order as if we'd recursed.
729 for (int i = (int)NumChildren-1; i >= 0; --i) {
730 MachineDomTreeNode *Child = Children[i];
731 ParentMap[Child] = Node;
732 WorkList.push_back(Child);
733 }
734 } while (!WorkList.empty());
735
736 if (Scopes.size() != 0) {
737 MachineBasicBlock *Preheader = getCurPreheader();
738 if (!Preheader)
739 return;
740
Evan Cheng87066f02010-10-20 22:03:58 +0000741 // Compute registers which are livein into the loop headers.
Evan Cheng63c76082010-10-19 18:58:51 +0000742 RegSeen.clear();
743 BackTrace.clear();
744 InitRegPressure(Preheader);
Daniel Dunbar418204e2010-10-19 17:14:24 +0000745 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000746
Pete Cooper1eed5b52011-12-22 02:05:40 +0000747 // Now perform LICM.
748 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
749 MachineDomTreeNode *Node = Scopes[i];
750 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000751
Pete Cooper1eed5b52011-12-22 02:05:40 +0000752 MachineBasicBlock *Preheader = getCurPreheader();
753 if (!Preheader)
754 continue;
755
756 EnterScope(MBB);
757
758 // Process the block
759 SpeculationState = SpeculateUnknown;
760 for (MachineBasicBlock::iterator
761 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
762 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
763 MachineInstr *MI = &*MII;
764 if (!Hoist(MI, Preheader))
765 UpdateRegPressure(MI);
766 MII = NextMII;
767 }
768
769 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
770 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000771 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000772}
773
Evan Cheng87066f02010-10-20 22:03:58 +0000774static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
775 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
776}
777
Evan Cheng90da66b2011-09-01 01:45:00 +0000778/// getRegisterClassIDAndCost - For a given MI, register, and the operand
779/// index, return the ID and cost of its representative register class.
780void
781MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
782 unsigned Reg, unsigned OpIdx,
783 unsigned &RCId, unsigned &RCCost) const {
784 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Patrik Hagglund05394352012-12-13 18:45:35 +0000785 MVT VT = *RC->vt_begin();
Owen Andersonca2f78a2011-11-16 01:02:57 +0000786 if (VT == MVT::Untyped) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000787 RCId = RC->getID();
788 RCCost = 1;
789 } else {
790 RCId = TLI->getRepRegClassFor(VT)->getID();
791 RCCost = TLI->getRepRegClassCostFor(VT);
792 }
793}
Andrew Trick5209c732012-02-08 21:23:00 +0000794
Evan Cheng44436302010-10-16 02:20:26 +0000795/// InitRegPressure - Find all virtual register references that are liveout of
796/// the preheader to initialize the starting "register pressure". Note this
797/// does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000798void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000799 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000800
Evan Cheng87066f02010-10-20 22:03:58 +0000801 // If the preheader has only a single predecessor and it ends with a
802 // fallthrough or an unconditional branch, then scan its predecessor for live
803 // defs as well. This happens whenever the preheader is created by splitting
804 // the critical edge from the loop predecessor to the loop header.
805 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000806 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000807 SmallVector<MachineOperand, 4> Cond;
808 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
809 InitRegPressure(*BB->pred_begin());
810 }
811
Evan Chengd62719c2010-10-14 01:16:09 +0000812 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
813 MII != E; ++MII) {
814 MachineInstr *MI = &*MII;
815 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
816 const MachineOperand &MO = MI->getOperand(i);
817 if (!MO.isReg() || MO.isImplicit())
818 continue;
819 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000820 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000821 continue;
Evan Chengd62719c2010-10-14 01:16:09 +0000822
Andrew Trick2006bbe2010-10-19 02:50:50 +0000823 bool isNew = RegSeen.insert(Reg);
Evan Cheng90da66b2011-09-01 01:45:00 +0000824 unsigned RCId, RCCost;
825 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng44436302010-10-16 02:20:26 +0000826 if (MO.isDef())
Evan Cheng90da66b2011-09-01 01:45:00 +0000827 RegPressure[RCId] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000828 else {
Evan Cheng87066f02010-10-20 22:03:58 +0000829 bool isKill = isOperandKill(MO, MRI);
830 if (isNew && !isKill)
Evan Cheng44436302010-10-16 02:20:26 +0000831 // Haven't seen this, it must be a livein.
Evan Cheng90da66b2011-09-01 01:45:00 +0000832 RegPressure[RCId] += RCCost;
Evan Cheng87066f02010-10-20 22:03:58 +0000833 else if (!isNew && isKill)
Evan Cheng90da66b2011-09-01 01:45:00 +0000834 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000835 }
Evan Chengd62719c2010-10-14 01:16:09 +0000836 }
837 }
838}
839
Evan Cheng87066f02010-10-20 22:03:58 +0000840/// UpdateRegPressure - Update estimate of register pressure after the
841/// specified instruction.
842void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
843 if (MI->isImplicitDef())
844 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000845
Evan Cheng87066f02010-10-20 22:03:58 +0000846 SmallVector<unsigned, 4> Defs;
Evan Chengd62719c2010-10-14 01:16:09 +0000847 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
848 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000849 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000850 continue;
851 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000852 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000853 continue;
854
Andrew Trick2006bbe2010-10-19 02:50:50 +0000855 bool isNew = RegSeen.insert(Reg);
Evan Cheng63c76082010-10-19 18:58:51 +0000856 if (MO.isDef())
857 Defs.push_back(Reg);
Evan Cheng87066f02010-10-20 22:03:58 +0000858 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000859 unsigned RCId, RCCost;
860 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +0000861 if (RCCost > RegPressure[RCId])
862 RegPressure[RCId] = 0;
863 else
Evan Cheng63c76082010-10-19 18:58:51 +0000864 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000865 }
Evan Chengd62719c2010-10-14 01:16:09 +0000866 }
Evan Chengd62719c2010-10-14 01:16:09 +0000867
Evan Cheng90da66b2011-09-01 01:45:00 +0000868 unsigned Idx = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000869 while (!Defs.empty()) {
870 unsigned Reg = Defs.pop_back_val();
Evan Cheng90da66b2011-09-01 01:45:00 +0000871 unsigned RCId, RCCost;
872 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Chengd62719c2010-10-14 01:16:09 +0000873 RegPressure[RCId] += RCCost;
Evan Cheng90da66b2011-09-01 01:45:00 +0000874 ++Idx;
Evan Chengd62719c2010-10-14 01:16:09 +0000875 }
876}
877
Andrew Trick5209c732012-02-08 21:23:00 +0000878/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel1d8ab462011-10-20 17:42:23 +0000879/// loads from global offset table or constant pool.
880static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000881 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000882 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000883 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000884 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
885 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
886 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000887 }
888 }
889 return false;
890}
891
Evan Cheng0a2aff22010-04-13 18:16:00 +0000892/// IsLICMCandidate - Returns true if the instruction may be a suitable
893/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
894/// not safe to hoist it.
895bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000896 // Check if it's safe to move the instruction.
897 bool DontMoveAcrossStore = true;
898 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000899 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000900
901 // If it is load then check if it is guaranteed to execute by making sure that
902 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000903 // the loop which does not execute this load, so we can't hoist it. Loads
904 // from constant memory are not safe to speculate all the time, for example
905 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000906 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000907 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000908 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000909 return false;
910
Evan Cheng0a2aff22010-04-13 18:16:00 +0000911 return true;
912}
913
914/// IsLoopInvariantInst - Returns true if the instruction is loop
915/// invariant. I.e., all virtual register operands are defined outside of the
916/// loop, physical registers aren't accessed explicitly, and there are no side
917/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000918///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000919bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
920 if (!IsLICMCandidate(I))
921 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000922
Bill Wendling70613b82008-05-12 19:38:32 +0000923 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000924 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
925 const MachineOperand &MO = I.getOperand(i);
926
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000927 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000928 continue;
929
Dan Gohman79618d12009-01-15 22:01:38 +0000930 unsigned Reg = MO.getReg();
931 if (Reg == 0) continue;
932
933 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000934 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000935 if (MO.isUse()) {
936 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000937 // and we can freely move its uses. Alternatively, if it's allocatable,
938 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000939 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000940 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000941 // Otherwise it's safe to move.
942 continue;
943 } else if (!MO.isDead()) {
944 // A def that isn't dead. We can't move it.
945 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000946 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
947 // If the reg is live into the loop, we can't hoist an instruction
948 // which would clobber it.
949 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000950 }
951 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000952
953 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000954 continue;
955
Evan Chengd62719c2010-10-14 01:16:09 +0000956 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000957 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000958
959 // If the loop contains the definition of an operand, then the instruction
960 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000961 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000962 return false;
963 }
964
965 // If we got this far, the instruction is loop invariant!
966 return true;
967}
968
Evan Cheng399660c2009-02-05 08:45:46 +0000969
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000970/// HasLoopPHIUse - Return true if the specified instruction is used by a
971/// phi node and hoisting it could cause a copy to be inserted.
972bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
973 SmallVector<const MachineInstr*, 8> Work(1, MI);
974 do {
975 MI = Work.pop_back_val();
976 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
977 if (!MO->isReg() || !MO->isDef())
978 continue;
979 unsigned Reg = MO->getReg();
980 if (!TargetRegisterInfo::isVirtualRegister(Reg))
981 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000982 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000983 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000984 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000985 // A PHI inside the loop causes a copy because the live range of Reg is
986 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000987 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000988 return true;
989 // A PHI in an exit block can cause a copy to be inserted if the PHI
990 // has multiple predecessors in the loop with different values.
991 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000992 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000993 return true;
994 continue;
995 }
996 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000997 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
998 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000999 }
Evan Chengef42bea2011-04-11 21:09:18 +00001000 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001001 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001002 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001003}
1004
Evan Cheng63c76082010-10-19 18:58:51 +00001005/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1006/// and an use in the current loop, return true if the target considered
1007/// it 'high'.
1008bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +00001009 unsigned DefIdx, unsigned Reg) const {
1010 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001011 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001012
Owen Andersonb36376e2014-03-17 19:36:09 +00001013 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1014 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001015 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001016 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001017 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001018 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1019 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001020 if (!MO.isReg() || !MO.isUse())
1021 continue;
1022 unsigned MOReg = MO.getReg();
1023 if (MOReg != Reg)
1024 continue;
1025
Owen Andersonb36376e2014-03-17 19:36:09 +00001026 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001027 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001028 }
1029
Evan Cheng63c76082010-10-19 18:58:51 +00001030 // Only look at the first in loop use.
1031 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001032 }
1033
Evan Cheng63c76082010-10-19 18:58:51 +00001034 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001035}
1036
Evan Chenge96b8d72010-10-26 02:08:50 +00001037/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1038/// the operand latency between its def and a use is one or less.
1039bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001040 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001041 return true;
1042 if (!InstrItins || InstrItins->isEmpty())
1043 return false;
1044
1045 bool isCheap = false;
1046 unsigned NumDefs = MI.getDesc().getNumDefs();
1047 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1048 MachineOperand &DefMO = MI.getOperand(i);
1049 if (!DefMO.isReg() || !DefMO.isDef())
1050 continue;
1051 --NumDefs;
1052 unsigned Reg = DefMO.getReg();
1053 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1054 continue;
1055
1056 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1057 return false;
1058 isCheap = true;
1059 }
1060
1061 return isCheap;
1062}
1063
Evan Cheng87066f02010-10-20 22:03:58 +00001064/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng44436302010-10-16 02:20:26 +00001065/// if hoisting an instruction of the given cost matrix can cause high
1066/// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001067bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1068 bool CheapInstr) {
Evan Cheng87066f02010-10-20 22:03:58 +00001069 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1070 CI != CE; ++CI) {
Andrew Trick5209c732012-02-08 21:23:00 +00001071 if (CI->second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001072 continue;
1073
1074 unsigned RCId = CI->first;
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001075 unsigned Limit = RegLimit[RCId];
1076 int Cost = CI->second;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001077
1078 // Don't hoist cheap instructions if they would increase register pressure,
1079 // even if we're under the limit.
1080 if (CheapInstr)
1081 return true;
1082
Evan Cheng87066f02010-10-20 22:03:58 +00001083 for (unsigned i = BackTrace.size(); i != 0; --i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001084 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001085 if (RP[RCId] + Cost >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001086 return true;
1087 }
Evan Cheng44436302010-10-16 02:20:26 +00001088 }
1089
1090 return false;
1091}
1092
Evan Cheng87066f02010-10-20 22:03:58 +00001093/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1094/// current block and update their register pressures to reflect the effect
1095/// of hoisting MI from the current block to the preheader.
1096void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1097 if (MI->isImplicitDef())
1098 return;
1099
1100 // First compute the 'cost' of the instruction, i.e. its contribution
1101 // to register pressure.
1102 DenseMap<unsigned, int> Cost;
1103 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1104 const MachineOperand &MO = MI->getOperand(i);
1105 if (!MO.isReg() || MO.isImplicit())
1106 continue;
1107 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001108 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng87066f02010-10-20 22:03:58 +00001109 continue;
1110
Evan Cheng90da66b2011-09-01 01:45:00 +00001111 unsigned RCId, RCCost;
1112 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +00001113 if (MO.isDef()) {
1114 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1115 if (CI != Cost.end())
1116 CI->second += RCCost;
1117 else
1118 Cost.insert(std::make_pair(RCId, RCCost));
1119 } else if (isOperandKill(MO, MRI)) {
1120 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1121 if (CI != Cost.end())
1122 CI->second -= RCCost;
1123 else
1124 Cost.insert(std::make_pair(RCId, -RCCost));
1125 }
1126 }
1127
1128 // Update register pressure of blocks from loop header to current block.
1129 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001130 SmallVectorImpl<unsigned> &RP = BackTrace[i];
Evan Cheng87066f02010-10-20 22:03:58 +00001131 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1132 CI != CE; ++CI) {
1133 unsigned RCId = CI->first;
1134 RP[RCId] += CI->second;
1135 }
1136 }
1137}
1138
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001139/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1140/// the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001141bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001142 if (MI.isImplicitDef())
1143 return true;
1144
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001145 // Besides removing computation from the loop, hoisting an instruction has
1146 // these effects:
1147 //
1148 // - The value defined by the instruction becomes live across the entire
1149 // loop. This increases register pressure in the loop.
1150 //
1151 // - If the value is used by a PHI in the loop, a copy will be required for
1152 // lowering the PHI after extending the live range.
1153 //
1154 // - When hoisting the last use of a value in the loop, that value no longer
1155 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001156
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001157 bool CheapInstr = IsCheapInstruction(MI);
1158 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001159
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001160 // Don't hoist a cheap instruction if it would create a copy in the loop.
1161 if (CheapInstr && CreatesCopy) {
1162 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1163 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001164 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001165
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001166 // Rematerializable instructions should always be hoisted since the register
1167 // allocator can just pull them down again when needed.
1168 if (TII->isTriviallyReMaterializable(&MI, AA))
1169 return true;
1170
1171 // Estimate register pressure to determine whether to LICM the instruction.
1172 // In low register pressure situation, we can be more aggressive about
1173 // hoisting. Also, favors hoisting long latency instructions even in
1174 // moderately high pressure situation.
1175 // Cheap instructions will only be hoisted if they don't increase register
1176 // pressure at all.
1177 // FIXME: If there are long latency loop-invariant instructions inside the
1178 // loop at this point, why didn't the optimizer's LICM hoist them?
1179 DenseMap<unsigned, int> Cost;
1180 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1181 const MachineOperand &MO = MI.getOperand(i);
1182 if (!MO.isReg() || MO.isImplicit())
1183 continue;
1184 unsigned Reg = MO.getReg();
1185 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1186 continue;
1187
1188 unsigned RCId, RCCost;
1189 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1190 if (MO.isDef()) {
1191 if (HasHighOperandLatency(MI, i, Reg)) {
1192 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1193 ++NumHighLatency;
1194 return true;
1195 }
1196 Cost[RCId] += RCCost;
1197 } else if (isOperandKill(MO, MRI)) {
1198 // Is a virtual register use is a kill, hoisting it out of the loop
1199 // may actually reduce register pressure or be register pressure
1200 // neutral.
1201 Cost[RCId] -= RCCost;
1202 }
1203 }
1204
1205 // Visit BBs from header to current BB, if hoisting this doesn't cause
1206 // high register pressure, then it's safe to proceed.
1207 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1208 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1209 ++NumLowRP;
1210 return true;
1211 }
1212
1213 // Don't risk increasing register pressure if it would create copies.
1214 if (CreatesCopy) {
1215 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001216 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001217 }
1218
1219 // Do not "speculate" in high register pressure situation. If an
1220 // instruction is not guaranteed to be executed in the loop, it's best to be
1221 // conservative.
1222 if (AvoidSpeculation &&
1223 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1224 DEBUG(dbgs() << "Won't speculate: " << MI);
1225 return false;
1226 }
1227
1228 // High register pressure situation, only hoist if the instruction is going
1229 // to be remat'ed.
1230 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1231 !MI.isInvariantLoad(AA)) {
1232 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1233 return false;
1234 }
Evan Cheng399660c2009-02-05 08:45:46 +00001235
1236 return true;
1237}
1238
Dan Gohman104f57c2009-10-29 17:47:20 +00001239MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001240 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001241 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001242 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001243
Dan Gohman104f57c2009-10-29 17:47:20 +00001244 // If not, we may be able to unfold a load and hoist that.
1245 // First test whether the instruction is loading from an amenable
1246 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001247 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001248 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001249
Dan Gohman104f57c2009-10-29 17:47:20 +00001250 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001251 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001252 unsigned NewOpc =
1253 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1254 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001255 /*UnfoldStore=*/false,
1256 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001257 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001258 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001259 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001260 MachineFunction &MF = *MI->getParent()->getParent();
1261 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001262 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001263 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001264
Dan Gohman104f57c2009-10-29 17:47:20 +00001265 SmallVector<MachineInstr *, 2> NewMIs;
1266 bool Success =
1267 TII->unfoldMemoryOperand(MF, MI, Reg,
1268 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1269 NewMIs);
1270 (void)Success;
1271 assert(Success &&
1272 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1273 "succeeded!");
1274 assert(NewMIs.size() == 2 &&
1275 "Unfolded a load into multiple instructions!");
1276 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001277 MachineBasicBlock::iterator Pos = MI;
1278 MBB->insert(Pos, NewMIs[0]);
1279 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001280 // If unfolding produced a load that wasn't loop-invariant or profitable to
1281 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001282 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001283 NewMIs[0]->eraseFromParent();
1284 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001285 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001286 }
Evan Cheng87066f02010-10-20 22:03:58 +00001287
1288 // Update register pressure for the unfolded instruction.
1289 UpdateRegPressure(NewMIs[1]);
1290
Dan Gohman104f57c2009-10-29 17:47:20 +00001291 // Otherwise we successfully unfolded a load that we can hoist.
1292 MI->eraseFromParent();
1293 return NewMIs[0];
1294}
1295
Evan Chengf42b5af2009-11-03 21:40:02 +00001296void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1297 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1298 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001299 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001300 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001301 }
1302}
1303
Evan Cheng7ff83192009-11-07 03:52:02 +00001304const MachineInstr*
1305MachineLICM::LookForDuplicate(const MachineInstr *MI,
1306 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001307 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1308 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001309 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001310 return PrevMI;
1311 }
Craig Topperc0196b12014-04-14 00:51:57 +00001312 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001313}
1314
1315bool MachineLICM::EliminateCSE(MachineInstr *MI,
1316 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001317 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1318 // the undef property onto uses.
1319 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001320 return false;
1321
1322 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001323 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001324
1325 // Replace virtual registers defined by MI by their counterparts defined
1326 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001327 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001328 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1329 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001330
1331 // Physical registers may not differ here.
1332 assert((!MO.isReg() || MO.getReg() == 0 ||
1333 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1334 MO.getReg() == Dup->getOperand(i).getReg()) &&
1335 "Instructions with different phys regs are not identical!");
1336
1337 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001338 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1339 Defs.push_back(i);
1340 }
1341
1342 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1343 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1344 unsigned Idx = Defs[i];
1345 unsigned Reg = MI->getOperand(Idx).getReg();
1346 unsigned DupReg = Dup->getOperand(Idx).getReg();
1347 OrigRCs.push_back(MRI->getRegClass(DupReg));
1348
1349 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1350 // Restore old RCs if more than one defs.
1351 for (unsigned j = 0; j != i; ++j)
1352 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1353 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001354 }
Evan Cheng921152f2009-11-05 00:51:13 +00001355 }
Evan Chengaa563df2011-10-17 19:50:12 +00001356
1357 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1358 unsigned Idx = Defs[i];
1359 unsigned Reg = MI->getOperand(Idx).getReg();
1360 unsigned DupReg = Dup->getOperand(Idx).getReg();
1361 MRI->replaceRegWith(Reg, DupReg);
1362 MRI->clearKillFlags(DupReg);
1363 }
1364
Evan Cheng7ff83192009-11-07 03:52:02 +00001365 MI->eraseFromParent();
1366 ++NumCSEed;
1367 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001368 }
1369 return false;
1370}
1371
Evan Chengaf138952011-10-12 00:09:14 +00001372/// MayCSE - Return true if the given instruction will be CSE'd if it's
1373/// hoisted out of the loop.
1374bool MachineLICM::MayCSE(MachineInstr *MI) {
1375 unsigned Opcode = MI->getOpcode();
1376 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1377 CI = CSEMap.find(Opcode);
1378 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1379 // the undef property onto uses.
1380 if (CI == CSEMap.end() || MI->isImplicitDef())
1381 return false;
1382
Craig Topperc0196b12014-04-14 00:51:57 +00001383 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001384}
1385
Bill Wendling70613b82008-05-12 19:38:32 +00001386/// Hoist - When an instruction is found to use only loop invariant operands
1387/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001388///
Evan Cheng87066f02010-10-20 22:03:58 +00001389bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001390 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001391 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001392 // If not, try unfolding a hoistable load.
1393 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001394 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001395 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001396
Dan Gohman79618d12009-01-15 22:01:38 +00001397 // Now move the instructions to the predecessor, inserting it before any
1398 // terminator instructions.
1399 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001400 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001401 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001402 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001403 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001404 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001405 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001406 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001407 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001408 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001409
Evan Chengf42b5af2009-11-03 21:40:02 +00001410 // If this is the first instruction being hoisted to the preheader,
1411 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001412 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001413 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001414 FirstInLoop = false;
1415 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001416
Evan Cheng399660c2009-02-05 08:45:46 +00001417 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001418 unsigned Opcode = MI->getOpcode();
1419 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1420 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001421 if (!EliminateCSE(MI, CI)) {
1422 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001423 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001424
Evan Cheng87066f02010-10-20 22:03:58 +00001425 // Update register pressure for BBs from header to this block.
1426 UpdateBackTraceRegPressure(MI);
1427
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001428 // Clear the kill flags of any register this instruction defines,
1429 // since they may need to be live throughout the entire loop
1430 // rather than just live for part of it.
1431 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1432 MachineOperand &MO = MI->getOperand(i);
1433 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001434 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001435 }
1436
Evan Cheng399660c2009-02-05 08:45:46 +00001437 // Add to the CSE map.
1438 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001439 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001440 else
1441 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001442 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001443
Dan Gohman79618d12009-01-15 22:01:38 +00001444 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001445 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001446
1447 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001448}
Dan Gohman3570f812010-06-22 17:25:57 +00001449
1450MachineBasicBlock *MachineLICM::getCurPreheader() {
1451 // Determine the block to which to hoist instructions. If we can't find a
1452 // suitable loop predecessor, we can't do any hoisting.
1453
1454 // If we've tried to get a preheader and failed, don't try again.
1455 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001456 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001457
1458 if (!CurPreheader) {
1459 CurPreheader = CurLoop->getLoopPreheader();
1460 if (!CurPreheader) {
1461 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1462 if (!Pred) {
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 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1468 if (!CurPreheader) {
1469 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001470 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001471 }
1472 }
1473 }
1474 return CurPreheader;
1475}