blob: 8d59ad061eb8f611565aa7d6f5fcb3685f20a063 [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 {
David Majnemer0d955d02016-08-11 22:21:41 +000095 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000096 }
97
Evan Chengd62719c2010-10-14 01:16:09 +000098 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +000099 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000100 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000101
Daniel Jasper274928f2015-04-14 11:56:25 +0000102 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000103 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000104 SmallVector<unsigned, 8> RegLimit;
105
Evan Cheng44436302010-10-16 02:20:26 +0000106 // Register pressure on path leading from loop preheader to current BB.
107 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
108
Dale Johannesen329d4742010-07-29 17:45:24 +0000109 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000110 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000111
Evan Chengf192ca02011-10-11 23:48:44 +0000112 enum {
113 SpeculateFalse = 0,
114 SpeculateTrue = 1,
115 SpeculateUnknown = 2
116 };
117
Devang Patel453d4012011-10-11 18:09:58 +0000118 // If a MBB does not dominate loop exiting blocks then it may not safe
119 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000120 // Tri-state: 0 - false, 1 - true, 2 - unknown
121 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000122
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000123 public:
124 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000125 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 MachineFunctionPass(ID), PreRegAlloc(true) {
127 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
128 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000129
130 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000131 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
132 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
133 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000134
Craig Topper4584cd52014-03-07 09:26:03 +0000135 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000136
Craig Topper4584cd52014-03-07 09:26:03 +0000137 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000138 AU.addRequired<MachineLoopInfo>();
139 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000140 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000141 AU.addPreserved<MachineLoopInfo>();
142 AU.addPreserved<MachineDominatorTree>();
143 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000144 }
Evan Cheng399660c2009-02-05 08:45:46 +0000145
Craig Topper4584cd52014-03-07 09:26:03 +0000146 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000147 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000148 RegPressure.clear();
149 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000150 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000151 CSEMap.clear();
152 }
153
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000154 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000155 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000156 struct CandidateInfo {
157 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000158 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000159 int FI;
160 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
161 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000162 };
163
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000164 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000165
Evan Cheng058b9f02010-04-08 01:03:47 +0000166 void HoistPostRA(MachineInstr *MI, unsigned Def);
167
Sanjay Patel87c6c072015-12-10 16:34:21 +0000168 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
169 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000170 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000171
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000172 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000173
Evan Cheng0a2aff22010-04-13 18:16:00 +0000174 bool IsLICMCandidate(MachineInstr &I);
175
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000176 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000177
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000178 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000179
Evan Chenge96b8d72010-10-26 02:08:50 +0000180 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
181 unsigned Reg) const;
182
183 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000184
Daniel Jasperefece522015-04-03 16:19:48 +0000185 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
186 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000187
Evan Cheng87066f02010-10-20 22:03:58 +0000188 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000189
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000190 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000191
Devang Patel453d4012011-10-11 18:09:58 +0000192 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
193
Pete Cooper1eed5b52011-12-22 02:05:40 +0000194 void EnterScope(MachineBasicBlock *MBB);
195
196 void ExitScope(MachineBasicBlock *MBB);
197
Sanjay Patel87c6c072015-12-10 16:34:21 +0000198 void ExitScopeIfDone(
199 MachineDomTreeNode *Node,
200 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
201 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000202
Pete Cooper1eed5b52011-12-22 02:05:40 +0000203 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000204
Pete Cooper1eed5b52011-12-22 02:05:40 +0000205 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000206
Daniel Jasper15e69542015-03-14 10:58:38 +0000207 void SinkIntoLoop();
208
Evan Chengd62719c2010-10-14 01:16:09 +0000209 void InitRegPressure(MachineBasicBlock *BB);
210
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000211 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
212 bool ConsiderSeen,
213 bool ConsiderUnseenAsDef);
214
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000215 void UpdateRegPressure(const MachineInstr *MI,
216 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000217
Dan Gohman104f57c2009-10-29 17:47:20 +0000218 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
219
Sanjay Patel87c6c072015-12-10 16:34:21 +0000220 const MachineInstr *
221 LookForDuplicate(const MachineInstr *MI,
222 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000223
Sanjay Patel87c6c072015-12-10 16:34:21 +0000224 bool EliminateCSE(
225 MachineInstr *MI,
226 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000227
Evan Chengaf138952011-10-12 00:09:14 +0000228 bool MayCSE(MachineInstr *MI);
229
Evan Cheng87066f02010-10-20 22:03:58 +0000230 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000231
Evan Chengf42b5af2009-11-03 21:40:02 +0000232 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000233
Dan Gohman3570f812010-06-22 17:25:57 +0000234 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000235 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000236} // end anonymous namespace
237
Dan Gohmand78c4002008-05-13 00:00:25 +0000238char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000239char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000240INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
241 "Machine Loop Invariant Code Motion", false, false)
242INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
243INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000244INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000245INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000246 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000247
Sanjay Patel87c6c072015-12-10 16:34:21 +0000248/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000249static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000250 // Check whether this loop even has a unique predecessor.
251 if (!CurLoop->getLoopPredecessor())
252 return false;
253 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000254 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000255 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000256 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000257 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000258 return true;
259}
260
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000261bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000262 if (skipFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000263 return false;
264
Evan Cheng032f3262010-05-29 00:06:36 +0000265 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000266 const TargetSubtargetInfo &ST = MF.getSubtarget();
267 TII = ST.getInstrInfo();
268 TLI = ST.getTargetLowering();
269 TRI = ST.getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000270 MFI = &MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000271 MRI = &MF.getRegInfo();
Matthias Braun88e21312015-06-13 03:42:11 +0000272 SchedModel.init(ST.getSchedModel(), &ST, TII);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000273
Andrew Trickc40815d2012-02-08 21:23:03 +0000274 PreRegAlloc = MRI->isSSA();
275
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000276 if (PreRegAlloc)
277 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
278 else
279 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000280 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000281
Evan Chengd62719c2010-10-14 01:16:09 +0000282 if (PreRegAlloc) {
283 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000284 unsigned NumRPS = TRI->getNumRegPressureSets();
285 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000286 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000287 RegLimit.resize(NumRPS);
288 for (unsigned i = 0, e = NumRPS; i != e; ++i)
289 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000290 }
291
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000292 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000293 MLI = &getAnalysis<MachineLoopInfo>();
294 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000295 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000296
Dan Gohman7929c442010-07-09 18:49:45 +0000297 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
298 while (!Worklist.empty()) {
299 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000300 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000301 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000302
Evan Cheng058b9f02010-04-08 01:03:47 +0000303 // If this is done before regalloc, only visit outer-most preheader-sporting
304 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000305 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
306 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000307 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000308 }
Dan Gohman79618d12009-01-15 22:01:38 +0000309
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000310 CurLoop->getExitBlocks(ExitBlocks);
311
Evan Cheng6ea59492010-04-07 00:41:17 +0000312 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000313 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000314 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000315 // CSEMap is initialized for loop header when the first instruction is
316 // being hoisted.
317 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000318 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000319 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000320 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000321
322 if (SinkInstsToAvoidSpills)
323 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000324 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000325 }
326
327 return Changed;
328}
329
Sanjay Patel87c6c072015-12-10 16:34:21 +0000330/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000331static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Philip Reames42bd26f2015-12-23 17:05:57 +0000332 // If we lost memory operands, conservatively assume that the instruction
333 // writes to all slots.
334 if (MI->memoperands_empty())
335 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000336 for (const MachineMemOperand *MemOp : MI->memoperands()) {
337 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000338 continue;
339 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000340 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000341 if (Value->getFrameIndex() == FI)
342 return true;
343 }
344 }
345 return false;
346}
347
Sanjay Patel87c6c072015-12-10 16:34:21 +0000348/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000349/// gather register def and frame object update information.
350void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000351 BitVector &PhysRegDefs,
352 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000353 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000354 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000355 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000356 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000357 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000358 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000359 if (MO.isFI()) {
360 // Remember if the instruction stores to the frame index.
361 int FI = MO.getIndex();
362 if (!StoredFIs.count(FI) &&
363 MFI->isSpillSlotObjectIndex(FI) &&
364 InstructionStoresToFI(MI, FI))
365 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000366 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000367 continue;
368 }
369
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000370 // We can't hoist an instruction defining a physreg that is clobbered in
371 // the loop.
372 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000373 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000374 continue;
375 }
376
Evan Cheng058b9f02010-04-08 01:03:47 +0000377 if (!MO.isReg())
378 continue;
379 unsigned Reg = MO.getReg();
380 if (!Reg)
381 continue;
382 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
383 "Not expecting virtual register!");
384
Evan Cheng0a2aff22010-04-13 18:16:00 +0000385 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000386 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000387 // If it's using a non-loop-invariant register, then it's obviously not
388 // safe to hoist.
389 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000390 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000391 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000392
393 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000394 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
395 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000396 if (!MO.isDead())
397 // Non-dead implicit def? This cannot be hoisted.
398 RuledOut = true;
399 // No need to check if a dead implicit def is also defined by
400 // another instruction.
401 continue;
402 }
403
404 // FIXME: For now, avoid instructions with multiple defs, unless
405 // it's a dead implicit def.
406 if (Def)
407 RuledOut = true;
408 else
409 Def = Reg;
410
411 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000412 // register, then this is not safe. Two defs is indicated by setting a
413 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000414 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000415 if (PhysRegDefs.test(*AS))
416 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000417 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000418 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000419 if (PhysRegClobbers.test(Reg))
420 // MI defined register is seen defined by another instruction in
421 // the loop, it cannot be a LICM candidate.
422 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000423 }
424
Evan Cheng0a2aff22010-04-13 18:16:00 +0000425 // Only consider reloads for now and remats which do not have register
426 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000427 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000428 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000429 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000430 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000431 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000432 }
433}
434
Sanjay Patel87c6c072015-12-10 16:34:21 +0000435/// Walk the specified region of the CFG and hoist loop invariants out to the
436/// preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000437void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000438 MachineBasicBlock *Preheader = getCurPreheader();
439 if (!Preheader)
440 return;
441
Evan Cheng6ea59492010-04-07 00:41:17 +0000442 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000443 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
444 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000445
Evan Cheng058b9f02010-04-08 01:03:47 +0000446 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000447 SmallSet<int, 32> StoredFIs;
448
449 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000450 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000451 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000452 for (MachineBasicBlock *BB : Blocks) {
Bill Wendling918cea22011-10-12 02:58:01 +0000453 // If the header of the loop containing this basic block is a landing pad,
454 // then don't try to hoist instructions out of this loop.
455 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000456 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000457
Evan Cheng6ea59492010-04-07 00:41:17 +0000458 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000459 // FIXME: That means a reload that're reused in successor block(s) will not
460 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000461 for (const auto &LI : BB->liveins()) {
462 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000463 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000464 }
465
Evan Chengf192ca02011-10-11 23:48:44 +0000466 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000467 for (MachineInstr &MI : *BB)
468 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000469 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000470
Evan Cheng7fede872012-03-27 01:50:58 +0000471 // Gather the registers read / clobbered by the terminator.
472 BitVector TermRegs(NumRegs);
473 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
474 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000475 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000476 if (!MO.isReg())
477 continue;
478 unsigned Reg = MO.getReg();
479 if (!Reg)
480 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000481 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
482 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000483 }
484 }
485
Evan Cheng6ea59492010-04-07 00:41:17 +0000486 // Now evaluate whether the potential candidates qualify.
487 // 1. Check if the candidate defined register is defined by another
488 // instruction in the loop.
489 // 2. If the candidate is a load from stack slot (always true for now),
490 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000491 // 3. Make sure candidate def should not clobber
492 // registers read by the terminator. Similarly its def should not be
493 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000494 for (CandidateInfo &Candidate : Candidates) {
495 if (Candidate.FI != INT_MIN &&
496 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000497 continue;
498
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000499 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000500 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000501 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000502 MachineInstr *MI = Candidate.MI;
503 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000504 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000505 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000506 unsigned Reg = MO.getReg();
507 if (PhysRegDefs.test(Reg) ||
508 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000509 // If it's using a non-loop-invariant register, then it's obviously
510 // not safe to hoist.
511 Safe = false;
512 break;
513 }
514 }
515 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000516 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000517 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000518 }
519}
520
Sanjay Patel87c6c072015-12-10 16:34:21 +0000521/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
522/// sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000523void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000524 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000525 for (MachineBasicBlock *BB : Blocks) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000526 if (!BB->isLiveIn(Reg))
527 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000528 for (MachineInstr &MI : *BB) {
529 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000530 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
531 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
532 MO.setIsKill(false);
533 }
534 }
535 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000536}
537
Sanjay Patel87c6c072015-12-10 16:34:21 +0000538/// When an instruction is found to only use loop invariant operands that is
539/// safe to hoist, this instruction is called to do the dirty work.
Evan Cheng058b9f02010-04-08 01:03:47 +0000540void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000541 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000542
Evan Cheng6ea59492010-04-07 00:41:17 +0000543 // Now move the instructions to the predecessor, inserting it before any
544 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000545 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
546 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000547
548 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000549 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000550 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000551
Andrew Trick5209c732012-02-08 21:23:00 +0000552 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000553 // loop invariant must be kept live throughout the whole loop. This is
554 // important to ensure later passes do not scavenge the def register.
555 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000556
557 ++NumPostRAHoisted;
558 Changed = true;
559}
560
Sanjay Patel87c6c072015-12-10 16:34:21 +0000561/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
562/// may not be safe to hoist.
Devang Patel453d4012011-10-11 18:09:58 +0000563bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000564 if (SpeculationState != SpeculateUnknown)
565 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000566
Devang Patel453d4012011-10-11 18:09:58 +0000567 if (BB != CurLoop->getHeader()) {
568 // Check loop exiting blocks.
569 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
570 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000571 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
572 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000573 SpeculationState = SpeculateTrue;
574 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000575 }
576 }
577
Evan Chengf192ca02011-10-11 23:48:44 +0000578 SpeculationState = SpeculateFalse;
579 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000580}
581
Pete Cooper1eed5b52011-12-22 02:05:40 +0000582void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
Justin Lebarf6f4a2a2016-05-23 18:56:07 +0000583 DEBUG(dbgs() << "Entering BB#" << MBB->getNumber() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000584
Pete Cooper1eed5b52011-12-22 02:05:40 +0000585 // Remember livein register pressure.
586 BackTrace.push_back(RegPressure);
587}
Bill Wendling918cea22011-10-12 02:58:01 +0000588
Pete Cooper1eed5b52011-12-22 02:05:40 +0000589void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
Justin Lebarf6f4a2a2016-05-23 18:56:07 +0000590 DEBUG(dbgs() << "Exiting BB#" << MBB->getNumber() << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000591 BackTrace.pop_back();
592}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000593
Sanjay Patel87c6c072015-12-10 16:34:21 +0000594/// Destroy scope for the MBB that corresponds to the given dominator tree node
595/// if its a leaf or all of its children are done. Walk up the dominator tree to
596/// destroy ancestors which are now done.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000597void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000598 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
599 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000600 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000601 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000602
Pete Cooper1eed5b52011-12-22 02:05:40 +0000603 // Pop scope.
604 ExitScope(Node->getBlock());
605
606 // Now traverse upwards to pop ancestors whose offsprings are all done.
607 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
608 unsigned Left = --OpenChildren[Parent];
609 if (Left != 0)
610 break;
611 ExitScope(Parent->getBlock());
612 Node = Parent;
613 }
614}
615
Sanjay Patel87c6c072015-12-10 16:34:21 +0000616/// Walk the specified loop in the CFG (defined by all blocks dominated by the
617/// specified header block, and that are in the current loop) in depth first
618/// order w.r.t the DominatorTree. This allows us to visit definitions before
619/// uses, allowing us to hoist a loop body in one pass without iteration.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000620///
621void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000622 MachineBasicBlock *Preheader = getCurPreheader();
623 if (!Preheader)
624 return;
625
Pete Cooper1eed5b52011-12-22 02:05:40 +0000626 SmallVector<MachineDomTreeNode*, 32> Scopes;
627 SmallVector<MachineDomTreeNode*, 8> WorkList;
628 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
629 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
630
631 // Perform a DFS walk to determine the order of visit.
632 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000633 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000634 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000635 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000636 MachineBasicBlock *BB = Node->getBlock();
637
638 // If the header of the loop containing this basic block is a landing pad,
639 // then don't try to hoist instructions out of this loop.
640 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000641 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000642 continue;
643
644 // If this subregion is not in the top level loop at all, exit.
645 if (!CurLoop->contains(BB))
646 continue;
647
648 Scopes.push_back(Node);
649 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
650 unsigned NumChildren = Children.size();
651
652 // Don't hoist things out of a large switch statement. This often causes
653 // code to be hoisted that wasn't going to be executed, and increases
654 // register pressure in a situation where it's likely to matter.
655 if (BB->succ_size() >= 25)
656 NumChildren = 0;
657
658 OpenChildren[Node] = NumChildren;
659 // Add children in reverse order as then the next popped worklist node is
660 // the first child of this node. This means we ultimately traverse the
661 // DOM tree in exactly the same order as if we'd recursed.
662 for (int i = (int)NumChildren-1; i >= 0; --i) {
663 MachineDomTreeNode *Child = Children[i];
664 ParentMap[Child] = Node;
665 WorkList.push_back(Child);
666 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000667 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000668
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000669 if (Scopes.size() == 0)
670 return;
671
672 // Compute registers which are livein into the loop headers.
673 RegSeen.clear();
674 BackTrace.clear();
675 InitRegPressure(Preheader);
676
Pete Cooper1eed5b52011-12-22 02:05:40 +0000677 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000678 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000679 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000680
Pete Cooper1eed5b52011-12-22 02:05:40 +0000681 EnterScope(MBB);
682
683 // Process the block
684 SpeculationState = SpeculateUnknown;
685 for (MachineBasicBlock::iterator
686 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
687 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
688 MachineInstr *MI = &*MII;
689 if (!Hoist(MI, Preheader))
690 UpdateRegPressure(MI);
691 MII = NextMII;
692 }
693
694 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
695 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000696 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000697}
698
Sanjay Patel87c6c072015-12-10 16:34:21 +0000699/// Sink instructions into loops if profitable. This especially tries to prevent
700/// register spills caused by register pressure if there is little to no
701/// overhead moving instructions into loops.
Daniel Jasper15e69542015-03-14 10:58:38 +0000702void MachineLICM::SinkIntoLoop() {
703 MachineBasicBlock *Preheader = getCurPreheader();
704 if (!Preheader)
705 return;
706
707 SmallVector<MachineInstr *, 8> Candidates;
708 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
709 I != Preheader->instr_end(); ++I) {
710 // We need to ensure that we can safely move this instruction into the loop.
711 // 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 +0000712 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
713 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000714 }
715
716 for (MachineInstr *I : Candidates) {
717 const MachineOperand &MO = I->getOperand(0);
718 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
719 continue;
720 if (!MRI->hasOneDef(MO.getReg()))
721 continue;
722 bool CanSink = true;
723 MachineBasicBlock *B = nullptr;
724 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
725 // FIXME: Come up with a proper cost model that estimates whether sinking
726 // the instruction (and thus possibly executing it on every loop
727 // iteration) is more expensive than a register.
728 // For now assumes that copies are cheap and thus almost always worth it.
729 if (!MI.isCopy()) {
730 CanSink = false;
731 break;
732 }
733 if (!B) {
734 B = MI.getParent();
735 continue;
736 }
737 B = DT->findNearestCommonDominator(B, MI.getParent());
738 if (!B) {
739 CanSink = false;
740 break;
741 }
742 }
743 if (!CanSink || !B || B == Preheader)
744 continue;
745 B->splice(B->getFirstNonPHI(), Preheader, I);
746 }
747}
748
Evan Cheng87066f02010-10-20 22:03:58 +0000749static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
750 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
751}
752
Sanjay Patel87c6c072015-12-10 16:34:21 +0000753/// Find all virtual register references that are liveout of the preheader to
754/// initialize the starting "register pressure". Note this does not count live
755/// through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000756void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000757 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000758
Evan Cheng87066f02010-10-20 22:03:58 +0000759 // If the preheader has only a single predecessor and it ends with a
760 // fallthrough or an unconditional branch, then scan its predecessor for live
761 // defs as well. This happens whenever the preheader is created by splitting
762 // the critical edge from the loop predecessor to the loop header.
763 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000764 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000765 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000766 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000767 InitRegPressure(*BB->pred_begin());
768 }
769
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000770 for (const MachineInstr &MI : *BB)
771 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000772}
773
Sanjay Patel87c6c072015-12-10 16:34:21 +0000774/// Update estimate of register pressure after the specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000775void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
776 bool ConsiderUnseenAsDef) {
777 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000778 for (const auto &RPIdAndCost : Cost) {
779 unsigned Class = RPIdAndCost.first;
780 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000781 RegPressure[Class] = 0;
782 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000783 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000784 }
785}
Evan Chengd62719c2010-10-14 01:16:09 +0000786
Sanjay Patel87c6c072015-12-10 16:34:21 +0000787/// Calculate the additional register pressure that the registers used in MI
788/// cause.
789///
790/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
791/// figure out which usages are live-ins.
792/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000793DenseMap<unsigned, int>
794MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
795 bool ConsiderUnseenAsDef) {
796 DenseMap<unsigned, int> Cost;
797 if (MI->isImplicitDef())
798 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000799 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000801 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000802 continue;
803 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000804 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000805 continue;
806
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000807 // FIXME: It seems bad to use RegSeen only for some of these calculations.
808 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000809 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
810
811 RegClassWeight W = TRI->getRegClassWeight(RC);
812 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000813 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000814 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000815 else {
816 bool isKill = isOperandKill(MO, MRI);
817 if (isNew && !isKill && ConsiderUnseenAsDef)
818 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000819 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000820 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000821 RCCost = -W.RegWeight;
822 }
823 if (RCCost == 0)
824 continue;
825 const int *PS = TRI->getRegClassPressureSets(RC);
826 for (; *PS != -1; ++PS) {
827 if (Cost.find(*PS) == Cost.end())
828 Cost[*PS] = RCCost;
829 else
830 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000831 }
Evan Chengd62719c2010-10-14 01:16:09 +0000832 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000833 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000834}
835
Sanjay Patel87c6c072015-12-10 16:34:21 +0000836/// Return true if this machine instruction loads from global offset table or
837/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000838static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000839 assert (MI.mayLoad() && "Expected MI that loads!");
Philip Reames42bd26f2015-12-23 17:05:57 +0000840
841 // If we lost memory operands, conservatively assume that the instruction
842 // reads from everything..
843 if (MI.memoperands_empty())
844 return true;
845
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000846 for (MachineMemOperand *MemOp : MI.memoperands())
847 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000848 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000849 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000850
Devang Patel69a45652011-10-17 17:35:01 +0000851 return false;
852}
853
Sanjay Patel87c6c072015-12-10 16:34:21 +0000854/// Returns true if the instruction may be a suitable candidate for LICM.
855/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000856bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000857 // Check if it's safe to move the instruction.
858 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000859 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000860 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000861
862 // If it is load then check if it is guaranteed to execute by making sure that
863 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000864 // the loop which does not execute this load, so we can't hoist it. Loads
865 // from constant memory are not safe to speculate all the time, for example
866 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000867 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000868 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000869 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000870 return false;
871
Evan Cheng0a2aff22010-04-13 18:16:00 +0000872 return true;
873}
874
Sanjay Patel87c6c072015-12-10 16:34:21 +0000875/// Returns true if the instruction is loop invariant.
876/// I.e., all virtual register operands are defined outside of the loop,
877/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +0000878/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000879///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000880bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
881 if (!IsLICMCandidate(I))
882 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000883
Bill Wendling70613b82008-05-12 19:38:32 +0000884 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000885 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000886 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000887 continue;
888
Dan Gohman79618d12009-01-15 22:01:38 +0000889 unsigned Reg = MO.getReg();
890 if (Reg == 0) continue;
891
892 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000893 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000894 if (MO.isUse()) {
895 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000896 // and we can freely move its uses. Alternatively, if it's allocatable,
897 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000898 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000899 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000900 // Otherwise it's safe to move.
901 continue;
902 } else if (!MO.isDead()) {
903 // A def that isn't dead. We can't move it.
904 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000905 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
906 // If the reg is live into the loop, we can't hoist an instruction
907 // which would clobber it.
908 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000909 }
910 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000911
912 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000913 continue;
914
Evan Chengd62719c2010-10-14 01:16:09 +0000915 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000916 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000917
918 // If the loop contains the definition of an operand, then the instruction
919 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000920 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000921 return false;
922 }
923
924 // If we got this far, the instruction is loop invariant!
925 return true;
926}
927
Evan Cheng399660c2009-02-05 08:45:46 +0000928
Sanjay Patel87c6c072015-12-10 16:34:21 +0000929/// Return true if the specified instruction is used by a phi node and hoisting
930/// it could cause a copy to be inserted.
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000931bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
932 SmallVector<const MachineInstr*, 8> Work(1, MI);
933 do {
934 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +0000935 for (const MachineOperand &MO : MI->operands()) {
936 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000937 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000938 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000939 if (!TargetRegisterInfo::isVirtualRegister(Reg))
940 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000941 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000942 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000943 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000944 // A PHI inside the loop causes a copy because the live range of Reg is
945 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000946 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000947 return true;
948 // A PHI in an exit block can cause a copy to be inserted if the PHI
949 // has multiple predecessors in the loop with different values.
950 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000951 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000952 return true;
953 continue;
954 }
955 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000956 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
957 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000958 }
Evan Chengef42bea2011-04-11 21:09:18 +0000959 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000960 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +0000961 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000962}
963
Sanjay Patel87c6c072015-12-10 16:34:21 +0000964/// Compute operand latency between a def of 'Reg' and an use in the current
965/// loop, return true if the target considered it high.
Evan Cheng63c76082010-10-19 18:58:51 +0000966bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +0000967 unsigned DefIdx, unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +0000968 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +0000969 return false;
Evan Chengd62719c2010-10-14 01:16:09 +0000970
Owen Andersonb36376e2014-03-17 19:36:09 +0000971 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
972 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +0000973 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000974 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +0000975 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000976 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
977 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +0000978 if (!MO.isReg() || !MO.isUse())
979 continue;
980 unsigned MOReg = MO.getReg();
981 if (MOReg != Reg)
982 continue;
983
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000984 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +0000985 return true;
Evan Chengd62719c2010-10-14 01:16:09 +0000986 }
987
Evan Cheng63c76082010-10-19 18:58:51 +0000988 // Only look at the first in loop use.
989 break;
Evan Chengd62719c2010-10-14 01:16:09 +0000990 }
991
Evan Cheng63c76082010-10-19 18:58:51 +0000992 return false;
Evan Chengd62719c2010-10-14 01:16:09 +0000993}
994
Sanjay Patel87c6c072015-12-10 16:34:21 +0000995/// Return true if the instruction is marked "cheap" or the operand latency
996/// between its def and a use is one or less.
Evan Chenge96b8d72010-10-26 02:08:50 +0000997bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000998 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +0000999 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001000
1001 bool isCheap = false;
1002 unsigned NumDefs = MI.getDesc().getNumDefs();
1003 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1004 MachineOperand &DefMO = MI.getOperand(i);
1005 if (!DefMO.isReg() || !DefMO.isDef())
1006 continue;
1007 --NumDefs;
1008 unsigned Reg = DefMO.getReg();
1009 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1010 continue;
1011
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001012 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001013 return false;
1014 isCheap = true;
1015 }
1016
1017 return isCheap;
1018}
1019
Sanjay Patel87c6c072015-12-10 16:34:21 +00001020/// Visit BBs from header to current BB, check if hoisting an instruction of the
1021/// given cost matrix can cause high register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +00001022bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001023 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001024 for (const auto &RPIdAndCost : Cost) {
1025 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001026 continue;
1027
Daniel Jasper274928f2015-04-14 11:56:25 +00001028 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001029 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001030
1031 // Don't hoist cheap instructions if they would increase register pressure,
1032 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001033 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001034 return true;
1035
Daniel Jasperefece522015-04-03 16:19:48 +00001036 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001037 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001038 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001039 }
1040
1041 return false;
1042}
1043
Sanjay Patel87c6c072015-12-10 16:34:21 +00001044/// Traverse the back trace from header to the current block and update their
1045/// register pressures to reflect the effect of hoisting MI from the current
1046/// block to the preheader.
Evan Cheng87066f02010-10-20 22:03:58 +00001047void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001048 // First compute the 'cost' of the instruction, i.e. its contribution
1049 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001050 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1051 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001052
1053 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001054 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001055 for (const auto &RPIdAndCost : Cost)
1056 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001057}
1058
Sanjay Patel87c6c072015-12-10 16:34:21 +00001059/// Return true if it is potentially profitable to hoist the given loop
1060/// invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001061bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001062 if (MI.isImplicitDef())
1063 return true;
1064
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001065 // Besides removing computation from the loop, hoisting an instruction has
1066 // these effects:
1067 //
1068 // - The value defined by the instruction becomes live across the entire
1069 // loop. This increases register pressure in the loop.
1070 //
1071 // - If the value is used by a PHI in the loop, a copy will be required for
1072 // lowering the PHI after extending the live range.
1073 //
1074 // - When hoisting the last use of a value in the loop, that value no longer
1075 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001076
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001077 bool CheapInstr = IsCheapInstruction(MI);
1078 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001079
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001080 // Don't hoist a cheap instruction if it would create a copy in the loop.
1081 if (CheapInstr && CreatesCopy) {
1082 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1083 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001084 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001085
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001086 // Rematerializable instructions should always be hoisted since the register
1087 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001088 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001089 return true;
1090
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001091 // FIXME: If there are long latency loop-invariant instructions inside the
1092 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001093 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1094 const MachineOperand &MO = MI.getOperand(i);
1095 if (!MO.isReg() || MO.isImplicit())
1096 continue;
1097 unsigned Reg = MO.getReg();
1098 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1099 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001100 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1101 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1102 ++NumHighLatency;
1103 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001104 }
1105 }
1106
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001107 // Estimate register pressure to determine whether to LICM the instruction.
1108 // In low register pressure situation, we can be more aggressive about
1109 // hoisting. Also, favors hoisting long latency instructions even in
1110 // moderately high pressure situation.
1111 // Cheap instructions will only be hoisted if they don't increase register
1112 // pressure at all.
1113 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1114 /*ConsiderUnseenAsDef=*/false);
1115
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001116 // Visit BBs from header to current BB, if hoisting this doesn't cause
1117 // high register pressure, then it's safe to proceed.
1118 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1119 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1120 ++NumLowRP;
1121 return true;
1122 }
1123
1124 // Don't risk increasing register pressure if it would create copies.
1125 if (CreatesCopy) {
1126 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001127 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001128 }
1129
1130 // Do not "speculate" in high register pressure situation. If an
1131 // instruction is not guaranteed to be executed in the loop, it's best to be
1132 // conservative.
1133 if (AvoidSpeculation &&
1134 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1135 DEBUG(dbgs() << "Won't speculate: " << MI);
1136 return false;
1137 }
1138
1139 // High register pressure situation, only hoist if the instruction is going
1140 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001141 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1142 !MI.isDereferenceableInvariantLoad(AA)) {
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001143 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1144 return false;
1145 }
Evan Cheng399660c2009-02-05 08:45:46 +00001146
1147 return true;
1148}
1149
Sanjay Patel87c6c072015-12-10 16:34:21 +00001150/// Unfold a load from the given machineinstr if the load itself could be
1151/// hoisted. Return the unfolded and hoistable load, or null if the load
1152/// couldn't be unfolded or if it wouldn't be hoistable.
Dan Gohman104f57c2009-10-29 17:47:20 +00001153MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001154 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001155 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001156 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001157
Dan Gohman104f57c2009-10-29 17:47:20 +00001158 // If not, we may be able to unfold a load and hoist that.
1159 // First test whether the instruction is loading from an amenable
1160 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001161 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001162 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001163
Dan Gohman104f57c2009-10-29 17:47:20 +00001164 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001165 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001166 unsigned NewOpc =
1167 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1168 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001169 /*UnfoldStore=*/false,
1170 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001171 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001172 const MCInstrDesc &MID = TII->get(NewOpc);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001173 MachineFunction &MF = *MI->getParent()->getParent();
1174 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001175 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001176 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001177
Dan Gohman104f57c2009-10-29 17:47:20 +00001178 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001179 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1180 /*UnfoldLoad=*/true,
1181 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001182 (void)Success;
1183 assert(Success &&
1184 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1185 "succeeded!");
1186 assert(NewMIs.size() == 2 &&
1187 "Unfolded a load into multiple instructions!");
1188 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001189 MachineBasicBlock::iterator Pos = MI;
1190 MBB->insert(Pos, NewMIs[0]);
1191 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001192 // If unfolding produced a load that wasn't loop-invariant or profitable to
1193 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001194 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001195 NewMIs[0]->eraseFromParent();
1196 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001197 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001198 }
Evan Cheng87066f02010-10-20 22:03:58 +00001199
1200 // Update register pressure for the unfolded instruction.
1201 UpdateRegPressure(NewMIs[1]);
1202
Dan Gohman104f57c2009-10-29 17:47:20 +00001203 // Otherwise we successfully unfolded a load that we can hoist.
1204 MI->eraseFromParent();
1205 return NewMIs[0];
1206}
1207
Sanjay Patel87c6c072015-12-10 16:34:21 +00001208/// Initialize the CSE map with instructions that are in the current loop
1209/// preheader that may become duplicates of instructions that are hoisted
1210/// out of the loop.
Evan Chengf42b5af2009-11-03 21:40:02 +00001211void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001212 for (MachineInstr &MI : *BB)
1213 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001214}
1215
Sanjay Patel87c6c072015-12-10 16:34:21 +00001216/// Find an instruction amount PrevMIs that is a duplicate of MI.
1217/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001218const MachineInstr*
1219MachineLICM::LookForDuplicate(const MachineInstr *MI,
1220 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001221 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001222 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001223 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001224
Craig Topperc0196b12014-04-14 00:51:57 +00001225 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001226}
1227
Sanjay Patel87c6c072015-12-10 16:34:21 +00001228/// Given a LICM'ed instruction, look for an instruction on the preheader that
1229/// computes the same value. If it's found, do a RAU on with the definition of
1230/// the existing instruction rather than hoisting the instruction to the
1231/// preheader.
Evan Cheng921152f2009-11-05 00:51:13 +00001232bool MachineLICM::EliminateCSE(MachineInstr *MI,
1233 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001234 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1235 // the undef property onto uses.
1236 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001237 return false;
1238
1239 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001240 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001241
1242 // Replace virtual registers defined by MI by their counterparts defined
1243 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001244 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001245 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1246 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001247
1248 // Physical registers may not differ here.
1249 assert((!MO.isReg() || MO.getReg() == 0 ||
1250 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1251 MO.getReg() == Dup->getOperand(i).getReg()) &&
1252 "Instructions with different phys regs are not identical!");
1253
1254 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001255 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1256 Defs.push_back(i);
1257 }
1258
1259 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1260 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1261 unsigned Idx = Defs[i];
1262 unsigned Reg = MI->getOperand(Idx).getReg();
1263 unsigned DupReg = Dup->getOperand(Idx).getReg();
1264 OrigRCs.push_back(MRI->getRegClass(DupReg));
1265
1266 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1267 // Restore old RCs if more than one defs.
1268 for (unsigned j = 0; j != i; ++j)
1269 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1270 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001271 }
Evan Cheng921152f2009-11-05 00:51:13 +00001272 }
Evan Chengaa563df2011-10-17 19:50:12 +00001273
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001274 for (unsigned Idx : Defs) {
Evan Chengaa563df2011-10-17 19:50:12 +00001275 unsigned Reg = MI->getOperand(Idx).getReg();
1276 unsigned DupReg = Dup->getOperand(Idx).getReg();
1277 MRI->replaceRegWith(Reg, DupReg);
1278 MRI->clearKillFlags(DupReg);
1279 }
1280
Evan Cheng7ff83192009-11-07 03:52:02 +00001281 MI->eraseFromParent();
1282 ++NumCSEed;
1283 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001284 }
1285 return false;
1286}
1287
Sanjay Patel87c6c072015-12-10 16:34:21 +00001288/// Return true if the given instruction will be CSE'd if it's hoisted out of
1289/// the loop.
Evan Chengaf138952011-10-12 00:09:14 +00001290bool MachineLICM::MayCSE(MachineInstr *MI) {
1291 unsigned Opcode = MI->getOpcode();
1292 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1293 CI = CSEMap.find(Opcode);
1294 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1295 // the undef property onto uses.
1296 if (CI == CSEMap.end() || MI->isImplicitDef())
1297 return false;
1298
Craig Topperc0196b12014-04-14 00:51:57 +00001299 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001300}
1301
Sanjay Patel87c6c072015-12-10 16:34:21 +00001302/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001303/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001304/// It returns true if the instruction is hoisted.
Evan Cheng87066f02010-10-20 22:03:58 +00001305bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001306 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001307 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001308 // If not, try unfolding a hoistable load.
1309 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001310 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001311 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001312
Dan Gohman79618d12009-01-15 22:01:38 +00001313 // Now move the instructions to the predecessor, inserting it before any
1314 // terminator instructions.
1315 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001316 dbgs() << "Hoisting " << *MI;
Dan Gohman1b44f102009-10-28 03:21:57 +00001317 if (MI->getParent()->getBasicBlock())
Justin Lebarf6f4a2a2016-05-23 18:56:07 +00001318 dbgs() << " from BB#" << MI->getParent()->getNumber();
1319 if (Preheader->getBasicBlock())
1320 dbgs() << " to BB#" << Preheader->getNumber();
David Greene55cf95c2010-01-05 00:03:48 +00001321 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001322 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001323
Evan Chengf42b5af2009-11-03 21:40:02 +00001324 // If this is the first instruction being hoisted to the preheader,
1325 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001326 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001327 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001328 FirstInLoop = false;
1329 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001330
Evan Cheng399660c2009-02-05 08:45:46 +00001331 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001332 unsigned Opcode = MI->getOpcode();
1333 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1334 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001335 if (!EliminateCSE(MI, CI)) {
1336 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001337 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001338
Evan Cheng87066f02010-10-20 22:03:58 +00001339 // Update register pressure for BBs from header to this block.
1340 UpdateBackTraceRegPressure(MI);
1341
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001342 // Clear the kill flags of any register this instruction defines,
1343 // since they may need to be live throughout the entire loop
1344 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001345 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001346 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001347 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001348
Evan Cheng399660c2009-02-05 08:45:46 +00001349 // Add to the CSE map.
1350 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001351 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001352 else
1353 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001354 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001355
Dan Gohman79618d12009-01-15 22:01:38 +00001356 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001357 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001358
1359 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001360}
Dan Gohman3570f812010-06-22 17:25:57 +00001361
Sanjay Patel87c6c072015-12-10 16:34:21 +00001362/// Get the preheader for the current loop, splitting a critical edge if needed.
Dan Gohman3570f812010-06-22 17:25:57 +00001363MachineBasicBlock *MachineLICM::getCurPreheader() {
1364 // Determine the block to which to hoist instructions. If we can't find a
1365 // suitable loop predecessor, we can't do any hoisting.
1366
1367 // If we've tried to get a preheader and failed, don't try again.
1368 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001369 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001370
1371 if (!CurPreheader) {
1372 CurPreheader = CurLoop->getLoopPreheader();
1373 if (!CurPreheader) {
1374 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1375 if (!Pred) {
1376 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001377 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001378 }
1379
Quentin Colombet23341a82016-04-21 21:01:13 +00001380 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001381 if (!CurPreheader) {
1382 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001383 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001384 }
1385 }
1386 }
1387 return CurPreheader;
1388}