blob: a8368e9c80d6fbfc144b08d0c7bda82176e18bad [file] [log] [blame]
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohman79618d12009-01-15 22:01:38 +000013// This pass is not intended to be a replacement or a complete alternative
14// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15// constructs that are not exposed before lowering and instruction selection.
16//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000017//===----------------------------------------------------------------------===//
18
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000019#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000024#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000027#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Matthias Braun88e21312015-06-13 03:42:11 +000030#include "llvm/CodeGen/TargetSchedule.h"
Evan Chengb35afca2011-10-12 21:33:49 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000032#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "machine-licm"
42
Evan Chengb35afca2011-10-12 21:33:49 +000043static cl::opt<bool>
44AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000046 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000047
Hal Finkel0709f512015-01-08 22:10:48 +000048static cl::opt<bool>
49HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
52
Daniel Jasper15e69542015-03-14 10:58:38 +000053static cl::opt<bool>
54SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
58
Evan Cheng44436302010-10-16 02:20:26 +000059STATISTIC(NumHoisted,
60 "Number of machine instructions hoisted out of loops");
61STATISTIC(NumLowRP,
62 "Number of instructions hoisted in low reg pressure situation");
63STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
65STATISTIC(NumCSEed,
66 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000067STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000069
Bill Wendlingfb706bc2007-12-07 21:42:31 +000070namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000071 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000072 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000073 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000074 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000075 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000076 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +000077 TargetSchedModel SchedModel;
Andrew Trickc40815d2012-02-08 21:23:03 +000078 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000079
Bill Wendlingfb706bc2007-12-07 21:42:31 +000080 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000081 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000082 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000083 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000084
Bill Wendlingfb706bc2007-12-07 21:42:31 +000085 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000086 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000087 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000088 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000089 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000090
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000091 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
93
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
96 ExitBlocks.end();
97 }
98
Evan Chengd62719c2010-10-14 01:16:09 +000099 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000100 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000101 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000102
Daniel Jasper274928f2015-04-14 11:56:25 +0000103 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000104 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000105 SmallVector<unsigned, 8> RegLimit;
106
Evan Cheng44436302010-10-16 02:20:26 +0000107 // Register pressure on path leading from loop preheader to current BB.
108 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
109
Dale Johannesen329d4742010-07-29 17:45:24 +0000110 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000111 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000112
Evan Chengf192ca02011-10-11 23:48:44 +0000113 enum {
114 SpeculateFalse = 0,
115 SpeculateTrue = 1,
116 SpeculateUnknown = 2
117 };
118
Devang Patel453d4012011-10-11 18:09:58 +0000119 // If a MBB does not dominate loop exiting blocks then it may not safe
120 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000121 // Tri-state: 0 - false, 1 - true, 2 - unknown
122 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000123
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000124 public:
125 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000126 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000127 MachineFunctionPass(ID), PreRegAlloc(true) {
128 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
129 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000130
131 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000132 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
134 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000135
Craig Topper4584cd52014-03-07 09:26:03 +0000136 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000137
Craig Topper4584cd52014-03-07 09:26:03 +0000138 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000139 AU.addRequired<MachineLoopInfo>();
140 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000141 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000142 AU.addPreserved<MachineLoopInfo>();
143 AU.addPreserved<MachineDominatorTree>();
144 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000145 }
Evan Cheng399660c2009-02-05 08:45:46 +0000146
Craig Topper4584cd52014-03-07 09:26:03 +0000147 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000148 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000149 RegPressure.clear();
150 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000151 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000152 CSEMap.clear();
153 }
154
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000155 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000156 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000157 struct CandidateInfo {
158 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000159 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000160 int FI;
161 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000163 };
164
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000165 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000166
Evan Cheng058b9f02010-04-08 01:03:47 +0000167 void HoistPostRA(MachineInstr *MI, unsigned Def);
168
Sanjay Patel87c6c072015-12-10 16:34:21 +0000169 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
170 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000171 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000172
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000173 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000174
Evan Cheng0a2aff22010-04-13 18:16:00 +0000175 bool IsLICMCandidate(MachineInstr &I);
176
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000177 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000178
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000179 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000180
Evan Chenge96b8d72010-10-26 02:08:50 +0000181 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
182 unsigned Reg) const;
183
184 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000185
Daniel Jasperefece522015-04-03 16:19:48 +0000186 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
187 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000188
Evan Cheng87066f02010-10-20 22:03:58 +0000189 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000190
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000191 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000192
Devang Patel453d4012011-10-11 18:09:58 +0000193 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
194
Pete Cooper1eed5b52011-12-22 02:05:40 +0000195 void EnterScope(MachineBasicBlock *MBB);
196
197 void ExitScope(MachineBasicBlock *MBB);
198
Sanjay Patel87c6c072015-12-10 16:34:21 +0000199 void ExitScopeIfDone(
200 MachineDomTreeNode *Node,
201 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
202 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000203
Pete Cooper1eed5b52011-12-22 02:05:40 +0000204 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000205
Pete Cooper1eed5b52011-12-22 02:05:40 +0000206 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000207
Daniel Jasper15e69542015-03-14 10:58:38 +0000208 void SinkIntoLoop();
209
Evan Chengd62719c2010-10-14 01:16:09 +0000210 void InitRegPressure(MachineBasicBlock *BB);
211
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000212 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
213 bool ConsiderSeen,
214 bool ConsiderUnseenAsDef);
215
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000216 void UpdateRegPressure(const MachineInstr *MI,
217 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000218
Dan Gohman104f57c2009-10-29 17:47:20 +0000219 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
220
Sanjay Patel87c6c072015-12-10 16:34:21 +0000221 const MachineInstr *
222 LookForDuplicate(const MachineInstr *MI,
223 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000224
Sanjay Patel87c6c072015-12-10 16:34:21 +0000225 bool EliminateCSE(
226 MachineInstr *MI,
227 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000228
Evan Chengaf138952011-10-12 00:09:14 +0000229 bool MayCSE(MachineInstr *MI);
230
Evan Cheng87066f02010-10-20 22:03:58 +0000231 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000232
Evan Chengf42b5af2009-11-03 21:40:02 +0000233 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000234
Dan Gohman3570f812010-06-22 17:25:57 +0000235 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000236 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000237} // end anonymous namespace
238
Dan Gohmand78c4002008-05-13 00:00:25 +0000239char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000240char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000241INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
242 "Machine Loop Invariant Code Motion", false, false)
243INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
244INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000245INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000246INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000247 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000248
Sanjay Patel87c6c072015-12-10 16:34:21 +0000249/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000250static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000251 // Check whether this loop even has a unique predecessor.
252 if (!CurLoop->getLoopPredecessor())
253 return false;
254 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000255 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000256 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000257 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000258 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000259 return true;
260}
261
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000262bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000263 if (skipOptnoneFunction(*MF.getFunction()))
264 return false;
265
Evan Cheng032f3262010-05-29 00:06:36 +0000266 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000267 const TargetSubtargetInfo &ST = MF.getSubtarget();
268 TII = ST.getInstrInfo();
269 TLI = ST.getTargetLowering();
270 TRI = ST.getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000271 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000272 MRI = &MF.getRegInfo();
Matthias Braun88e21312015-06-13 03:42:11 +0000273 SchedModel.init(ST.getSchedModel(), &ST, TII);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000274
Andrew Trickc40815d2012-02-08 21:23:03 +0000275 PreRegAlloc = MRI->isSSA();
276
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000277 if (PreRegAlloc)
278 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
279 else
280 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000281 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000282
Evan Chengd62719c2010-10-14 01:16:09 +0000283 if (PreRegAlloc) {
284 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000285 unsigned NumRPS = TRI->getNumRegPressureSets();
286 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000287 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000288 RegLimit.resize(NumRPS);
289 for (unsigned i = 0, e = NumRPS; i != e; ++i)
290 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000291 }
292
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000293 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000294 MLI = &getAnalysis<MachineLoopInfo>();
295 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000296 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000297
Dan Gohman7929c442010-07-09 18:49:45 +0000298 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
299 while (!Worklist.empty()) {
300 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000301 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000302 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000303
Evan Cheng058b9f02010-04-08 01:03:47 +0000304 // If this is done before regalloc, only visit outer-most preheader-sporting
305 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000306 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
307 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000308 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000309 }
Dan Gohman79618d12009-01-15 22:01:38 +0000310
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000311 CurLoop->getExitBlocks(ExitBlocks);
312
Evan Cheng6ea59492010-04-07 00:41:17 +0000313 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000314 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000315 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000316 // CSEMap is initialized for loop header when the first instruction is
317 // being hoisted.
318 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000319 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000320 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000321 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000322
323 if (SinkInstsToAvoidSpills)
324 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000325 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000326 }
327
328 return Changed;
329}
330
Sanjay Patel87c6c072015-12-10 16:34:21 +0000331/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000332static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Philip Reames42bd26f2015-12-23 17:05:57 +0000333 // If we lost memory operands, conservatively assume that the instruction
334 // writes to all slots.
335 if (MI->memoperands_empty())
336 return true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000337 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
338 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000339 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000340 continue;
341 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000342 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000343 if (Value->getFrameIndex() == FI)
344 return true;
345 }
346 }
347 return false;
348}
349
Sanjay Patel87c6c072015-12-10 16:34:21 +0000350/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000351/// gather register def and frame object update information.
352void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000353 BitVector &PhysRegDefs,
354 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000355 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000356 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000357 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000358 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000359 unsigned Def = 0;
360 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
361 const MachineOperand &MO = MI->getOperand(i);
362 if (MO.isFI()) {
363 // Remember if the instruction stores to the frame index.
364 int FI = MO.getIndex();
365 if (!StoredFIs.count(FI) &&
366 MFI->isSpillSlotObjectIndex(FI) &&
367 InstructionStoresToFI(MI, FI))
368 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000369 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000370 continue;
371 }
372
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000373 // We can't hoist an instruction defining a physreg that is clobbered in
374 // the loop.
375 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000376 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000377 continue;
378 }
379
Evan Cheng058b9f02010-04-08 01:03:47 +0000380 if (!MO.isReg())
381 continue;
382 unsigned Reg = MO.getReg();
383 if (!Reg)
384 continue;
385 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
386 "Not expecting virtual register!");
387
Evan Cheng0a2aff22010-04-13 18:16:00 +0000388 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000389 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000390 // If it's using a non-loop-invariant register, then it's obviously not
391 // safe to hoist.
392 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000393 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000394 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000395
396 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000397 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
398 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000399 if (!MO.isDead())
400 // Non-dead implicit def? This cannot be hoisted.
401 RuledOut = true;
402 // No need to check if a dead implicit def is also defined by
403 // another instruction.
404 continue;
405 }
406
407 // FIXME: For now, avoid instructions with multiple defs, unless
408 // it's a dead implicit def.
409 if (Def)
410 RuledOut = true;
411 else
412 Def = Reg;
413
414 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000415 // register, then this is not safe. Two defs is indicated by setting a
416 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000417 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000418 if (PhysRegDefs.test(*AS))
419 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000420 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000421 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000422 if (PhysRegClobbers.test(Reg))
423 // MI defined register is seen defined by another instruction in
424 // the loop, it cannot be a LICM candidate.
425 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000426 }
427
Evan Cheng0a2aff22010-04-13 18:16:00 +0000428 // Only consider reloads for now and remats which do not have register
429 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000430 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000431 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000432 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000433 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
434 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000435 }
436}
437
Sanjay Patel87c6c072015-12-10 16:34:21 +0000438/// Walk the specified region of the CFG and hoist loop invariants out to the
439/// preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000440void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000441 MachineBasicBlock *Preheader = getCurPreheader();
442 if (!Preheader)
443 return;
444
Evan Cheng6ea59492010-04-07 00:41:17 +0000445 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000446 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
447 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000448
Evan Cheng058b9f02010-04-08 01:03:47 +0000449 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000450 SmallSet<int, 32> StoredFIs;
451
452 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000453 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000454 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000455 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
456 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000457
458 // If the header of the loop containing this basic block is a landing pad,
459 // then don't try to hoist instructions out of this loop.
460 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000461 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000462
Evan Cheng6ea59492010-04-07 00:41:17 +0000463 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000464 // FIXME: That means a reload that're reused in successor block(s) will not
465 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000466 for (const auto &LI : BB->liveins()) {
467 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000468 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000469 }
470
Evan Chengf192ca02011-10-11 23:48:44 +0000471 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000472 for (MachineBasicBlock::iterator
473 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000474 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000475 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000476 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000477 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000478
Evan Cheng7fede872012-03-27 01:50:58 +0000479 // Gather the registers read / clobbered by the terminator.
480 BitVector TermRegs(NumRegs);
481 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
482 if (TI != Preheader->end()) {
483 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
484 const MachineOperand &MO = TI->getOperand(i);
485 if (!MO.isReg())
486 continue;
487 unsigned Reg = MO.getReg();
488 if (!Reg)
489 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000490 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
491 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000492 }
493 }
494
Evan Cheng6ea59492010-04-07 00:41:17 +0000495 // Now evaluate whether the potential candidates qualify.
496 // 1. Check if the candidate defined register is defined by another
497 // instruction in the loop.
498 // 2. If the candidate is a load from stack slot (always true for now),
499 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000500 // 3. Make sure candidate def should not clobber
501 // registers read by the terminator. Similarly its def should not be
502 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000503 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000504 if (Candidates[i].FI != INT_MIN &&
505 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000506 continue;
507
Evan Cheng7fede872012-03-27 01:50:58 +0000508 unsigned Def = Candidates[i].Def;
509 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000510 bool Safe = true;
511 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000512 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
513 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000514 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000515 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000516 unsigned Reg = MO.getReg();
517 if (PhysRegDefs.test(Reg) ||
518 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000519 // If it's using a non-loop-invariant register, then it's obviously
520 // not safe to hoist.
521 Safe = false;
522 break;
523 }
524 }
525 if (Safe)
526 HoistPostRA(MI, Candidates[i].Def);
527 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000528 }
529}
530
Sanjay Patel87c6c072015-12-10 16:34:21 +0000531/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
532/// sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000533void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000534 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000535 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
536 MachineBasicBlock *BB = Blocks[i];
537 if (!BB->isLiveIn(Reg))
538 BB->addLiveIn(Reg);
539 for (MachineBasicBlock::iterator
540 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
541 MachineInstr *MI = &*MII;
542 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
543 MachineOperand &MO = MI->getOperand(i);
544 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
545 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
546 MO.setIsKill(false);
547 }
548 }
549 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000550}
551
Sanjay Patel87c6c072015-12-10 16:34:21 +0000552/// When an instruction is found to only use loop invariant operands that is
553/// safe to hoist, this instruction is called to do the dirty work.
Evan Cheng058b9f02010-04-08 01:03:47 +0000554void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000555 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000556
Evan Cheng6ea59492010-04-07 00:41:17 +0000557 // Now move the instructions to the predecessor, inserting it before any
558 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000559 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
560 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000561
562 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000563 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000564 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000565
Andrew Trick5209c732012-02-08 21:23:00 +0000566 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000567 // loop invariant must be kept live throughout the whole loop. This is
568 // important to ensure later passes do not scavenge the def register.
569 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000570
571 ++NumPostRAHoisted;
572 Changed = true;
573}
574
Sanjay Patel87c6c072015-12-10 16:34:21 +0000575/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
576/// may not be safe to hoist.
Devang Patel453d4012011-10-11 18:09:58 +0000577bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000578 if (SpeculationState != SpeculateUnknown)
579 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000580
Devang Patel453d4012011-10-11 18:09:58 +0000581 if (BB != CurLoop->getHeader()) {
582 // Check loop exiting blocks.
583 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
584 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
585 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
586 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000587 SpeculationState = SpeculateTrue;
588 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000589 }
590 }
591
Evan Chengf192ca02011-10-11 23:48:44 +0000592 SpeculationState = SpeculateFalse;
593 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000594}
595
Pete Cooper1eed5b52011-12-22 02:05:40 +0000596void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
597 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000598
Pete Cooper1eed5b52011-12-22 02:05:40 +0000599 // Remember livein register pressure.
600 BackTrace.push_back(RegPressure);
601}
Bill Wendling918cea22011-10-12 02:58:01 +0000602
Pete Cooper1eed5b52011-12-22 02:05:40 +0000603void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
604 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
605 BackTrace.pop_back();
606}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000607
Sanjay Patel87c6c072015-12-10 16:34:21 +0000608/// Destroy scope for the MBB that corresponds to the given dominator tree node
609/// if its a leaf or all of its children are done. Walk up the dominator tree to
610/// destroy ancestors which are now done.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000611void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000612 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
613 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000614 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000615 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000616
Pete Cooper1eed5b52011-12-22 02:05:40 +0000617 // Pop scope.
618 ExitScope(Node->getBlock());
619
620 // Now traverse upwards to pop ancestors whose offsprings are all done.
621 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
622 unsigned Left = --OpenChildren[Parent];
623 if (Left != 0)
624 break;
625 ExitScope(Parent->getBlock());
626 Node = Parent;
627 }
628}
629
Sanjay Patel87c6c072015-12-10 16:34:21 +0000630/// Walk the specified loop in the CFG (defined by all blocks dominated by the
631/// specified header block, and that are in the current loop) in depth first
632/// order w.r.t the DominatorTree. This allows us to visit definitions before
633/// uses, allowing us to hoist a loop body in one pass without iteration.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000634///
635void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000636 MachineBasicBlock *Preheader = getCurPreheader();
637 if (!Preheader)
638 return;
639
Pete Cooper1eed5b52011-12-22 02:05:40 +0000640 SmallVector<MachineDomTreeNode*, 32> Scopes;
641 SmallVector<MachineDomTreeNode*, 8> WorkList;
642 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
643 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
644
645 // Perform a DFS walk to determine the order of visit.
646 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000647 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000648 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000649 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000650 MachineBasicBlock *BB = Node->getBlock();
651
652 // If the header of the loop containing this basic block is a landing pad,
653 // then don't try to hoist instructions out of this loop.
654 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000655 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000656 continue;
657
658 // If this subregion is not in the top level loop at all, exit.
659 if (!CurLoop->contains(BB))
660 continue;
661
662 Scopes.push_back(Node);
663 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
664 unsigned NumChildren = Children.size();
665
666 // Don't hoist things out of a large switch statement. This often causes
667 // code to be hoisted that wasn't going to be executed, and increases
668 // register pressure in a situation where it's likely to matter.
669 if (BB->succ_size() >= 25)
670 NumChildren = 0;
671
672 OpenChildren[Node] = NumChildren;
673 // Add children in reverse order as then the next popped worklist node is
674 // the first child of this node. This means we ultimately traverse the
675 // DOM tree in exactly the same order as if we'd recursed.
676 for (int i = (int)NumChildren-1; i >= 0; --i) {
677 MachineDomTreeNode *Child = Children[i];
678 ParentMap[Child] = Node;
679 WorkList.push_back(Child);
680 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000681 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000682
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000683 if (Scopes.size() == 0)
684 return;
685
686 // Compute registers which are livein into the loop headers.
687 RegSeen.clear();
688 BackTrace.clear();
689 InitRegPressure(Preheader);
690
Pete Cooper1eed5b52011-12-22 02:05:40 +0000691 // Now perform LICM.
692 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
693 MachineDomTreeNode *Node = Scopes[i];
694 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000695
Pete Cooper1eed5b52011-12-22 02:05:40 +0000696 EnterScope(MBB);
697
698 // Process the block
699 SpeculationState = SpeculateUnknown;
700 for (MachineBasicBlock::iterator
701 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
702 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
703 MachineInstr *MI = &*MII;
704 if (!Hoist(MI, Preheader))
705 UpdateRegPressure(MI);
706 MII = NextMII;
707 }
708
709 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
710 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000711 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000712}
713
Sanjay Patel87c6c072015-12-10 16:34:21 +0000714/// Sink instructions into loops if profitable. This especially tries to prevent
715/// register spills caused by register pressure if there is little to no
716/// overhead moving instructions into loops.
Daniel Jasper15e69542015-03-14 10:58:38 +0000717void MachineLICM::SinkIntoLoop() {
718 MachineBasicBlock *Preheader = getCurPreheader();
719 if (!Preheader)
720 return;
721
722 SmallVector<MachineInstr *, 8> Candidates;
723 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
724 I != Preheader->instr_end(); ++I) {
725 // We need to ensure that we can safely move this instruction into the loop.
726 // As such, it must not have side-effects, e.g. such as a call has.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000727 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
728 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000729 }
730
731 for (MachineInstr *I : Candidates) {
732 const MachineOperand &MO = I->getOperand(0);
733 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
734 continue;
735 if (!MRI->hasOneDef(MO.getReg()))
736 continue;
737 bool CanSink = true;
738 MachineBasicBlock *B = nullptr;
739 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
740 // FIXME: Come up with a proper cost model that estimates whether sinking
741 // the instruction (and thus possibly executing it on every loop
742 // iteration) is more expensive than a register.
743 // For now assumes that copies are cheap and thus almost always worth it.
744 if (!MI.isCopy()) {
745 CanSink = false;
746 break;
747 }
748 if (!B) {
749 B = MI.getParent();
750 continue;
751 }
752 B = DT->findNearestCommonDominator(B, MI.getParent());
753 if (!B) {
754 CanSink = false;
755 break;
756 }
757 }
758 if (!CanSink || !B || B == Preheader)
759 continue;
760 B->splice(B->getFirstNonPHI(), Preheader, I);
761 }
762}
763
Evan Cheng87066f02010-10-20 22:03:58 +0000764static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
765 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
766}
767
Sanjay Patel87c6c072015-12-10 16:34:21 +0000768/// Find all virtual register references that are liveout of the preheader to
769/// initialize the starting "register pressure". Note this does not count live
770/// through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000771void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000772 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000773
Evan Cheng87066f02010-10-20 22:03:58 +0000774 // If the preheader has only a single predecessor and it ends with a
775 // fallthrough or an unconditional branch, then scan its predecessor for live
776 // defs as well. This happens whenever the preheader is created by splitting
777 // the critical edge from the loop predecessor to the loop header.
778 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000779 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000780 SmallVector<MachineOperand, 4> Cond;
781 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
782 InitRegPressure(*BB->pred_begin());
783 }
784
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000785 for (const MachineInstr &MI : *BB)
786 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000787}
788
Sanjay Patel87c6c072015-12-10 16:34:21 +0000789/// Update estimate of register pressure after the specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000790void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
791 bool ConsiderUnseenAsDef) {
792 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000793 for (const auto &RPIdAndCost : Cost) {
794 unsigned Class = RPIdAndCost.first;
795 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000796 RegPressure[Class] = 0;
797 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000798 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000799 }
800}
Evan Chengd62719c2010-10-14 01:16:09 +0000801
Sanjay Patel87c6c072015-12-10 16:34:21 +0000802/// Calculate the additional register pressure that the registers used in MI
803/// cause.
804///
805/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
806/// figure out which usages are live-ins.
807/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000808DenseMap<unsigned, int>
809MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
810 bool ConsiderUnseenAsDef) {
811 DenseMap<unsigned, int> Cost;
812 if (MI->isImplicitDef())
813 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000814 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
815 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000816 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000817 continue;
818 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000819 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000820 continue;
821
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000822 // FIXME: It seems bad to use RegSeen only for some of these calculations.
823 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000824 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
825
826 RegClassWeight W = TRI->getRegClassWeight(RC);
827 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000828 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000829 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000830 else {
831 bool isKill = isOperandKill(MO, MRI);
832 if (isNew && !isKill && ConsiderUnseenAsDef)
833 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000834 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000835 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000836 RCCost = -W.RegWeight;
837 }
838 if (RCCost == 0)
839 continue;
840 const int *PS = TRI->getRegClassPressureSets(RC);
841 for (; *PS != -1; ++PS) {
842 if (Cost.find(*PS) == Cost.end())
843 Cost[*PS] = RCCost;
844 else
845 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000846 }
Evan Chengd62719c2010-10-14 01:16:09 +0000847 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000848 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000849}
850
Sanjay Patel87c6c072015-12-10 16:34:21 +0000851/// Return true if this machine instruction loads from global offset table or
852/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000853static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000854 assert (MI.mayLoad() && "Expected MI that loads!");
Philip Reames42bd26f2015-12-23 17:05:57 +0000855
856 // If we lost memory operands, conservatively assume that the instruction
857 // reads from everything..
858 if (MI.memoperands_empty())
859 return true;
860
Devang Patel69a45652011-10-17 17:35:01 +0000861 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000862 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000863 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
Alex Lorenze40c8a22015-08-11 23:09:45 +0000864 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000865 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000866 }
867 }
868 return false;
869}
870
Sanjay Patel87c6c072015-12-10 16:34:21 +0000871/// Returns true if the instruction may be a suitable candidate for LICM.
872/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000873bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000874 // Check if it's safe to move the instruction.
875 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000876 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000877 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000878
879 // If it is load then check if it is guaranteed to execute by making sure that
880 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000881 // the loop which does not execute this load, so we can't hoist it. Loads
882 // from constant memory are not safe to speculate all the time, for example
883 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000884 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000885 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000886 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000887 return false;
888
Evan Cheng0a2aff22010-04-13 18:16:00 +0000889 return true;
890}
891
Sanjay Patel87c6c072015-12-10 16:34:21 +0000892/// Returns true if the instruction is loop invariant.
893/// I.e., all virtual register operands are defined outside of the loop,
894/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +0000895/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000896///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000897bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
898 if (!IsLICMCandidate(I))
899 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000900
Bill Wendling70613b82008-05-12 19:38:32 +0000901 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000902 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
903 const MachineOperand &MO = I.getOperand(i);
904
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000905 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000906 continue;
907
Dan Gohman79618d12009-01-15 22:01:38 +0000908 unsigned Reg = MO.getReg();
909 if (Reg == 0) continue;
910
911 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000912 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000913 if (MO.isUse()) {
914 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000915 // and we can freely move its uses. Alternatively, if it's allocatable,
916 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000917 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000918 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000919 // Otherwise it's safe to move.
920 continue;
921 } else if (!MO.isDead()) {
922 // A def that isn't dead. We can't move it.
923 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000924 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
925 // If the reg is live into the loop, we can't hoist an instruction
926 // which would clobber it.
927 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000928 }
929 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000930
931 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000932 continue;
933
Evan Chengd62719c2010-10-14 01:16:09 +0000934 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000935 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000936
937 // If the loop contains the definition of an operand, then the instruction
938 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000939 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000940 return false;
941 }
942
943 // If we got this far, the instruction is loop invariant!
944 return true;
945}
946
Evan Cheng399660c2009-02-05 08:45:46 +0000947
Sanjay Patel87c6c072015-12-10 16:34:21 +0000948/// Return true if the specified instruction is used by a phi node and hoisting
949/// it could cause a copy to be inserted.
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000950bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
951 SmallVector<const MachineInstr*, 8> Work(1, MI);
952 do {
953 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +0000954 for (const MachineOperand &MO : MI->operands()) {
955 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000956 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000957 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000958 if (!TargetRegisterInfo::isVirtualRegister(Reg))
959 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000960 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000961 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000962 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000963 // A PHI inside the loop causes a copy because the live range of Reg is
964 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000965 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000966 return true;
967 // A PHI in an exit block can cause a copy to be inserted if the PHI
968 // has multiple predecessors in the loop with different values.
969 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000970 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000971 return true;
972 continue;
973 }
974 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000975 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
976 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000977 }
Evan Chengef42bea2011-04-11 21:09:18 +0000978 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000979 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +0000980 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000981}
982
Sanjay Patel87c6c072015-12-10 16:34:21 +0000983/// Compute operand latency between a def of 'Reg' and an use in the current
984/// loop, return true if the target considered it high.
Evan Cheng63c76082010-10-19 18:58:51 +0000985bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +0000986 unsigned DefIdx, unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +0000987 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +0000988 return false;
Evan Chengd62719c2010-10-14 01:16:09 +0000989
Owen Andersonb36376e2014-03-17 19:36:09 +0000990 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
991 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +0000992 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000993 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +0000994 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000995 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
996 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +0000997 if (!MO.isReg() || !MO.isUse())
998 continue;
999 unsigned MOReg = MO.getReg();
1000 if (MOReg != Reg)
1001 continue;
1002
Matthias Braun88e21312015-06-13 03:42:11 +00001003 if (TII->hasHighOperandLatency(SchedModel, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001004 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001005 }
1006
Evan Cheng63c76082010-10-19 18:58:51 +00001007 // Only look at the first in loop use.
1008 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001009 }
1010
Evan Cheng63c76082010-10-19 18:58:51 +00001011 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001012}
1013
Sanjay Patel87c6c072015-12-10 16:34:21 +00001014/// Return true if the instruction is marked "cheap" or the operand latency
1015/// between its def and a use is one or less.
Evan Chenge96b8d72010-10-26 02:08:50 +00001016bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001017 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001018 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001019
1020 bool isCheap = false;
1021 unsigned NumDefs = MI.getDesc().getNumDefs();
1022 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1023 MachineOperand &DefMO = MI.getOperand(i);
1024 if (!DefMO.isReg() || !DefMO.isDef())
1025 continue;
1026 --NumDefs;
1027 unsigned Reg = DefMO.getReg();
1028 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1029 continue;
1030
Matthias Braun88e21312015-06-13 03:42:11 +00001031 if (!TII->hasLowDefLatency(SchedModel, &MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001032 return false;
1033 isCheap = true;
1034 }
1035
1036 return isCheap;
1037}
1038
Sanjay Patel87c6c072015-12-10 16:34:21 +00001039/// Visit BBs from header to current BB, check if hoisting an instruction of the
1040/// given cost matrix can cause high register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +00001041bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001042 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001043 for (const auto &RPIdAndCost : Cost) {
1044 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001045 continue;
1046
Daniel Jasper274928f2015-04-14 11:56:25 +00001047 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001048 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001049
1050 // Don't hoist cheap instructions if they would increase register pressure,
1051 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001052 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001053 return true;
1054
Daniel Jasperefece522015-04-03 16:19:48 +00001055 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001056 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001057 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001058 }
1059
1060 return false;
1061}
1062
Sanjay Patel87c6c072015-12-10 16:34:21 +00001063/// Traverse the back trace from header to the current block and update their
1064/// register pressures to reflect the effect of hoisting MI from the current
1065/// block to the preheader.
Evan Cheng87066f02010-10-20 22:03:58 +00001066void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001067 // First compute the 'cost' of the instruction, i.e. its contribution
1068 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001069 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1070 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001071
1072 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001073 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001074 for (const auto &RPIdAndCost : Cost)
1075 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001076}
1077
Sanjay Patel87c6c072015-12-10 16:34:21 +00001078/// Return true if it is potentially profitable to hoist the given loop
1079/// invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001080bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001081 if (MI.isImplicitDef())
1082 return true;
1083
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001084 // Besides removing computation from the loop, hoisting an instruction has
1085 // these effects:
1086 //
1087 // - The value defined by the instruction becomes live across the entire
1088 // loop. This increases register pressure in the loop.
1089 //
1090 // - If the value is used by a PHI in the loop, a copy will be required for
1091 // lowering the PHI after extending the live range.
1092 //
1093 // - When hoisting the last use of a value in the loop, that value no longer
1094 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001095
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001096 bool CheapInstr = IsCheapInstruction(MI);
1097 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001098
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001099 // Don't hoist a cheap instruction if it would create a copy in the loop.
1100 if (CheapInstr && CreatesCopy) {
1101 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1102 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001103 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001104
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001105 // Rematerializable instructions should always be hoisted since the register
1106 // allocator can just pull them down again when needed.
1107 if (TII->isTriviallyReMaterializable(&MI, AA))
1108 return true;
1109
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001110 // FIXME: If there are long latency loop-invariant instructions inside the
1111 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001112 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1113 const MachineOperand &MO = MI.getOperand(i);
1114 if (!MO.isReg() || MO.isImplicit())
1115 continue;
1116 unsigned Reg = MO.getReg();
1117 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1118 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001119 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1120 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1121 ++NumHighLatency;
1122 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001123 }
1124 }
1125
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001126 // Estimate register pressure to determine whether to LICM the instruction.
1127 // In low register pressure situation, we can be more aggressive about
1128 // hoisting. Also, favors hoisting long latency instructions even in
1129 // moderately high pressure situation.
1130 // Cheap instructions will only be hoisted if they don't increase register
1131 // pressure at all.
1132 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1133 /*ConsiderUnseenAsDef=*/false);
1134
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001135 // Visit BBs from header to current BB, if hoisting this doesn't cause
1136 // high register pressure, then it's safe to proceed.
1137 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1138 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1139 ++NumLowRP;
1140 return true;
1141 }
1142
1143 // Don't risk increasing register pressure if it would create copies.
1144 if (CreatesCopy) {
1145 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001146 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001147 }
1148
1149 // Do not "speculate" in high register pressure situation. If an
1150 // instruction is not guaranteed to be executed in the loop, it's best to be
1151 // conservative.
1152 if (AvoidSpeculation &&
1153 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1154 DEBUG(dbgs() << "Won't speculate: " << MI);
1155 return false;
1156 }
1157
1158 // High register pressure situation, only hoist if the instruction is going
1159 // to be remat'ed.
1160 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1161 !MI.isInvariantLoad(AA)) {
1162 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1163 return false;
1164 }
Evan Cheng399660c2009-02-05 08:45:46 +00001165
1166 return true;
1167}
1168
Sanjay Patel87c6c072015-12-10 16:34:21 +00001169/// Unfold a load from the given machineinstr if the load itself could be
1170/// hoisted. Return the unfolded and hoistable load, or null if the load
1171/// couldn't be unfolded or if it wouldn't be hoistable.
Dan Gohman104f57c2009-10-29 17:47:20 +00001172MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001173 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001174 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001175 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001176
Dan Gohman104f57c2009-10-29 17:47:20 +00001177 // If not, we may be able to unfold a load and hoist that.
1178 // First test whether the instruction is loading from an amenable
1179 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001180 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001181 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001182
Dan Gohman104f57c2009-10-29 17:47:20 +00001183 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001184 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001185 unsigned NewOpc =
1186 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1187 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001188 /*UnfoldStore=*/false,
1189 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001190 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001191 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001192 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001193 MachineFunction &MF = *MI->getParent()->getParent();
1194 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001195 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001196 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001197
Dan Gohman104f57c2009-10-29 17:47:20 +00001198 SmallVector<MachineInstr *, 2> NewMIs;
1199 bool Success =
1200 TII->unfoldMemoryOperand(MF, MI, Reg,
1201 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1202 NewMIs);
1203 (void)Success;
1204 assert(Success &&
1205 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1206 "succeeded!");
1207 assert(NewMIs.size() == 2 &&
1208 "Unfolded a load into multiple instructions!");
1209 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001210 MachineBasicBlock::iterator Pos = MI;
1211 MBB->insert(Pos, NewMIs[0]);
1212 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001213 // If unfolding produced a load that wasn't loop-invariant or profitable to
1214 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001215 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001216 NewMIs[0]->eraseFromParent();
1217 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001218 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001219 }
Evan Cheng87066f02010-10-20 22:03:58 +00001220
1221 // Update register pressure for the unfolded instruction.
1222 UpdateRegPressure(NewMIs[1]);
1223
Dan Gohman104f57c2009-10-29 17:47:20 +00001224 // Otherwise we successfully unfolded a load that we can hoist.
1225 MI->eraseFromParent();
1226 return NewMIs[0];
1227}
1228
Sanjay Patel87c6c072015-12-10 16:34:21 +00001229/// Initialize the CSE map with instructions that are in the current loop
1230/// preheader that may become duplicates of instructions that are hoisted
1231/// out of the loop.
Evan Chengf42b5af2009-11-03 21:40:02 +00001232void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1233 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1234 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001235 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001236 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001237 }
1238}
1239
Sanjay Patel87c6c072015-12-10 16:34:21 +00001240/// Find an instruction amount PrevMIs that is a duplicate of MI.
1241/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001242const MachineInstr*
1243MachineLICM::LookForDuplicate(const MachineInstr *MI,
1244 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001245 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1246 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001247 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001248 return PrevMI;
1249 }
Craig Topperc0196b12014-04-14 00:51:57 +00001250 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001251}
1252
Sanjay Patel87c6c072015-12-10 16:34:21 +00001253/// Given a LICM'ed instruction, look for an instruction on the preheader that
1254/// computes the same value. If it's found, do a RAU on with the definition of
1255/// the existing instruction rather than hoisting the instruction to the
1256/// preheader.
Evan Cheng921152f2009-11-05 00:51:13 +00001257bool MachineLICM::EliminateCSE(MachineInstr *MI,
1258 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001259 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1260 // the undef property onto uses.
1261 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001262 return false;
1263
1264 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001265 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001266
1267 // Replace virtual registers defined by MI by their counterparts defined
1268 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001269 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001270 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1271 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001272
1273 // Physical registers may not differ here.
1274 assert((!MO.isReg() || MO.getReg() == 0 ||
1275 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1276 MO.getReg() == Dup->getOperand(i).getReg()) &&
1277 "Instructions with different phys regs are not identical!");
1278
1279 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001280 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1281 Defs.push_back(i);
1282 }
1283
1284 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1285 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1286 unsigned Idx = Defs[i];
1287 unsigned Reg = MI->getOperand(Idx).getReg();
1288 unsigned DupReg = Dup->getOperand(Idx).getReg();
1289 OrigRCs.push_back(MRI->getRegClass(DupReg));
1290
1291 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1292 // Restore old RCs if more than one defs.
1293 for (unsigned j = 0; j != i; ++j)
1294 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1295 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001296 }
Evan Cheng921152f2009-11-05 00:51:13 +00001297 }
Evan Chengaa563df2011-10-17 19:50:12 +00001298
1299 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1300 unsigned Idx = Defs[i];
1301 unsigned Reg = MI->getOperand(Idx).getReg();
1302 unsigned DupReg = Dup->getOperand(Idx).getReg();
1303 MRI->replaceRegWith(Reg, DupReg);
1304 MRI->clearKillFlags(DupReg);
1305 }
1306
Evan Cheng7ff83192009-11-07 03:52:02 +00001307 MI->eraseFromParent();
1308 ++NumCSEed;
1309 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001310 }
1311 return false;
1312}
1313
Sanjay Patel87c6c072015-12-10 16:34:21 +00001314/// Return true if the given instruction will be CSE'd if it's hoisted out of
1315/// the loop.
Evan Chengaf138952011-10-12 00:09:14 +00001316bool MachineLICM::MayCSE(MachineInstr *MI) {
1317 unsigned Opcode = MI->getOpcode();
1318 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1319 CI = CSEMap.find(Opcode);
1320 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1321 // the undef property onto uses.
1322 if (CI == CSEMap.end() || MI->isImplicitDef())
1323 return false;
1324
Craig Topperc0196b12014-04-14 00:51:57 +00001325 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001326}
1327
Sanjay Patel87c6c072015-12-10 16:34:21 +00001328/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001329/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001330/// It returns true if the instruction is hoisted.
Evan Cheng87066f02010-10-20 22:03:58 +00001331bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001332 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001333 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001334 // If not, try unfolding a hoistable load.
1335 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001336 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001337 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001338
Dan Gohman79618d12009-01-15 22:01:38 +00001339 // Now move the instructions to the predecessor, inserting it before any
1340 // terminator instructions.
1341 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001342 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001343 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001344 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001345 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001346 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001347 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001348 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001349 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001350 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001351
Evan Chengf42b5af2009-11-03 21:40:02 +00001352 // If this is the first instruction being hoisted to the preheader,
1353 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001354 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001355 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001356 FirstInLoop = false;
1357 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001358
Evan Cheng399660c2009-02-05 08:45:46 +00001359 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001360 unsigned Opcode = MI->getOpcode();
1361 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1362 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001363 if (!EliminateCSE(MI, CI)) {
1364 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001365 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001366
Evan Cheng87066f02010-10-20 22:03:58 +00001367 // Update register pressure for BBs from header to this block.
1368 UpdateBackTraceRegPressure(MI);
1369
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001370 // Clear the kill flags of any register this instruction defines,
1371 // since they may need to be live throughout the entire loop
1372 // rather than just live for part of it.
1373 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1374 MachineOperand &MO = MI->getOperand(i);
1375 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001376 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001377 }
1378
Evan Cheng399660c2009-02-05 08:45:46 +00001379 // Add to the CSE map.
1380 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001381 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001382 else
1383 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001384 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001385
Dan Gohman79618d12009-01-15 22:01:38 +00001386 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001387 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001388
1389 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001390}
Dan Gohman3570f812010-06-22 17:25:57 +00001391
Sanjay Patel87c6c072015-12-10 16:34:21 +00001392/// Get the preheader for the current loop, splitting a critical edge if needed.
Dan Gohman3570f812010-06-22 17:25:57 +00001393MachineBasicBlock *MachineLICM::getCurPreheader() {
1394 // Determine the block to which to hoist instructions. If we can't find a
1395 // suitable loop predecessor, we can't do any hoisting.
1396
1397 // If we've tried to get a preheader and failed, don't try again.
1398 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001399 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001400
1401 if (!CurPreheader) {
1402 CurPreheader = CurLoop->getLoopPreheader();
1403 if (!CurPreheader) {
1404 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1405 if (!Pred) {
1406 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001407 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001408 }
1409
1410 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1411 if (!CurPreheader) {
1412 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001413 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001414 }
1415 }
1416 }
1417 return CurPreheader;
1418}