blob: 68d2efdb1d0dca5bc65c49fa5fd6dc8a4e66fa77 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Wendling0f940c92007-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 Gohmanc475c362009-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 Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
Chris Lattnerac695822008-01-04 06:41:45 +000023#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-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 Wendling0f940c92007-12-07 21:42:31 +000028#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000031#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000033#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Chengab8be962011-06-29 01:14:12 +000034#include "llvm/MC/MCInstrItineraries.h"
Evan Cheng7007e4c2011-10-12 21:33:49 +000035#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000036#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000037#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-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"
Bill Wendling0f940c92007-12-07 21:42:31 +000042using namespace llvm;
43
Stephen Hinesdce4a402014-05-29 02:49:00 -070044#define DEBUG_TYPE "machine-licm"
45
Evan Cheng7007e4c2011-10-12 21:33:49 +000046static cl::opt<bool>
47AvoidSpeculation("avoid-speculation",
48 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73b5bb32011-10-26 01:26:57 +000049 cl::init(true), cl::Hidden);
Evan Cheng7007e4c2011-10-12 21:33:49 +000050
Evan Cheng03a9fdf2010-10-16 02:20:26 +000051STATISTIC(NumHoisted,
52 "Number of machine instructions hoisted out of loops");
53STATISTIC(NumLowRP,
54 "Number of instructions hoisted in low reg pressure situation");
55STATISTIC(NumHighLatency,
56 "Number of high latency instructions hoisted");
57STATISTIC(NumCSEed,
58 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000059STATISTIC(NumPostRAHoisted,
60 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000061
Bill Wendling0f940c92007-12-07 21:42:31 +000062namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 class MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000064 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000065 const TargetInstrInfo *TII;
Benjamin Kramer69e42db2013-01-11 20:05:37 +000066 const TargetLoweringBase *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000067 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000068 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000069 MachineRegisterInfo *MRI;
70 const InstrItineraryData *InstrItins;
Andrew Trick9d41bd52012-02-08 21:23:03 +000071 bool PreRegAlloc;
Bill Wendling12ebf142007-12-11 19:40:06 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000074 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000075 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000076 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000077
Bill Wendling0f940c92007-12-07 21:42:31 +000078 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000079 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000080 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000081 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000082 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000083
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +000084 // Exit blocks for CurLoop.
85 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
86
87 bool isExitBlock(const MachineBasicBlock *MBB) const {
88 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
89 ExitBlocks.end();
90 }
91
Evan Cheng0e673912010-10-14 01:16:09 +000092 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000093 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000094 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000095
96 // Register pressure "limit" per register class. If the pressure
97 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000098 SmallVector<unsigned, 8> RegLimit;
99
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000100 // Register pressure on path leading from loop preheader to current BB.
101 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
102
Dale Johannesenc46a5f22010-07-29 17:45:24 +0000103 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +0000104 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +0000105
Evan Chengfad62872011-10-11 23:48:44 +0000106 enum {
107 SpeculateFalse = 0,
108 SpeculateTrue = 1,
109 SpeculateUnknown = 2
110 };
111
Devang Patel2e350472011-10-11 18:09:58 +0000112 // If a MBB does not dominate loop exiting blocks then it may not safe
113 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000114 // Tri-state: 0 - false, 1 - true, 2 - unknown
115 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000116
Bill Wendling0f940c92007-12-07 21:42:31 +0000117 public:
118 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000119 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000120 MachineFunctionPass(ID), PreRegAlloc(true) {
121 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
122 }
Evan Chengd94671a2010-04-07 00:41:17 +0000123
124 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000125 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
126 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
127 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000128
Stephen Hines36b56882014-04-23 16:57:46 -0700129 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendling0f940c92007-12-07 21:42:31 +0000130
Stephen Hines36b56882014-04-23 16:57:46 -0700131 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendling0f940c92007-12-07 21:42:31 +0000132 AU.addRequired<MachineLoopInfo>();
133 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000134 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000135 AU.addPreserved<MachineLoopInfo>();
136 AU.addPreserved<MachineDominatorTree>();
137 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000138 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000139
Stephen Hines36b56882014-04-23 16:57:46 -0700140 void releaseMemory() override {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000141 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000142 RegPressure.clear();
143 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000144 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000145 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
146 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
147 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000148 CSEMap.clear();
149 }
150
Bill Wendling0f940c92007-12-07 21:42:31 +0000151 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000152 /// CandidateInfo - Keep track of information about hoisting candidates.
153 struct CandidateInfo {
154 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000155 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000156 int FI;
157 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
158 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000159 };
160
161 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
162 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000163 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000164
165 /// HoistPostRA - When an instruction is found to only use loop invariant
166 /// operands that is safe to hoist, this instruction is called to do the
167 /// dirty work.
168 void HoistPostRA(MachineInstr *MI, unsigned Def);
169
170 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
171 /// gather register def and frame object update information.
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000172 void ProcessMI(MachineInstr *MI,
173 BitVector &PhysRegDefs,
174 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000175 SmallSet<int, 32> &StoredFIs,
Craig Topper9e639e82013-07-11 16:22:38 +0000176 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000177
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000178 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
179 /// current loop.
180 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000181
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000182 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000183 /// candidate for LICM. e.g. If the instruction is a call, then it's
184 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000185 bool IsLICMCandidate(MachineInstr &I);
186
Bill Wendling041b3f82007-12-08 23:58:46 +0000187 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000188 /// invariant. I.e., all virtual register operands are defined outside of
189 /// the loop, physical registers aren't accessed (explicitly or implicitly),
190 /// and the instruction is hoistable.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000191 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000192 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000193
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000194 /// HasLoopPHIUse - Return true if the specified instruction is used by any
195 /// phi node in the current loop.
196 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengd67705f2011-04-11 21:09:18 +0000197
Evan Cheng23128422010-10-19 18:58:51 +0000198 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
199 /// and an use in the current loop, return true if the target considered
200 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000201 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
202 unsigned Reg) const;
203
204 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000205
Evan Cheng134982d2010-10-20 22:03:58 +0000206 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
207 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000208 /// register pressure.
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +0000209 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng134982d2010-10-20 22:03:58 +0000210
211 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
212 /// the current block and update their register pressures to reflect the
213 /// effect of hoisting MI from the current block to the preheader.
214 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000215
Evan Cheng45e94d62009-02-04 09:19:56 +0000216 /// IsProfitableToHoist - Return true if it is potentially profitable to
217 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000218 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000219
Devang Patel2e350472011-10-11 18:09:58 +0000220 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
221 /// If not then a load from this mbb may not be safe to hoist.
222 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
223
Pete Cooperacde91e2011-12-22 02:05:40 +0000224 void EnterScope(MachineBasicBlock *MBB);
225
226 void ExitScope(MachineBasicBlock *MBB);
227
228 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
229 /// dominator tree node if its a leaf or all of its children are done. Walk
230 /// up the dominator tree to destroy ancestors which are now done.
231 void ExitScopeIfDone(MachineDomTreeNode *Node,
232 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
233 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
234
235 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
236 /// blocks dominated by the specified header block, and that are in the
237 /// current loop) in depth first order w.r.t the DominatorTree. This allows
238 /// us to visit definitions before uses, allowing us to hoist a loop body in
239 /// one pass without iteration.
Bill Wendling0f940c92007-12-07 21:42:31 +0000240 ///
Pete Cooperacde91e2011-12-22 02:05:40 +0000241 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
242 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000243
Evan Cheng61560e22011-09-01 01:45:00 +0000244 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
245 /// index, return the ID and cost of its representative register class by
246 /// reference.
247 void getRegisterClassIDAndCost(const MachineInstr *MI,
248 unsigned Reg, unsigned OpIdx,
249 unsigned &RCId, unsigned &RCCost) const;
250
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000251 /// InitRegPressure - Find all virtual register references that are liveout
252 /// of the preheader to initialize the starting "register pressure". Note
253 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000254 void InitRegPressure(MachineBasicBlock *BB);
255
Evan Cheng134982d2010-10-20 22:03:58 +0000256 /// UpdateRegPressure - Update estimate of register pressure after the
257 /// specified instruction.
258 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000259
Dan Gohman5c952302009-10-29 17:47:20 +0000260 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
261 /// the load itself could be hoisted. Return the unfolded and hoistable
262 /// load, or null if the load couldn't be unfolded or if it wouldn't
263 /// be hoistable.
264 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
265
Evan Cheng78e5c112009-11-07 03:52:02 +0000266 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
267 /// duplicate of MI. Return this instruction if it's found.
268 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
269 std::vector<const MachineInstr*> &PrevMIs);
270
Evan Cheng9fb744e2009-11-05 00:51:13 +0000271 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
272 /// the preheader that compute the same value. If it's found, do a RAU on
273 /// with the definition of the existing instruction rather than hoisting
274 /// the instruction to the preheader.
275 bool EliminateCSE(MachineInstr *MI,
276 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
277
Evan Cheng7efba852011-10-12 00:09:14 +0000278 /// MayCSE - Return true if the given instruction will be CSE'd if it's
279 /// hoisted out of the loop.
280 bool MayCSE(MachineInstr *MI);
281
Bill Wendling0f940c92007-12-07 21:42:31 +0000282 /// Hoist - When an instruction is found to only use loop invariant operands
283 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000284 /// It returns true if the instruction is hoisted.
285 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000286
287 /// InitCSEMap - Initialize the CSE map with instructions that are in the
288 /// current loop preheader that may become duplicates of instructions that
289 /// are hoisted out of the loop.
290 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000291
292 /// getCurPreheader - Get the preheader for the current loop, splitting
293 /// a critical edge if needed.
294 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000295 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000296} // end anonymous namespace
297
Dan Gohman844731a2008-05-13 00:00:25 +0000298char MachineLICM::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000299char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000300INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
301 "Machine Loop Invariant Code Motion", false, false)
302INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
303INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
304INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
305INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000306 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000307
Dan Gohman853d3fb2010-06-22 17:25:57 +0000308/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
309/// loop that has a unique predecessor.
310static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000311 // Check whether this loop even has a unique predecessor.
312 if (!CurLoop->getLoopPredecessor())
313 return false;
314 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000315 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000316 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000317 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000318 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000319 return true;
320}
321
Bill Wendling0f940c92007-12-07 21:42:31 +0000322bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Stephen Hines36b56882014-04-23 16:57:46 -0700323 if (skipOptnoneFunction(*MF.getFunction()))
324 return false;
325
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000326 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000327 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000328 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000329 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000330 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000331 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000332 MRI = &MF.getRegInfo();
333 InstrItins = TM->getInstrItineraryData();
Bill Wendling0f940c92007-12-07 21:42:31 +0000334
Andrew Trick9d41bd52012-02-08 21:23:03 +0000335 PreRegAlloc = MRI->isSSA();
336
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000337 if (PreRegAlloc)
338 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
339 else
340 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Topper96601ca2012-08-22 06:07:19 +0000341 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000342
Evan Cheng0e673912010-10-14 01:16:09 +0000343 if (PreRegAlloc) {
344 // Estimate register pressure during pre-regalloc pass.
345 unsigned NumRC = TRI->getNumRegClasses();
346 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000347 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000348 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000349 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
350 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000351 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000352 }
353
Bill Wendling0f940c92007-12-07 21:42:31 +0000354 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000355 MLI = &getAnalysis<MachineLoopInfo>();
356 DT = &getAnalysis<MachineDominatorTree>();
357 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000358
Dan Gohmanaa742602010-07-09 18:49:45 +0000359 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
360 while (!Worklist.empty()) {
361 CurLoop = Worklist.pop_back_val();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700362 CurPreheader = nullptr;
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000363 ExitBlocks.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000364
Evan Cheng4038f9c2010-04-08 01:03:47 +0000365 // If this is done before regalloc, only visit outer-most preheader-sporting
366 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000367 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
368 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000369 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000370 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000371
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000372 CurLoop->getExitBlocks(ExitBlocks);
373
Evan Chengd94671a2010-04-07 00:41:17 +0000374 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000375 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000376 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000377 // CSEMap is initialized for loop header when the first instruction is
378 // being hoisted.
379 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000380 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000381 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000382 CSEMap.clear();
383 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000384 }
385
386 return Changed;
387}
388
Evan Cheng4038f9c2010-04-08 01:03:47 +0000389/// InstructionStoresToFI - Return true if instruction stores to the
390/// specified frame.
391static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
392 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
393 oe = MI->memoperands_end(); o != oe; ++o) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700394 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng4038f9c2010-04-08 01:03:47 +0000395 continue;
396 if (const FixedStackPseudoSourceValue *Value =
Stephen Hinesdce4a402014-05-29 02:49:00 -0700397 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000398 if (Value->getFrameIndex() == FI)
399 return true;
400 }
401 }
402 return false;
403}
404
405/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
406/// gather register def and frame object update information.
407void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000408 BitVector &PhysRegDefs,
409 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000410 SmallSet<int, 32> &StoredFIs,
Craig Topper9e639e82013-07-11 16:22:38 +0000411 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000412 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000413 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000414 unsigned Def = 0;
415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
416 const MachineOperand &MO = MI->getOperand(i);
417 if (MO.isFI()) {
418 // Remember if the instruction stores to the frame index.
419 int FI = MO.getIndex();
420 if (!StoredFIs.count(FI) &&
421 MFI->isSpillSlotObjectIndex(FI) &&
422 InstructionStoresToFI(MI, FI))
423 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000424 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000425 continue;
426 }
427
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000428 // We can't hoist an instruction defining a physreg that is clobbered in
429 // the loop.
430 if (MO.isRegMask()) {
Jakob Stoklund Olesen478a8a02012-02-02 23:52:57 +0000431 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000432 continue;
433 }
434
Evan Cheng4038f9c2010-04-08 01:03:47 +0000435 if (!MO.isReg())
436 continue;
437 unsigned Reg = MO.getReg();
438 if (!Reg)
439 continue;
440 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
441 "Not expecting virtual register!");
442
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000443 if (!MO.isDef()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000444 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000445 // If it's using a non-loop-invariant register, then it's obviously not
446 // safe to hoist.
447 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000448 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000449 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000450
451 if (MO.isImplicit()) {
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000452 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
453 PhysRegClobbers.set(*AI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000454 if (!MO.isDead())
455 // Non-dead implicit def? This cannot be hoisted.
456 RuledOut = true;
457 // No need to check if a dead implicit def is also defined by
458 // another instruction.
459 continue;
460 }
461
462 // FIXME: For now, avoid instructions with multiple defs, unless
463 // it's a dead implicit def.
464 if (Def)
465 RuledOut = true;
466 else
467 Def = Reg;
468
469 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000470 // register, then this is not safe. Two defs is indicated by setting a
471 // PhysRegClobbers bit.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000472 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000473 if (PhysRegDefs.test(*AS))
474 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000475 PhysRegDefs.set(*AS);
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000476 }
Richard Sandiford9608ed12013-08-20 09:11:13 +0000477 if (PhysRegClobbers.test(Reg))
478 // MI defined register is seen defined by another instruction in
479 // the loop, it cannot be a LICM candidate.
480 RuledOut = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000481 }
482
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000483 // Only consider reloads for now and remats which do not have register
484 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000485 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000486 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000487 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000488 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
489 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000490 }
491}
492
493/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
494/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000495void MachineLICM::HoistRegionPostRA() {
Evan Chengd6c23552012-03-27 01:50:58 +0000496 MachineBasicBlock *Preheader = getCurPreheader();
497 if (!Preheader)
498 return;
499
Evan Chengd94671a2010-04-07 00:41:17 +0000500 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000501 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
502 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Chengd94671a2010-04-07 00:41:17 +0000503
Evan Cheng4038f9c2010-04-08 01:03:47 +0000504 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000505 SmallSet<int, 32> StoredFIs;
506
507 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000508 // collect potential LICM candidates.
Benjamin Kramer94ee55d2013-09-15 22:04:42 +0000509 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000510 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
511 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000512
513 // If the header of the loop containing this basic block is a landing pad,
514 // then don't try to hoist instructions out of this loop.
515 const MachineLoop *ML = MLI->getLoopFor(BB);
516 if (ML && ML->getHeader()->isLandingPad()) continue;
517
Evan Chengd94671a2010-04-07 00:41:17 +0000518 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000519 // FIXME: That means a reload that're reused in successor block(s) will not
520 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000521 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000522 E = BB->livein_end(); I != E; ++I) {
523 unsigned Reg = *I;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000524 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
525 PhysRegDefs.set(*AI);
Evan Chengd94671a2010-04-07 00:41:17 +0000526 }
527
Evan Chengfad62872011-10-11 23:48:44 +0000528 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000529 for (MachineBasicBlock::iterator
530 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000531 MachineInstr *MI = &*MII;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000532 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000533 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000534 }
Evan Chengd94671a2010-04-07 00:41:17 +0000535
Evan Chengd6c23552012-03-27 01:50:58 +0000536 // Gather the registers read / clobbered by the terminator.
537 BitVector TermRegs(NumRegs);
538 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
539 if (TI != Preheader->end()) {
540 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
541 const MachineOperand &MO = TI->getOperand(i);
542 if (!MO.isReg())
543 continue;
544 unsigned Reg = MO.getReg();
545 if (!Reg)
546 continue;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000547 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
548 TermRegs.set(*AI);
Evan Chengd6c23552012-03-27 01:50:58 +0000549 }
550 }
551
Evan Chengd94671a2010-04-07 00:41:17 +0000552 // Now evaluate whether the potential candidates qualify.
553 // 1. Check if the candidate defined register is defined by another
554 // instruction in the loop.
555 // 2. If the candidate is a load from stack slot (always true for now),
556 // check if the slot is stored anywhere in the loop.
Evan Chengd6c23552012-03-27 01:50:58 +0000557 // 3. Make sure candidate def should not clobber
558 // registers read by the terminator. Similarly its def should not be
559 // clobbered by the terminator.
Evan Chengd94671a2010-04-07 00:41:17 +0000560 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000561 if (Candidates[i].FI != INT_MIN &&
562 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000563 continue;
564
Evan Chengd6c23552012-03-27 01:50:58 +0000565 unsigned Def = Candidates[i].Def;
566 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000567 bool Safe = true;
568 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000569 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
570 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000571 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000572 continue;
Evan Chengd6c23552012-03-27 01:50:58 +0000573 unsigned Reg = MO.getReg();
574 if (PhysRegDefs.test(Reg) ||
575 PhysRegClobbers.test(Reg)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000576 // If it's using a non-loop-invariant register, then it's obviously
577 // not safe to hoist.
578 Safe = false;
579 break;
580 }
581 }
582 if (Safe)
583 HoistPostRA(MI, Candidates[i].Def);
584 }
Evan Chengd94671a2010-04-07 00:41:17 +0000585 }
586}
587
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000588/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
589/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000590void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer94ee55d2013-09-15 22:04:42 +0000591 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000592 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
593 MachineBasicBlock *BB = Blocks[i];
594 if (!BB->isLiveIn(Reg))
595 BB->addLiveIn(Reg);
596 for (MachineBasicBlock::iterator
597 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
598 MachineInstr *MI = &*MII;
599 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
600 MachineOperand &MO = MI->getOperand(i);
601 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
602 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
603 MO.setIsKill(false);
604 }
605 }
606 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000607}
608
609/// HoistPostRA - When an instruction is found to only use loop invariant
610/// operands that is safe to hoist, this instruction is called to do the
611/// dirty work.
612void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000613 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000614
Evan Chengd94671a2010-04-07 00:41:17 +0000615 // Now move the instructions to the predecessor, inserting it before any
616 // terminator instructions.
Jakob Stoklund Olesen39f66602012-01-23 21:01:11 +0000617 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
618 << MI->getParent()->getNumber() << ": " << *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000619
620 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000621 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000622 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000623
Andrew Trick9f17cf62012-02-08 21:23:00 +0000624 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000625 // loop invariant must be kept live throughout the whole loop. This is
626 // important to ensure later passes do not scavenge the def register.
627 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000628
629 ++NumPostRAHoisted;
630 Changed = true;
631}
632
Devang Patel2e350472011-10-11 18:09:58 +0000633// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
634// If not then a load from this mbb may not be safe to hoist.
635bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000636 if (SpeculationState != SpeculateUnknown)
637 return SpeculationState == SpeculateFalse;
Andrew Trick9f17cf62012-02-08 21:23:00 +0000638
Devang Patel2e350472011-10-11 18:09:58 +0000639 if (BB != CurLoop->getHeader()) {
640 // Check loop exiting blocks.
641 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
642 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
643 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
644 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000645 SpeculationState = SpeculateTrue;
646 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000647 }
648 }
649
Evan Chengfad62872011-10-11 23:48:44 +0000650 SpeculationState = SpeculateFalse;
651 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000652}
653
Pete Cooperacde91e2011-12-22 02:05:40 +0000654void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
655 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000656
Pete Cooperacde91e2011-12-22 02:05:40 +0000657 // Remember livein register pressure.
658 BackTrace.push_back(RegPressure);
659}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000660
Pete Cooperacde91e2011-12-22 02:05:40 +0000661void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
662 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
663 BackTrace.pop_back();
664}
Bill Wendling0f940c92007-12-07 21:42:31 +0000665
Pete Cooperacde91e2011-12-22 02:05:40 +0000666/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
667/// dominator tree node if its a leaf or all of its children are done. Walk
668/// up the dominator tree to destroy ancestors which are now done.
669void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Cheng75fda5d2012-01-10 22:27:32 +0000670 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
671 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000672 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000673 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000674
Pete Cooperacde91e2011-12-22 02:05:40 +0000675 // Pop scope.
676 ExitScope(Node->getBlock());
677
678 // Now traverse upwards to pop ancestors whose offsprings are all done.
679 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
680 unsigned Left = --OpenChildren[Parent];
681 if (Left != 0)
682 break;
683 ExitScope(Parent->getBlock());
684 Node = Parent;
685 }
686}
687
688/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
689/// blocks dominated by the specified header block, and that are in the
690/// current loop) in depth first order w.r.t the DominatorTree. This allows
691/// us to visit definitions before uses, allowing us to hoist a loop body in
692/// one pass without iteration.
693///
694void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
695 SmallVector<MachineDomTreeNode*, 32> Scopes;
696 SmallVector<MachineDomTreeNode*, 8> WorkList;
697 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
698 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
699
700 // Perform a DFS walk to determine the order of visit.
701 WorkList.push_back(HeaderN);
702 do {
703 MachineDomTreeNode *Node = WorkList.pop_back_val();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700704 assert(Node && "Null dominator tree node?");
Pete Cooperacde91e2011-12-22 02:05:40 +0000705 MachineBasicBlock *BB = Node->getBlock();
706
707 // If the header of the loop containing this basic block is a landing pad,
708 // then don't try to hoist instructions out of this loop.
709 const MachineLoop *ML = MLI->getLoopFor(BB);
710 if (ML && ML->getHeader()->isLandingPad())
711 continue;
712
713 // If this subregion is not in the top level loop at all, exit.
714 if (!CurLoop->contains(BB))
715 continue;
716
717 Scopes.push_back(Node);
718 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
719 unsigned NumChildren = Children.size();
720
721 // Don't hoist things out of a large switch statement. This often causes
722 // code to be hoisted that wasn't going to be executed, and increases
723 // register pressure in a situation where it's likely to matter.
724 if (BB->succ_size() >= 25)
725 NumChildren = 0;
726
727 OpenChildren[Node] = NumChildren;
728 // Add children in reverse order as then the next popped worklist node is
729 // the first child of this node. This means we ultimately traverse the
730 // DOM tree in exactly the same order as if we'd recursed.
731 for (int i = (int)NumChildren-1; i >= 0; --i) {
732 MachineDomTreeNode *Child = Children[i];
733 ParentMap[Child] = Node;
734 WorkList.push_back(Child);
735 }
736 } while (!WorkList.empty());
737
738 if (Scopes.size() != 0) {
739 MachineBasicBlock *Preheader = getCurPreheader();
740 if (!Preheader)
741 return;
742
Evan Cheng134982d2010-10-20 22:03:58 +0000743 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000744 RegSeen.clear();
745 BackTrace.clear();
746 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000747 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000748
Pete Cooperacde91e2011-12-22 02:05:40 +0000749 // Now perform LICM.
750 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
751 MachineDomTreeNode *Node = Scopes[i];
752 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000753
Pete Cooperacde91e2011-12-22 02:05:40 +0000754 MachineBasicBlock *Preheader = getCurPreheader();
755 if (!Preheader)
756 continue;
757
758 EnterScope(MBB);
759
760 // Process the block
761 SpeculationState = SpeculateUnknown;
762 for (MachineBasicBlock::iterator
763 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
764 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
765 MachineInstr *MI = &*MII;
766 if (!Hoist(MI, Preheader))
767 UpdateRegPressure(MI);
768 MII = NextMII;
769 }
770
771 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
772 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000773 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000774}
775
Evan Cheng134982d2010-10-20 22:03:58 +0000776static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
777 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
778}
779
Evan Cheng61560e22011-09-01 01:45:00 +0000780/// getRegisterClassIDAndCost - For a given MI, register, and the operand
781/// index, return the ID and cost of its representative register class.
782void
783MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
784 unsigned Reg, unsigned OpIdx,
785 unsigned &RCId, unsigned &RCCost) const {
786 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Patrik Hagglund860e7cd2012-12-13 18:45:35 +0000787 MVT VT = *RC->vt_begin();
Owen Anderson99aa14f2011-11-16 01:02:57 +0000788 if (VT == MVT::Untyped) {
Evan Cheng61560e22011-09-01 01:45:00 +0000789 RCId = RC->getID();
790 RCCost = 1;
791 } else {
792 RCId = TLI->getRepRegClassFor(VT)->getID();
793 RCCost = TLI->getRepRegClassCostFor(VT);
794 }
795}
Andrew Trick9f17cf62012-02-08 21:23:00 +0000796
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000797/// InitRegPressure - Find all virtual register references that are liveout of
798/// the preheader to initialize the starting "register pressure". Note this
799/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000800void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000801 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000802
Evan Cheng134982d2010-10-20 22:03:58 +0000803 // If the preheader has only a single predecessor and it ends with a
804 // fallthrough or an unconditional branch, then scan its predecessor for live
805 // defs as well. This happens whenever the preheader is created by splitting
806 // the critical edge from the loop predecessor to the loop header.
807 if (BB->pred_size() == 1) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700808 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng134982d2010-10-20 22:03:58 +0000809 SmallVector<MachineOperand, 4> Cond;
810 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
811 InitRegPressure(*BB->pred_begin());
812 }
813
Evan Cheng0e673912010-10-14 01:16:09 +0000814 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
815 MII != E; ++MII) {
816 MachineInstr *MI = &*MII;
817 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
818 const MachineOperand &MO = MI->getOperand(i);
819 if (!MO.isReg() || MO.isImplicit())
820 continue;
821 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000822 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000823 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000824
Andrew Trickdc986d22010-10-19 02:50:50 +0000825 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000826 unsigned RCId, RCCost;
827 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000828 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000829 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000830 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000831 bool isKill = isOperandKill(MO, MRI);
832 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000833 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000834 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000835 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000836 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000837 }
Evan Cheng0e673912010-10-14 01:16:09 +0000838 }
839 }
840}
841
Evan Cheng134982d2010-10-20 22:03:58 +0000842/// UpdateRegPressure - Update estimate of register pressure after the
843/// specified instruction.
844void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
845 if (MI->isImplicitDef())
846 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000847
Evan Cheng134982d2010-10-20 22:03:58 +0000848 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000849 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
850 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000851 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000852 continue;
853 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000854 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000855 continue;
856
Andrew Trickdc986d22010-10-19 02:50:50 +0000857 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000858 if (MO.isDef())
859 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000860 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000861 unsigned RCId, RCCost;
862 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000863 if (RCCost > RegPressure[RCId])
864 RegPressure[RCId] = 0;
865 else
Evan Cheng23128422010-10-19 18:58:51 +0000866 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000867 }
Evan Cheng0e673912010-10-14 01:16:09 +0000868 }
Evan Cheng0e673912010-10-14 01:16:09 +0000869
Evan Cheng61560e22011-09-01 01:45:00 +0000870 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000871 while (!Defs.empty()) {
872 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000873 unsigned RCId, RCCost;
874 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000875 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000876 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000877 }
878}
879
Andrew Trick9f17cf62012-02-08 21:23:00 +0000880/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel06e16bb2011-10-20 17:42:23 +0000881/// loads from global offset table or constant pool.
882static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000883 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel6c15fec2011-10-17 17:35:01 +0000884 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick9f17cf62012-02-08 21:23:00 +0000885 E = MI.memoperands_end(); I != E; ++I) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700886 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
887 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
888 return true;
Devang Patel6c15fec2011-10-17 17:35:01 +0000889 }
890 }
891 return false;
892}
893
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000894/// IsLICMCandidate - Returns true if the instruction may be a suitable
895/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
896/// not safe to hoist it.
897bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000898 // Check if it's safe to move the instruction.
899 bool DontMoveAcrossStore = true;
900 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000901 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000902
903 // If it is load then check if it is guaranteed to execute by making sure that
904 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000905 // the loop which does not execute this load, so we can't hoist it. Loads
906 // from constant memory are not safe to speculate all the time, for example
907 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000908 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000909 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000910 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000911 return false;
912
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000913 return true;
914}
915
916/// IsLoopInvariantInst - Returns true if the instruction is loop
917/// invariant. I.e., all virtual register operands are defined outside of the
918/// loop, physical registers aren't accessed explicitly, and there are no side
919/// effects that aren't captured by the operands or other flags.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000920///
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000921bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
922 if (!IsLICMCandidate(I))
923 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000924
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000925 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000926 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
927 const MachineOperand &MO = I.getOperand(i);
928
Dan Gohmand735b802008-10-03 15:45:36 +0000929 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000930 continue;
931
Dan Gohmanc475c362009-01-15 22:01:38 +0000932 unsigned Reg = MO.getReg();
933 if (Reg == 0) continue;
934
935 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000936 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000937 if (MO.isUse()) {
938 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000939 // and we can freely move its uses. Alternatively, if it's allocatable,
940 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000941 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000942 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000943 // Otherwise it's safe to move.
944 continue;
945 } else if (!MO.isDead()) {
946 // A def that isn't dead. We can't move it.
947 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000948 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
949 // If the reg is live into the loop, we can't hoist an instruction
950 // which would clobber it.
951 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000952 }
953 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000954
955 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000956 continue;
957
Evan Cheng0e673912010-10-14 01:16:09 +0000958 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000959 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000960
961 // If the loop contains the definition of an operand, then the instruction
962 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000963 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000964 return false;
965 }
966
967 // If we got this far, the instruction is loop invariant!
968 return true;
969}
970
Evan Chengaf6949d2009-02-05 08:45:46 +0000971
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000972/// HasLoopPHIUse - Return true if the specified instruction is used by a
973/// phi node and hoisting it could cause a copy to be inserted.
974bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
975 SmallVector<const MachineInstr*, 8> Work(1, MI);
976 do {
977 MI = Work.pop_back_val();
978 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
979 if (!MO->isReg() || !MO->isDef())
980 continue;
981 unsigned Reg = MO->getReg();
982 if (!TargetRegisterInfo::isVirtualRegister(Reg))
983 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700984 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000985 // A PHI may cause a copy to be inserted.
Stephen Hines36b56882014-04-23 16:57:46 -0700986 if (UseMI.isPHI()) {
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000987 // A PHI inside the loop causes a copy because the live range of Reg is
988 // extended across the PHI.
Stephen Hines36b56882014-04-23 16:57:46 -0700989 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000990 return true;
991 // A PHI in an exit block can cause a copy to be inserted if the PHI
992 // has multiple predecessors in the loop with different values.
993 // For now, approximate by rejecting all exit blocks.
Stephen Hines36b56882014-04-23 16:57:46 -0700994 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000995 return true;
996 continue;
997 }
998 // Look past copies as well.
Stephen Hines36b56882014-04-23 16:57:46 -0700999 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1000 Work.push_back(&UseMI);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001001 }
Evan Chengd67705f2011-04-11 21:09:18 +00001002 }
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001003 } while (!Work.empty());
Evan Chengaf6949d2009-02-05 08:45:46 +00001004 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001005}
1006
Evan Cheng23128422010-10-19 18:58:51 +00001007/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1008/// and an use in the current loop, return true if the target considered
1009/// it 'high'.
1010bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +00001011 unsigned DefIdx, unsigned Reg) const {
1012 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +00001013 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001014
Stephen Hines36b56882014-04-23 16:57:46 -07001015 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1016 if (UseMI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001017 continue;
Stephen Hines36b56882014-04-23 16:57:46 -07001018 if (!CurLoop->contains(UseMI.getParent()))
Evan Cheng0e673912010-10-14 01:16:09 +00001019 continue;
Stephen Hines36b56882014-04-23 16:57:46 -07001020 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1021 const MachineOperand &MO = UseMI.getOperand(i);
Evan Cheng0e673912010-10-14 01:16:09 +00001022 if (!MO.isReg() || !MO.isUse())
1023 continue;
1024 unsigned MOReg = MO.getReg();
1025 if (MOReg != Reg)
1026 continue;
1027
Stephen Hines36b56882014-04-23 16:57:46 -07001028 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng23128422010-10-19 18:58:51 +00001029 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001030 }
1031
Evan Cheng23128422010-10-19 18:58:51 +00001032 // Only look at the first in loop use.
1033 break;
Evan Cheng0e673912010-10-14 01:16:09 +00001034 }
1035
Evan Cheng23128422010-10-19 18:58:51 +00001036 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001037}
1038
Evan Chengc8141df2010-10-26 02:08:50 +00001039/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1040/// the operand latency between its def and a use is one or less.
1041bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001042 if (MI.isAsCheapAsAMove() || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001043 return true;
1044 if (!InstrItins || InstrItins->isEmpty())
1045 return false;
1046
1047 bool isCheap = false;
1048 unsigned NumDefs = MI.getDesc().getNumDefs();
1049 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1050 MachineOperand &DefMO = MI.getOperand(i);
1051 if (!DefMO.isReg() || !DefMO.isDef())
1052 continue;
1053 --NumDefs;
1054 unsigned Reg = DefMO.getReg();
1055 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1056 continue;
1057
1058 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1059 return false;
1060 isCheap = true;
1061 }
1062
1063 return isCheap;
1064}
1065
Evan Cheng134982d2010-10-20 22:03:58 +00001066/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001067/// if hoisting an instruction of the given cost matrix can cause high
1068/// register pressure.
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001069bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1070 bool CheapInstr) {
Evan Cheng134982d2010-10-20 22:03:58 +00001071 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1072 CI != CE; ++CI) {
Andrew Trick9f17cf62012-02-08 21:23:00 +00001073 if (CI->second <= 0)
Evan Cheng134982d2010-10-20 22:03:58 +00001074 continue;
1075
1076 unsigned RCId = CI->first;
Pete Cooper3cfecf52011-12-22 02:13:25 +00001077 unsigned Limit = RegLimit[RCId];
1078 int Cost = CI->second;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001079
1080 // Don't hoist cheap instructions if they would increase register pressure,
1081 // even if we're under the limit.
1082 if (CheapInstr)
1083 return true;
1084
Evan Cheng134982d2010-10-20 22:03:58 +00001085 for (unsigned i = BackTrace.size(); i != 0; --i) {
Craig Topper9e639e82013-07-11 16:22:38 +00001086 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
Pete Cooper3cfecf52011-12-22 02:13:25 +00001087 if (RP[RCId] + Cost >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001088 return true;
1089 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001090 }
1091
1092 return false;
1093}
1094
Evan Cheng134982d2010-10-20 22:03:58 +00001095/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1096/// current block and update their register pressures to reflect the effect
1097/// of hoisting MI from the current block to the preheader.
1098void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1099 if (MI->isImplicitDef())
1100 return;
1101
1102 // First compute the 'cost' of the instruction, i.e. its contribution
1103 // to register pressure.
1104 DenseMap<unsigned, int> Cost;
1105 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1106 const MachineOperand &MO = MI->getOperand(i);
1107 if (!MO.isReg() || MO.isImplicit())
1108 continue;
1109 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001110 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +00001111 continue;
1112
Evan Cheng61560e22011-09-01 01:45:00 +00001113 unsigned RCId, RCCost;
1114 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +00001115 if (MO.isDef()) {
1116 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1117 if (CI != Cost.end())
1118 CI->second += RCCost;
1119 else
1120 Cost.insert(std::make_pair(RCId, RCCost));
1121 } else if (isOperandKill(MO, MRI)) {
1122 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1123 if (CI != Cost.end())
1124 CI->second -= RCCost;
1125 else
1126 Cost.insert(std::make_pair(RCId, -RCCost));
1127 }
1128 }
1129
1130 // Update register pressure of blocks from loop header to current block.
1131 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
Craig Topper9e639e82013-07-11 16:22:38 +00001132 SmallVectorImpl<unsigned> &RP = BackTrace[i];
Evan Cheng134982d2010-10-20 22:03:58 +00001133 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1134 CI != CE; ++CI) {
1135 unsigned RCId = CI->first;
1136 RP[RCId] += CI->second;
1137 }
1138 }
1139}
1140
Evan Cheng45e94d62009-02-04 09:19:56 +00001141/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1142/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +00001143bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001144 if (MI.isImplicitDef())
1145 return true;
1146
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001147 // Besides removing computation from the loop, hoisting an instruction has
1148 // these effects:
1149 //
1150 // - The value defined by the instruction becomes live across the entire
1151 // loop. This increases register pressure in the loop.
1152 //
1153 // - If the value is used by a PHI in the loop, a copy will be required for
1154 // lowering the PHI after extending the live range.
1155 //
1156 // - When hoisting the last use of a value in the loop, that value no longer
1157 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng61560e22011-09-01 01:45:00 +00001158
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001159 bool CheapInstr = IsCheapInstruction(MI);
1160 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001161
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001162 // Don't hoist a cheap instruction if it would create a copy in the loop.
1163 if (CheapInstr && CreatesCopy) {
1164 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1165 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001166 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001167
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001168 // Rematerializable instructions should always be hoisted since the register
1169 // allocator can just pull them down again when needed.
1170 if (TII->isTriviallyReMaterializable(&MI, AA))
1171 return true;
1172
1173 // Estimate register pressure to determine whether to LICM the instruction.
1174 // In low register pressure situation, we can be more aggressive about
1175 // hoisting. Also, favors hoisting long latency instructions even in
1176 // moderately high pressure situation.
1177 // Cheap instructions will only be hoisted if they don't increase register
1178 // pressure at all.
1179 // FIXME: If there are long latency loop-invariant instructions inside the
1180 // loop at this point, why didn't the optimizer's LICM hoist them?
1181 DenseMap<unsigned, int> Cost;
1182 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1183 const MachineOperand &MO = MI.getOperand(i);
1184 if (!MO.isReg() || MO.isImplicit())
1185 continue;
1186 unsigned Reg = MO.getReg();
1187 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1188 continue;
1189
1190 unsigned RCId, RCCost;
1191 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1192 if (MO.isDef()) {
1193 if (HasHighOperandLatency(MI, i, Reg)) {
1194 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1195 ++NumHighLatency;
1196 return true;
1197 }
1198 Cost[RCId] += RCCost;
1199 } else if (isOperandKill(MO, MRI)) {
1200 // Is a virtual register use is a kill, hoisting it out of the loop
1201 // may actually reduce register pressure or be register pressure
1202 // neutral.
1203 Cost[RCId] -= RCCost;
1204 }
1205 }
1206
1207 // Visit BBs from header to current BB, if hoisting this doesn't cause
1208 // high register pressure, then it's safe to proceed.
1209 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1210 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1211 ++NumLowRP;
1212 return true;
1213 }
1214
1215 // Don't risk increasing register pressure if it would create copies.
1216 if (CreatesCopy) {
1217 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001218 return false;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001219 }
1220
1221 // Do not "speculate" in high register pressure situation. If an
1222 // instruction is not guaranteed to be executed in the loop, it's best to be
1223 // conservative.
1224 if (AvoidSpeculation &&
1225 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1226 DEBUG(dbgs() << "Won't speculate: " << MI);
1227 return false;
1228 }
1229
1230 // High register pressure situation, only hoist if the instruction is going
1231 // to be remat'ed.
1232 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1233 !MI.isInvariantLoad(AA)) {
1234 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1235 return false;
1236 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001237
1238 return true;
1239}
1240
Dan Gohman5c952302009-10-29 17:47:20 +00001241MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001242 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001243 if (MI->canFoldAsLoad())
Stephen Hinesdce4a402014-05-29 02:49:00 -07001244 return nullptr;
Evan Chenge95f3192010-10-08 18:59:19 +00001245
Dan Gohman5c952302009-10-29 17:47:20 +00001246 // If not, we may be able to unfold a load and hoist that.
1247 // First test whether the instruction is loading from an amenable
1248 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001249 if (!MI->isInvariantLoad(AA))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001250 return nullptr;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001251
Dan Gohman5c952302009-10-29 17:47:20 +00001252 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001253 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001254 unsigned NewOpc =
1255 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1256 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001257 /*UnfoldStore=*/false,
1258 &LoadRegIndex);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001259 if (NewOpc == 0) return nullptr;
Evan Chenge837dea2011-06-28 19:10:37 +00001260 const MCInstrDesc &MID = TII->get(NewOpc);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001261 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +00001262 MachineFunction &MF = *MI->getParent()->getParent();
1263 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman5c952302009-10-29 17:47:20 +00001264 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001265 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001266
Dan Gohman5c952302009-10-29 17:47:20 +00001267 SmallVector<MachineInstr *, 2> NewMIs;
1268 bool Success =
1269 TII->unfoldMemoryOperand(MF, MI, Reg,
1270 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1271 NewMIs);
1272 (void)Success;
1273 assert(Success &&
1274 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1275 "succeeded!");
1276 assert(NewMIs.size() == 2 &&
1277 "Unfolded a load into multiple instructions!");
1278 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001279 MachineBasicBlock::iterator Pos = MI;
1280 MBB->insert(Pos, NewMIs[0]);
1281 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001282 // If unfolding produced a load that wasn't loop-invariant or profitable to
1283 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001284 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001285 NewMIs[0]->eraseFromParent();
1286 NewMIs[1]->eraseFromParent();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001287 return nullptr;
Dan Gohman5c952302009-10-29 17:47:20 +00001288 }
Evan Cheng134982d2010-10-20 22:03:58 +00001289
1290 // Update register pressure for the unfolded instruction.
1291 UpdateRegPressure(NewMIs[1]);
1292
Dan Gohman5c952302009-10-29 17:47:20 +00001293 // Otherwise we successfully unfolded a load that we can hoist.
1294 MI->eraseFromParent();
1295 return NewMIs[0];
1296}
1297
Evan Cheng777c6b72009-11-03 21:40:02 +00001298void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1299 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1300 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001301 unsigned Opcode = MI->getOpcode();
1302 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1303 CI = CSEMap.find(Opcode);
1304 if (CI != CSEMap.end())
1305 CI->second.push_back(MI);
1306 else {
1307 std::vector<const MachineInstr*> CSEMIs;
1308 CSEMIs.push_back(MI);
1309 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001310 }
1311 }
1312}
1313
Evan Cheng78e5c112009-11-07 03:52:02 +00001314const MachineInstr*
1315MachineLICM::LookForDuplicate(const MachineInstr *MI,
1316 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001317 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1318 const MachineInstr *PrevMI = PrevMIs[i];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001319 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001320 return PrevMI;
1321 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001322 return nullptr;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001323}
1324
1325bool MachineLICM::EliminateCSE(MachineInstr *MI,
1326 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001327 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1328 // the undef property onto uses.
1329 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001330 return false;
1331
1332 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001333 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001334
1335 // Replace virtual registers defined by MI by their counterparts defined
1336 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001337 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001338 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1339 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001340
1341 // Physical registers may not differ here.
1342 assert((!MO.isReg() || MO.getReg() == 0 ||
1343 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1344 MO.getReg() == Dup->getOperand(i).getReg()) &&
1345 "Instructions with different phys regs are not identical!");
1346
1347 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001348 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1349 Defs.push_back(i);
1350 }
1351
1352 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1353 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1354 unsigned Idx = Defs[i];
1355 unsigned Reg = MI->getOperand(Idx).getReg();
1356 unsigned DupReg = Dup->getOperand(Idx).getReg();
1357 OrigRCs.push_back(MRI->getRegClass(DupReg));
1358
1359 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1360 // Restore old RCs if more than one defs.
1361 for (unsigned j = 0; j != i; ++j)
1362 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1363 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001364 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001365 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001366
1367 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1368 unsigned Idx = Defs[i];
1369 unsigned Reg = MI->getOperand(Idx).getReg();
1370 unsigned DupReg = Dup->getOperand(Idx).getReg();
1371 MRI->replaceRegWith(Reg, DupReg);
1372 MRI->clearKillFlags(DupReg);
1373 }
1374
Evan Cheng78e5c112009-11-07 03:52:02 +00001375 MI->eraseFromParent();
1376 ++NumCSEed;
1377 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001378 }
1379 return false;
1380}
1381
Evan Cheng7efba852011-10-12 00:09:14 +00001382/// MayCSE - Return true if the given instruction will be CSE'd if it's
1383/// hoisted out of the loop.
1384bool MachineLICM::MayCSE(MachineInstr *MI) {
1385 unsigned Opcode = MI->getOpcode();
1386 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1387 CI = CSEMap.find(Opcode);
1388 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1389 // the undef property onto uses.
1390 if (CI == CSEMap.end() || MI->isImplicitDef())
1391 return false;
1392
Stephen Hinesdce4a402014-05-29 02:49:00 -07001393 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Cheng7efba852011-10-12 00:09:14 +00001394}
1395
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001396/// Hoist - When an instruction is found to use only loop invariant operands
1397/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001398///
Evan Cheng134982d2010-10-20 22:03:58 +00001399bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001400 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001401 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001402 // If not, try unfolding a hoistable load.
1403 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001404 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001405 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001406
Dan Gohmanc475c362009-01-15 22:01:38 +00001407 // Now move the instructions to the predecessor, inserting it before any
1408 // terminator instructions.
1409 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001410 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001411 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001412 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001413 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001414 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001415 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001416 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001417 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001418 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001419
Evan Cheng777c6b72009-11-03 21:40:02 +00001420 // If this is the first instruction being hoisted to the preheader,
1421 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001422 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001423 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001424 FirstInLoop = false;
1425 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001426
Evan Chengaf6949d2009-02-05 08:45:46 +00001427 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001428 unsigned Opcode = MI->getOpcode();
1429 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1430 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001431 if (!EliminateCSE(MI, CI)) {
1432 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001433 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001434
Evan Cheng134982d2010-10-20 22:03:58 +00001435 // Update register pressure for BBs from header to this block.
1436 UpdateBackTraceRegPressure(MI);
1437
Dan Gohmane6cd7572010-05-13 20:34:42 +00001438 // Clear the kill flags of any register this instruction defines,
1439 // since they may need to be live throughout the entire loop
1440 // rather than just live for part of it.
1441 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1442 MachineOperand &MO = MI->getOperand(i);
1443 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001444 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001445 }
1446
Evan Chengaf6949d2009-02-05 08:45:46 +00001447 // Add to the CSE map.
1448 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001449 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001450 else {
1451 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001452 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001453 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001454 }
1455 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001456
Dan Gohmanc475c362009-01-15 22:01:38 +00001457 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001458 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001459
1460 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001461}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001462
1463MachineBasicBlock *MachineLICM::getCurPreheader() {
1464 // Determine the block to which to hoist instructions. If we can't find a
1465 // suitable loop predecessor, we can't do any hoisting.
1466
1467 // If we've tried to get a preheader and failed, don't try again.
1468 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001469 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001470
1471 if (!CurPreheader) {
1472 CurPreheader = CurLoop->getLoopPreheader();
1473 if (!CurPreheader) {
1474 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1475 if (!Pred) {
1476 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001477 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001478 }
1479
1480 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1481 if (!CurPreheader) {
1482 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001483 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001484 }
1485 }
1486 }
1487 return CurPreheader;
1488}