blob: 58fd1f23842060aebc302c18bc22af7c923b3176 [file] [log] [blame]
Eugene Zelenko38409752017-09-22 23:46:57 +00001//===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
Bill Wendling0f940c92007-12-07 21:42:31 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// This pass 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 Wendling0f940c92007-12-07 21:42:31 +000017//===----------------------------------------------------------------------===//
18
Eugene Zelenko38409752017-09-22 23:46:57 +000019#include "llvm/ADT/BitVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/ADT/SmallSet.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000023#include "llvm/ADT/SmallVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000032#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000033#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000034#include "llvm/CodeGen/MachineOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000036#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikie48319232017-11-08 01:01:31 +000037#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
39#include "llvm/CodeGen/TargetRegisterInfo.h"
Matthias Braun6fee0b02015-06-13 03:42:11 +000040#include "llvm/CodeGen/TargetSchedule.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000042#include "llvm/IR/DebugLoc.h"
43#include "llvm/MC/MCInstrDesc.h"
44#include "llvm/MC/MCRegisterInfo.h"
45#include "llvm/Pass.h"
46#include "llvm/Support/Casting.h"
Evan Cheng7007e4c2011-10-12 21:33:49 +000047#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000048#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38409752017-09-22 23:46:57 +000050#include <algorithm>
51#include <cassert>
52#include <limits>
53#include <vector>
54
Bill Wendling0f940c92007-12-07 21:42:31 +000055using namespace llvm;
56
Matthias Braun94c49042017-05-25 21:26:32 +000057#define DEBUG_TYPE "machinelicm"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000058
Evan Cheng7007e4c2011-10-12 21:33:49 +000059static cl::opt<bool>
60AvoidSpeculation("avoid-speculation",
61 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73b5bb32011-10-26 01:26:57 +000062 cl::init(true), cl::Hidden);
Evan Cheng7007e4c2011-10-12 21:33:49 +000063
Hal Finkel9d1500e2015-01-08 22:10:48 +000064static cl::opt<bool>
65HoistCheapInsts("hoist-cheap-insts",
66 cl::desc("MachineLICM should hoist even cheap instructions"),
67 cl::init(false), cl::Hidden);
68
Daniel Jasper439cc2c2015-03-14 10:58:38 +000069static cl::opt<bool>
70SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
71 cl::desc("MachineLICM should sink instructions into "
72 "loops to avoid register spills"),
73 cl::init(false), cl::Hidden);
Zaara Syeda4561f7d2018-03-23 15:28:15 +000074static cl::opt<bool>
75HoistConstStores("hoist-const-stores",
76 cl::desc("Hoist invariant stores"),
Zaara Syedadbec9f72018-04-09 14:50:02 +000077 cl::init(true), cl::Hidden);
Daniel Jasper439cc2c2015-03-14 10:58:38 +000078
Evan Cheng03a9fdf2010-10-16 02:20:26 +000079STATISTIC(NumHoisted,
80 "Number of machine instructions hoisted out of loops");
81STATISTIC(NumLowRP,
82 "Number of instructions hoisted in low reg pressure situation");
83STATISTIC(NumHighLatency,
84 "Number of high latency instructions hoisted");
85STATISTIC(NumCSEed,
86 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000087STATISTIC(NumPostRAHoisted,
88 "Number of machine instructions hoisted out of loops post regalloc");
Zaara Syeda4561f7d2018-03-23 15:28:15 +000089STATISTIC(NumStoreConst,
90 "Number of stores of const phys reg hoisted out of loops");
Bill Wendlingb48519c2007-12-08 01:47:01 +000091
Bill Wendling0f940c92007-12-07 21:42:31 +000092namespace {
Eugene Zelenko38409752017-09-22 23:46:57 +000093
Matthias Braun09008362018-01-19 06:46:10 +000094 class MachineLICMBase : public MachineFunctionPass {
Bill Wendlingefe2be72007-12-11 23:27:51 +000095 const TargetInstrInfo *TII;
Benjamin Kramer69e42db2013-01-11 20:05:37 +000096 const TargetLoweringBase *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000097 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000098 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000099 MachineRegisterInfo *MRI;
Matthias Braun6fee0b02015-06-13 03:42:11 +0000100 TargetSchedModel SchedModel;
Matthias Braun09008362018-01-19 06:46:10 +0000101 bool PreRegAlloc;
Bill Wendling12ebf142007-12-11 19:40:06 +0000102
Bill Wendling0f940c92007-12-07 21:42:31 +0000103 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +0000104 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000105 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000106 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000107
Bill Wendling0f940c92007-12-07 21:42:31 +0000108 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000109 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000110 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000111 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +0000112 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +0000113
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000114 // Exit blocks for CurLoop.
Eugene Zelenko38409752017-09-22 23:46:57 +0000115 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000116
117 bool isExitBlock(const MachineBasicBlock *MBB) const {
David Majnemer975248e2016-08-11 22:21:41 +0000118 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000119 }
120
Evan Cheng0e673912010-10-14 01:16:09 +0000121 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000122 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +0000123 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000124
Daniel Jasper6c456f02015-04-14 11:56:25 +0000125 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000126 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +0000127 SmallVector<unsigned, 8> RegLimit;
128
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000129 // Register pressure on path leading from loop preheader to current BB.
130 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
131
Dale Johannesenc46a5f22010-07-29 17:45:24 +0000132 // For each opcode, keep a list of potential CSE instructions.
Eugene Zelenko38409752017-09-22 23:46:57 +0000133 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +0000134
Evan Chengfad62872011-10-11 23:48:44 +0000135 enum {
136 SpeculateFalse = 0,
137 SpeculateTrue = 1,
138 SpeculateUnknown = 2
139 };
140
Devang Patel2e350472011-10-11 18:09:58 +0000141 // If a MBB does not dominate loop exiting blocks then it may not safe
142 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000143 // Tri-state: 0 - false, 1 - true, 2 - unknown
144 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000145
Bill Wendling0f940c92007-12-07 21:42:31 +0000146 public:
Matthias Braun09008362018-01-19 06:46:10 +0000147 MachineLICMBase(char &PassID, bool PreRegAlloc)
148 : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
Bill Wendling0f940c92007-12-07 21:42:31 +0000149
Craig Topper9f998de2014-03-07 09:26:03 +0000150 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendling0f940c92007-12-07 21:42:31 +0000151
Craig Topper9f998de2014-03-07 09:26:03 +0000152 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendling0f940c92007-12-07 21:42:31 +0000153 AU.addRequired<MachineLoopInfo>();
154 AU.addRequired<MachineDominatorTree>();
Chandler Carruth91468332015-09-09 17:55:00 +0000155 AU.addRequired<AAResultsWrapperPass>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000156 AU.addPreserved<MachineLoopInfo>();
157 AU.addPreserved<MachineDominatorTree>();
158 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000159 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000160
Craig Topper9f998de2014-03-07 09:26:03 +0000161 void releaseMemory() override {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000162 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000163 RegPressure.clear();
164 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000165 BackTrace.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000166 CSEMap.clear();
167 }
168
Bill Wendling0f940c92007-12-07 21:42:31 +0000169 private:
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000170 /// Keep track of information about hoisting candidates.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000171 struct CandidateInfo {
172 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000173 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000174 int FI;
Eugene Zelenko38409752017-09-22 23:46:57 +0000175
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000176 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
177 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000178 };
179
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000180 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000181
Evan Cheng4038f9c2010-04-08 01:03:47 +0000182 void HoistPostRA(MachineInstr *MI, unsigned Def);
183
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000184 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
185 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper9e639e82013-07-11 16:22:38 +0000186 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000187
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000188 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000189
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000190 bool IsLICMCandidate(MachineInstr &I);
191
Bill Wendling041b3f82007-12-08 23:58:46 +0000192 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000193
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000194 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengd67705f2011-04-11 21:09:18 +0000195
Evan Chengc8141df2010-10-26 02:08:50 +0000196 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
197 unsigned Reg) const;
198
199 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000200
Daniel Jasperefa23ae2015-04-03 16:19:48 +0000201 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
202 bool Cheap);
Evan Cheng134982d2010-10-20 22:03:58 +0000203
Evan Cheng134982d2010-10-20 22:03:58 +0000204 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000205
Evan Chengc26abd92009-11-20 23:31:34 +0000206 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000207
Devang Patel2e350472011-10-11 18:09:58 +0000208 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
209
Pete Cooperacde91e2011-12-22 02:05:40 +0000210 void EnterScope(MachineBasicBlock *MBB);
211
212 void ExitScope(MachineBasicBlock *MBB);
213
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000214 void ExitScopeIfDone(
215 MachineDomTreeNode *Node,
216 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
217 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooperacde91e2011-12-22 02:05:40 +0000218
Fangrui Song7d882862018-07-16 18:51:40 +0000219 void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000220
Pete Cooperacde91e2011-12-22 02:05:40 +0000221 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000222
Daniel Jasper439cc2c2015-03-14 10:58:38 +0000223 void SinkIntoLoop();
224
Evan Cheng0e673912010-10-14 01:16:09 +0000225 void InitRegPressure(MachineBasicBlock *BB);
226
Daniel Jasper6221f412015-04-07 16:42:35 +0000227 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
228 bool ConsiderSeen,
229 bool ConsiderUnseenAsDef);
230
Daniel Jasper6221f412015-04-07 16:42:35 +0000231 void UpdateRegPressure(const MachineInstr *MI,
232 bool ConsiderUnseenAsDef = false);
Evan Cheng0e673912010-10-14 01:16:09 +0000233
Dan Gohman5c952302009-10-29 17:47:20 +0000234 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
235
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000236 const MachineInstr *
237 LookForDuplicate(const MachineInstr *MI,
238 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng78e5c112009-11-07 03:52:02 +0000239
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000240 bool EliminateCSE(
241 MachineInstr *MI,
242 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000243
Evan Cheng7efba852011-10-12 00:09:14 +0000244 bool MayCSE(MachineInstr *MI);
245
Evan Cheng134982d2010-10-20 22:03:58 +0000246 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000247
Evan Cheng777c6b72009-11-03 21:40:02 +0000248 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000249
Dan Gohman853d3fb2010-06-22 17:25:57 +0000250 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000251 };
Eugene Zelenko38409752017-09-22 23:46:57 +0000252
Matthias Braun09008362018-01-19 06:46:10 +0000253 class MachineLICM : public MachineLICMBase {
254 public:
255 static char ID;
256 MachineLICM() : MachineLICMBase(ID, false) {
257 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
258 }
259 };
260
261 class EarlyMachineLICM : public MachineLICMBase {
262 public:
263 static char ID;
264 EarlyMachineLICM() : MachineLICMBase(ID, true) {
265 initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
266 }
267 };
268
Bill Wendling0f940c92007-12-07 21:42:31 +0000269} // end anonymous namespace
270
Matthias Braun09008362018-01-19 06:46:10 +0000271char MachineLICM::ID;
272char EarlyMachineLICM::ID;
Eugene Zelenko38409752017-09-22 23:46:57 +0000273
Andrew Trick1dd8c852012-02-08 21:23:13 +0000274char &llvm::MachineLICMID = MachineLICM::ID;
Matthias Braun09008362018-01-19 06:46:10 +0000275char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
Eugene Zelenko38409752017-09-22 23:46:57 +0000276
Matthias Braun94c49042017-05-25 21:26:32 +0000277INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
278 "Machine Loop Invariant Code Motion", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000279INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
280INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth91468332015-09-09 17:55:00 +0000281INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun94c49042017-05-25 21:26:32 +0000282INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
283 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000284
Matthias Braun09008362018-01-19 06:46:10 +0000285INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
286 "Early Machine Loop Invariant Code Motion", false, false)
287INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
288INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
289INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
290INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
291 "Early Machine Loop Invariant Code Motion", false, false)
292
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000293/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman853d3fb2010-06-22 17:25:57 +0000294static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000295 // Check whether this loop even has a unique predecessor.
296 if (!CurLoop->getLoopPredecessor())
297 return false;
298 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000299 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000300 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000301 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000302 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000303 return true;
304}
305
Matthias Braun09008362018-01-19 06:46:10 +0000306bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
Matthias Braund3181392017-12-15 22:22:58 +0000307 if (skipFunction(MF.getFunction()))
Paul Robinson5fa58a52014-03-31 17:43:35 +0000308 return false;
309
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000310 Changed = FirstInLoop = false;
Matthias Braun6fee0b02015-06-13 03:42:11 +0000311 const TargetSubtargetInfo &ST = MF.getSubtarget();
312 TII = ST.getInstrInfo();
313 TLI = ST.getTargetLowering();
314 TRI = ST.getRegisterInfo();
Matthias Braunf79c57a2016-07-28 18:40:00 +0000315 MFI = &MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000316 MRI = &MF.getRegInfo();
Sanjay Patele599cea2018-04-08 19:56:04 +0000317 SchedModel.init(&ST);
Bill Wendling0f940c92007-12-07 21:42:31 +0000318
Andrew Trick9d41bd52012-02-08 21:23:03 +0000319 PreRegAlloc = MRI->isSSA();
320
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000321 if (PreRegAlloc)
Nicola Zaghen0818e782018-05-14 12:53:11 +0000322 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000323 else
Nicola Zaghen0818e782018-05-14 12:53:11 +0000324 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
325 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000326
Evan Cheng0e673912010-10-14 01:16:09 +0000327 if (PreRegAlloc) {
328 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper6c456f02015-04-14 11:56:25 +0000329 unsigned NumRPS = TRI->getNumRegPressureSets();
330 RegPressure.resize(NumRPS);
Evan Cheng0e673912010-10-14 01:16:09 +0000331 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper6c456f02015-04-14 11:56:25 +0000332 RegLimit.resize(NumRPS);
333 for (unsigned i = 0, e = NumRPS; i != e; ++i)
334 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Cheng0e673912010-10-14 01:16:09 +0000335 }
336
Bill Wendling0f940c92007-12-07 21:42:31 +0000337 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000338 MLI = &getAnalysis<MachineLoopInfo>();
339 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth91468332015-09-09 17:55:00 +0000340 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendling0f940c92007-12-07 21:42:31 +0000341
Dan Gohmanaa742602010-07-09 18:49:45 +0000342 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
343 while (!Worklist.empty()) {
344 CurLoop = Worklist.pop_back_val();
Craig Topper4ba84432014-04-14 00:51:57 +0000345 CurPreheader = nullptr;
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000346 ExitBlocks.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000347
Evan Cheng4038f9c2010-04-08 01:03:47 +0000348 // If this is done before regalloc, only visit outer-most preheader-sporting
349 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000350 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
351 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000352 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000353 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000354
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +0000355 CurLoop->getExitBlocks(ExitBlocks);
356
Evan Chengd94671a2010-04-07 00:41:17 +0000357 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000358 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000359 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000360 // CSEMap is initialized for loop header when the first instruction is
361 // being hoisted.
362 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000363 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000364 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000365 CSEMap.clear();
Daniel Jasper439cc2c2015-03-14 10:58:38 +0000366
367 if (SinkInstsToAvoidSpills)
368 SinkIntoLoop();
Evan Chengd94671a2010-04-07 00:41:17 +0000369 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000370 }
371
372 return Changed;
373}
374
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000375/// Return true if instruction stores to the specified frame.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000376static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Geoff Berry156f7612018-05-04 19:25:09 +0000377 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
378 // true since they have no memory operands.
379 if (!MI->mayStore())
380 return false;
Philip Reamesa79baf52015-12-23 17:05:57 +0000381 // If we lost memory operands, conservatively assume that the instruction
Michael Liao2238d782017-04-26 05:27:20 +0000382 // writes to all slots.
Philip Reamesa79baf52015-12-23 17:05:57 +0000383 if (MI->memoperands_empty())
384 return true;
Sanjay Patel3442ec92016-01-06 23:45:05 +0000385 for (const MachineMemOperand *MemOp : MI->memoperands()) {
386 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng4038f9c2010-04-08 01:03:47 +0000387 continue;
388 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel3442ec92016-01-06 23:45:05 +0000389 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000390 if (Value->getFrameIndex() == FI)
391 return true;
392 }
393 }
394 return false;
395}
396
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000397/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng4038f9c2010-04-08 01:03:47 +0000398/// gather register def and frame object update information.
Matthias Braun09008362018-01-19 06:46:10 +0000399void MachineLICMBase::ProcessMI(MachineInstr *MI,
400 BitVector &PhysRegDefs,
401 BitVector &PhysRegClobbers,
402 SmallSet<int, 32> &StoredFIs,
403 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000404 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000405 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000406 unsigned Def = 0;
Sanjay Patel3442ec92016-01-06 23:45:05 +0000407 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000408 if (MO.isFI()) {
409 // Remember if the instruction stores to the frame index.
410 int FI = MO.getIndex();
411 if (!StoredFIs.count(FI) &&
412 MFI->isSpillSlotObjectIndex(FI) &&
413 InstructionStoresToFI(MI, FI))
414 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000415 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000416 continue;
417 }
418
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000419 // We can't hoist an instruction defining a physreg that is clobbered in
420 // the loop.
421 if (MO.isRegMask()) {
Jakob Stoklund Olesen478a8a02012-02-02 23:52:57 +0000422 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000423 continue;
424 }
425
Evan Cheng4038f9c2010-04-08 01:03:47 +0000426 if (!MO.isReg())
427 continue;
428 unsigned Reg = MO.getReg();
429 if (!Reg)
430 continue;
431 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
432 "Not expecting virtual register!");
433
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000434 if (!MO.isDef()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000435 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000436 // If it's using a non-loop-invariant register, then it's obviously not
437 // safe to hoist.
438 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000439 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000440 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000441
442 if (MO.isImplicit()) {
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000443 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
444 PhysRegClobbers.set(*AI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000445 if (!MO.isDead())
446 // Non-dead implicit def? This cannot be hoisted.
447 RuledOut = true;
448 // No need to check if a dead implicit def is also defined by
449 // another instruction.
450 continue;
451 }
452
453 // FIXME: For now, avoid instructions with multiple defs, unless
454 // it's a dead implicit def.
455 if (Def)
456 RuledOut = true;
457 else
458 Def = Reg;
459
460 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000461 // register, then this is not safe. Two defs is indicated by setting a
462 // PhysRegClobbers bit.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000463 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000464 if (PhysRegDefs.test(*AS))
465 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000466 }
Craig Topper23084bd2018-12-05 03:41:26 +0000467 // Need a second loop because MCRegAliasIterator can visit the same
468 // register twice.
469 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
470 PhysRegDefs.set(*AS);
471
Richard Sandiford9608ed12013-08-20 09:11:13 +0000472 if (PhysRegClobbers.test(Reg))
473 // MI defined register is seen defined by another instruction in
474 // the loop, it cannot be a LICM candidate.
475 RuledOut = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000476 }
477
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000478 // Only consider reloads for now and remats which do not have register
479 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000480 if (Def && !RuledOut) {
Eugene Zelenko38409752017-09-22 23:46:57 +0000481 int FI = std::numeric_limits<int>::min();
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000482 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +0000483 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000484 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000485 }
486}
487
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000488/// Walk the specified region of the CFG and hoist loop invariants out to the
489/// preheader.
Matthias Braun09008362018-01-19 06:46:10 +0000490void MachineLICMBase::HoistRegionPostRA() {
Evan Chengd6c23552012-03-27 01:50:58 +0000491 MachineBasicBlock *Preheader = getCurPreheader();
492 if (!Preheader)
493 return;
494
Evan Chengd94671a2010-04-07 00:41:17 +0000495 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000496 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
497 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Chengd94671a2010-04-07 00:41:17 +0000498
Evan Cheng4038f9c2010-04-08 01:03:47 +0000499 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000500 SmallSet<int, 32> StoredFIs;
501
502 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000503 // collect potential LICM candidates.
Benjamin Kramer3ebb2152018-09-10 12:32:06 +0000504 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Bill Wendlinga2e87912011-10-12 02:58:01 +0000505 // If the header of the loop containing this basic block is a landing pad,
506 // then don't try to hoist instructions out of this loop.
507 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Klecknerc0e64ad2015-08-27 23:27:47 +0000508 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendlinga2e87912011-10-12 02:58:01 +0000509
Evan Chengd94671a2010-04-07 00:41:17 +0000510 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000511 // FIXME: That means a reload that're reused in successor block(s) will not
512 // be LICM'ed.
Matthias Braunaf5ff602015-09-09 18:08:03 +0000513 for (const auto &LI : BB->liveins()) {
514 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000515 PhysRegDefs.set(*AI);
Evan Chengd94671a2010-04-07 00:41:17 +0000516 }
517
Evan Chengfad62872011-10-11 23:48:44 +0000518 SpeculationState = SpeculateUnknown;
Sanjay Patel3442ec92016-01-06 23:45:05 +0000519 for (MachineInstr &MI : *BB)
520 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000521 }
Evan Chengd94671a2010-04-07 00:41:17 +0000522
Evan Chengd6c23552012-03-27 01:50:58 +0000523 // Gather the registers read / clobbered by the terminator.
524 BitVector TermRegs(NumRegs);
525 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
526 if (TI != Preheader->end()) {
Sanjay Patel3442ec92016-01-06 23:45:05 +0000527 for (const MachineOperand &MO : TI->operands()) {
Evan Chengd6c23552012-03-27 01:50:58 +0000528 if (!MO.isReg())
529 continue;
530 unsigned Reg = MO.getReg();
531 if (!Reg)
532 continue;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000533 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
534 TermRegs.set(*AI);
Evan Chengd6c23552012-03-27 01:50:58 +0000535 }
536 }
537
Evan Chengd94671a2010-04-07 00:41:17 +0000538 // Now evaluate whether the potential candidates qualify.
539 // 1. Check if the candidate defined register is defined by another
540 // instruction in the loop.
541 // 2. If the candidate is a load from stack slot (always true for now),
542 // check if the slot is stored anywhere in the loop.
Evan Chengd6c23552012-03-27 01:50:58 +0000543 // 3. Make sure candidate def should not clobber
544 // registers read by the terminator. Similarly its def should not be
545 // clobbered by the terminator.
Sanjay Patel3442ec92016-01-06 23:45:05 +0000546 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenko38409752017-09-22 23:46:57 +0000547 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel3442ec92016-01-06 23:45:05 +0000548 StoredFIs.count(Candidate.FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000549 continue;
550
Sanjay Patel3442ec92016-01-06 23:45:05 +0000551 unsigned Def = Candidate.Def;
Evan Chengd6c23552012-03-27 01:50:58 +0000552 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000553 bool Safe = true;
Sanjay Patel3442ec92016-01-06 23:45:05 +0000554 MachineInstr *MI = Candidate.MI;
555 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng63275372010-04-13 22:13:34 +0000556 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000557 continue;
Evan Chengd6c23552012-03-27 01:50:58 +0000558 unsigned Reg = MO.getReg();
559 if (PhysRegDefs.test(Reg) ||
560 PhysRegClobbers.test(Reg)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000561 // If it's using a non-loop-invariant register, then it's obviously
562 // not safe to hoist.
563 Safe = false;
564 break;
565 }
566 }
567 if (Safe)
Sanjay Patel3442ec92016-01-06 23:45:05 +0000568 HoistPostRA(MI, Candidate.Def);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000569 }
Evan Chengd94671a2010-04-07 00:41:17 +0000570 }
571}
572
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000573/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
574/// sure it is not killed by any instructions in the loop.
Matthias Braun09008362018-01-19 06:46:10 +0000575void MachineLICMBase::AddToLiveIns(unsigned Reg) {
Benjamin Kramer3ebb2152018-09-10 12:32:06 +0000576 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000577 if (!BB->isLiveIn(Reg))
578 BB->addLiveIn(Reg);
Sanjay Patel3442ec92016-01-06 23:45:05 +0000579 for (MachineInstr &MI : *BB) {
580 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000581 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
582 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
583 MO.setIsKill(false);
584 }
585 }
586 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000587}
588
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000589/// When an instruction is found to only use loop invariant operands that is
590/// safe to hoist, this instruction is called to do the dirty work.
Matthias Braun09008362018-01-19 06:46:10 +0000591void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000592 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000593
Evan Chengd94671a2010-04-07 00:41:17 +0000594 // Now move the instructions to the predecessor, inserting it before any
595 // terminator instructions.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000596 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
597 << " from " << printMBBReference(*MI->getParent()) << ": "
598 << *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000599
600 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000601 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000602 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000603
Andrew Trick9f17cf62012-02-08 21:23:00 +0000604 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000605 // loop invariant must be kept live throughout the whole loop. This is
606 // important to ensure later passes do not scavenge the def register.
607 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000608
609 ++NumPostRAHoisted;
610 Changed = true;
611}
612
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000613/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
614/// may not be safe to hoist.
Matthias Braun09008362018-01-19 06:46:10 +0000615bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000616 if (SpeculationState != SpeculateUnknown)
617 return SpeculationState == SpeculateFalse;
Andrew Trick9f17cf62012-02-08 21:23:00 +0000618
Devang Patel2e350472011-10-11 18:09:58 +0000619 if (BB != CurLoop->getHeader()) {
620 // Check loop exiting blocks.
621 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
622 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel3442ec92016-01-06 23:45:05 +0000623 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
624 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000625 SpeculationState = SpeculateTrue;
626 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000627 }
628 }
629
Evan Chengfad62872011-10-11 23:48:44 +0000630 SpeculationState = SpeculateFalse;
631 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000632}
633
Matthias Braun09008362018-01-19 06:46:10 +0000634void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000635 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000636
Pete Cooperacde91e2011-12-22 02:05:40 +0000637 // Remember livein register pressure.
638 BackTrace.push_back(RegPressure);
639}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000640
Matthias Braun09008362018-01-19 06:46:10 +0000641void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000642 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
Pete Cooperacde91e2011-12-22 02:05:40 +0000643 BackTrace.pop_back();
644}
Bill Wendling0f940c92007-12-07 21:42:31 +0000645
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000646/// Destroy scope for the MBB that corresponds to the given dominator tree node
647/// if its a leaf or all of its children are done. Walk up the dominator tree to
648/// destroy ancestors which are now done.
Matthias Braun09008362018-01-19 06:46:10 +0000649void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
650 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
651 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000652 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000653 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000654
Pete Cooperacde91e2011-12-22 02:05:40 +0000655 // Pop scope.
656 ExitScope(Node->getBlock());
657
658 // Now traverse upwards to pop ancestors whose offsprings are all done.
659 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
660 unsigned Left = --OpenChildren[Parent];
661 if (Left != 0)
662 break;
663 ExitScope(Parent->getBlock());
664 Node = Parent;
665 }
666}
667
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000668/// Walk the specified loop in the CFG (defined by all blocks dominated by the
669/// specified header block, and that are in the current loop) in depth first
670/// order w.r.t the DominatorTree. This allows us to visit definitions before
671/// uses, allowing us to hoist a loop body in one pass without iteration.
Matthias Braun09008362018-01-19 06:46:10 +0000672void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasperc7c25182015-02-05 22:39:46 +0000673 MachineBasicBlock *Preheader = getCurPreheader();
674 if (!Preheader)
675 return;
676
Pete Cooperacde91e2011-12-22 02:05:40 +0000677 SmallVector<MachineDomTreeNode*, 32> Scopes;
678 SmallVector<MachineDomTreeNode*, 8> WorkList;
679 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
680 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
681
682 // Perform a DFS walk to determine the order of visit.
683 WorkList.push_back(HeaderN);
Daniel Jasperc7c25182015-02-05 22:39:46 +0000684 while (!WorkList.empty()) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000685 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topper4ba84432014-04-14 00:51:57 +0000686 assert(Node && "Null dominator tree node?");
Pete Cooperacde91e2011-12-22 02:05:40 +0000687 MachineBasicBlock *BB = Node->getBlock();
688
689 // If the header of the loop containing this basic block is a landing pad,
690 // then don't try to hoist instructions out of this loop.
691 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Klecknerc0e64ad2015-08-27 23:27:47 +0000692 if (ML && ML->getHeader()->isEHPad())
Pete Cooperacde91e2011-12-22 02:05:40 +0000693 continue;
694
695 // If this subregion is not in the top level loop at all, exit.
696 if (!CurLoop->contains(BB))
697 continue;
698
699 Scopes.push_back(Node);
700 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
701 unsigned NumChildren = Children.size();
702
703 // Don't hoist things out of a large switch statement. This often causes
704 // code to be hoisted that wasn't going to be executed, and increases
705 // register pressure in a situation where it's likely to matter.
706 if (BB->succ_size() >= 25)
707 NumChildren = 0;
708
709 OpenChildren[Node] = NumChildren;
710 // Add children in reverse order as then the next popped worklist node is
711 // the first child of this node. This means we ultimately traverse the
712 // DOM tree in exactly the same order as if we'd recursed.
713 for (int i = (int)NumChildren-1; i >= 0; --i) {
714 MachineDomTreeNode *Child = Children[i];
715 ParentMap[Child] = Node;
716 WorkList.push_back(Child);
717 }
Daniel Dunbar98694132010-10-19 17:14:24 +0000718 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000719
Daniel Jasperc7c25182015-02-05 22:39:46 +0000720 if (Scopes.size() == 0)
721 return;
722
723 // Compute registers which are livein into the loop headers.
724 RegSeen.clear();
725 BackTrace.clear();
726 InitRegPressure(Preheader);
727
Pete Cooperacde91e2011-12-22 02:05:40 +0000728 // Now perform LICM.
Sanjay Patel3442ec92016-01-06 23:45:05 +0000729 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000730 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000731
Pete Cooperacde91e2011-12-22 02:05:40 +0000732 EnterScope(MBB);
733
734 // Process the block
735 SpeculationState = SpeculateUnknown;
736 for (MachineBasicBlock::iterator
737 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
738 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
739 MachineInstr *MI = &*MII;
740 if (!Hoist(MI, Preheader))
741 UpdateRegPressure(MI);
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000742 // If we have hoisted an instruction that may store, it can only be a
743 // constant store.
Pete Cooperacde91e2011-12-22 02:05:40 +0000744 MII = NextMII;
745 }
746
747 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
748 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000749 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000750}
751
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000752/// Sink instructions into loops if profitable. This especially tries to prevent
753/// register spills caused by register pressure if there is little to no
754/// overhead moving instructions into loops.
Matthias Braun09008362018-01-19 06:46:10 +0000755void MachineLICMBase::SinkIntoLoop() {
Daniel Jasper439cc2c2015-03-14 10:58:38 +0000756 MachineBasicBlock *Preheader = getCurPreheader();
757 if (!Preheader)
758 return;
759
760 SmallVector<MachineInstr *, 8> Candidates;
761 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
762 I != Preheader->instr_end(); ++I) {
763 // We need to ensure that we can safely move this instruction into the loop.
Michael Liao2238d782017-04-26 05:27:20 +0000764 // As such, it must not have side-effects, e.g. such as a call has.
Duncan P. N. Exon Smith9731c602015-10-09 19:40:45 +0000765 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
766 Candidates.push_back(&*I);
Daniel Jasper439cc2c2015-03-14 10:58:38 +0000767 }
768
769 for (MachineInstr *I : Candidates) {
770 const MachineOperand &MO = I->getOperand(0);
771 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
772 continue;
773 if (!MRI->hasOneDef(MO.getReg()))
774 continue;
775 bool CanSink = true;
776 MachineBasicBlock *B = nullptr;
777 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
778 // FIXME: Come up with a proper cost model that estimates whether sinking
779 // the instruction (and thus possibly executing it on every loop
780 // iteration) is more expensive than a register.
781 // For now assumes that copies are cheap and thus almost always worth it.
782 if (!MI.isCopy()) {
783 CanSink = false;
784 break;
785 }
786 if (!B) {
787 B = MI.getParent();
788 continue;
789 }
790 B = DT->findNearestCommonDominator(B, MI.getParent());
791 if (!B) {
792 CanSink = false;
793 break;
794 }
795 }
796 if (!CanSink || !B || B == Preheader)
797 continue;
798 B->splice(B->getFirstNonPHI(), Preheader, I);
799 }
800}
801
Evan Cheng134982d2010-10-20 22:03:58 +0000802static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
803 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
804}
805
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000806/// Find all virtual register references that are liveout of the preheader to
807/// initialize the starting "register pressure". Note this does not count live
808/// through (livein but not used) registers.
Matthias Braun09008362018-01-19 06:46:10 +0000809void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000810 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000811
Evan Cheng134982d2010-10-20 22:03:58 +0000812 // If the preheader has only a single predecessor and it ends with a
813 // fallthrough or an unconditional branch, then scan its predecessor for live
814 // defs as well. This happens whenever the preheader is created by splitting
815 // the critical edge from the loop predecessor to the loop header.
816 if (BB->pred_size() == 1) {
Craig Topper4ba84432014-04-14 00:51:57 +0000817 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng134982d2010-10-20 22:03:58 +0000818 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +0000819 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng134982d2010-10-20 22:03:58 +0000820 InitRegPressure(*BB->pred_begin());
821 }
822
Daniel Jasper6221f412015-04-07 16:42:35 +0000823 for (const MachineInstr &MI : *BB)
824 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Cheng0e673912010-10-14 01:16:09 +0000825}
826
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000827/// Update estimate of register pressure after the specified instruction.
Matthias Braun09008362018-01-19 06:46:10 +0000828void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
829 bool ConsiderUnseenAsDef) {
Daniel Jasper6221f412015-04-07 16:42:35 +0000830 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper6c456f02015-04-14 11:56:25 +0000831 for (const auto &RPIdAndCost : Cost) {
832 unsigned Class = RPIdAndCost.first;
833 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jasper6221f412015-04-07 16:42:35 +0000834 RegPressure[Class] = 0;
835 else
Daniel Jasper6c456f02015-04-14 11:56:25 +0000836 RegPressure[Class] += RPIdAndCost.second;
Daniel Jasper6221f412015-04-07 16:42:35 +0000837 }
838}
Evan Cheng0e673912010-10-14 01:16:09 +0000839
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000840/// Calculate the additional register pressure that the registers used in MI
841/// cause.
842///
843/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
844/// figure out which usages are live-ins.
845/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jasper6221f412015-04-07 16:42:35 +0000846DenseMap<unsigned, int>
Matthias Braun09008362018-01-19 06:46:10 +0000847MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
848 bool ConsiderUnseenAsDef) {
Daniel Jasper6221f412015-04-07 16:42:35 +0000849 DenseMap<unsigned, int> Cost;
850 if (MI->isImplicitDef())
851 return Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000852 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
853 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000854 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000855 continue;
856 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000857 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000858 continue;
859
Daniel Jasper6221f412015-04-07 16:42:35 +0000860 // FIXME: It seems bad to use RegSeen only for some of these calculations.
861 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper6c456f02015-04-14 11:56:25 +0000862 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
863
864 RegClassWeight W = TRI->getRegClassWeight(RC);
865 int RCCost = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000866 if (MO.isDef())
Daniel Jasper6c456f02015-04-14 11:56:25 +0000867 RCCost = W.RegWeight;
Daniel Jasper6221f412015-04-07 16:42:35 +0000868 else {
869 bool isKill = isOperandKill(MO, MRI);
870 if (isNew && !isKill && ConsiderUnseenAsDef)
871 // Haven't seen this, it must be a livein.
Daniel Jasper6c456f02015-04-14 11:56:25 +0000872 RCCost = W.RegWeight;
Daniel Jasper6221f412015-04-07 16:42:35 +0000873 else if (!isNew && isKill)
Daniel Jasper6c456f02015-04-14 11:56:25 +0000874 RCCost = -W.RegWeight;
875 }
876 if (RCCost == 0)
877 continue;
878 const int *PS = TRI->getRegClassPressureSets(RC);
879 for (; *PS != -1; ++PS) {
880 if (Cost.find(*PS) == Cost.end())
881 Cost[*PS] = RCCost;
882 else
883 Cost[*PS] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000884 }
Evan Cheng0e673912010-10-14 01:16:09 +0000885 }
Daniel Jasper6221f412015-04-07 16:42:35 +0000886 return Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000887}
888
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000889/// Return true if this machine instruction loads from global offset table or
890/// constant pool.
Philip Reamesa79baf52015-12-23 17:05:57 +0000891static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenko38409752017-09-22 23:46:57 +0000892 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liao2238d782017-04-26 05:27:20 +0000893
Philip Reamesa79baf52015-12-23 17:05:57 +0000894 // If we lost memory operands, conservatively assume that the instruction
Michael Liao2238d782017-04-26 05:27:20 +0000895 // reads from everything..
Philip Reamesa79baf52015-12-23 17:05:57 +0000896 if (MI.memoperands_empty())
897 return true;
898
Sanjay Patel3442ec92016-01-06 23:45:05 +0000899 for (MachineMemOperand *MemOp : MI.memoperands())
900 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenzde0129a2015-08-11 23:09:45 +0000901 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyd63390c2014-04-15 07:22:52 +0000902 return true;
Sanjay Patel3442ec92016-01-06 23:45:05 +0000903
Devang Patel6c15fec2011-10-17 17:35:01 +0000904 return false;
905}
906
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000907// This function iterates through all the operands of the input store MI and
908// checks that each register operand statisfies isCallerPreservedPhysReg.
909// This means, the value being stored and the address where it is being stored
910// is constant throughout the body of the function (not including prologue and
911// epilogue). When called with an MI that isn't a store, it returns false.
Zaara Syedadbec9f72018-04-09 14:50:02 +0000912// A future improvement can be to check if the store registers are constant
913// throughout the loop rather than throughout the funtion.
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000914static bool isInvariantStore(const MachineInstr &MI,
915 const TargetRegisterInfo *TRI,
916 const MachineRegisterInfo *MRI) {
917
Zaara Syedadbec9f72018-04-09 14:50:02 +0000918 bool FoundCallerPresReg = false;
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000919 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
920 (MI.getNumOperands() == 0))
921 return false;
922
923 // Check that all register operands are caller-preserved physical registers.
924 for (const MachineOperand &MO : MI.operands()) {
925 if (MO.isReg()) {
926 unsigned Reg = MO.getReg();
927 // If operand is a virtual register, check if it comes from a copy of a
928 // physical register.
929 if (TargetRegisterInfo::isVirtualRegister(Reg))
930 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
931 if (TargetRegisterInfo::isVirtualRegister(Reg))
932 return false;
933 if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
934 return false;
Zaara Syedadbec9f72018-04-09 14:50:02 +0000935 else
936 FoundCallerPresReg = true;
937 } else if (!MO.isImm()) {
938 return false;
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000939 }
940 }
Zaara Syedadbec9f72018-04-09 14:50:02 +0000941 return FoundCallerPresReg;
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000942}
943
944// Return true if the input MI is a copy instruction that feeds an invariant
945// store instruction. This means that the src of the copy has to satisfy
946// isCallerPreservedPhysReg and atleast one of it's users should satisfy
947// isInvariantStore.
948static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
949 const MachineRegisterInfo *MRI,
950 const TargetRegisterInfo *TRI) {
951
952 // FIXME: If targets would like to look through instructions that aren't
953 // pure copies, this can be updated to a query.
954 if (!MI.isCopy())
955 return false;
956
957 const MachineFunction *MF = MI.getMF();
958 // Check that we are copying a constant physical register.
959 unsigned CopySrcReg = MI.getOperand(1).getReg();
960 if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
961 return false;
962
963 if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
964 return false;
965
966 unsigned CopyDstReg = MI.getOperand(0).getReg();
967 // Check if any of the uses of the copy are invariant stores.
968 assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
969 "copy dst is not a virtual reg");
970
971 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
972 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
973 return true;
974 }
975 return false;
976}
977
Sanjay Patelf3ba0562015-12-10 16:34:21 +0000978/// Returns true if the instruction may be a suitable candidate for LICM.
979/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Matthias Braun09008362018-01-19 06:46:10 +0000980bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000981 // Check if it's safe to move the instruction.
982 bool DontMoveAcrossStore = true;
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000983 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
984 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000985 return false;
Zaara Syeda4561f7d2018-03-23 15:28:15 +0000986 }
Devang Patel2e350472011-10-11 18:09:58 +0000987
988 // If it is load then check if it is guaranteed to execute by making sure that
989 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000990 // the loop which does not execute this load, so we can't hoist it. Loads
991 // from constant memory are not safe to speculate all the time, for example
992 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000993 // Stores and side effects are already checked by isSafeToMove.
Philip Reamesa79baf52015-12-23 17:05:57 +0000994 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000995 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000996 return false;
997
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000998 return true;
999}
1000
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001001/// Returns true if the instruction is loop invariant.
1002/// I.e., all virtual register operands are defined outside of the loop,
1003/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng5dc57ce2010-04-13 18:16:00 +00001004/// effects that aren't captured by the operands or other flags.
Matthias Braun09008362018-01-19 06:46:10 +00001005bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +00001006 if (!IsLICMCandidate(I))
1007 return false;
Bill Wendling074223a2008-03-10 08:13:01 +00001008
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001009 // The instruction is loop invariant if all of its operands are.
Sanjay Patel3442ec92016-01-06 23:45:05 +00001010 for (const MachineOperand &MO : I.operands()) {
Dan Gohmand735b802008-10-03 15:45:36 +00001011 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +00001012 continue;
1013
Dan Gohmanc475c362009-01-15 22:01:38 +00001014 unsigned Reg = MO.getReg();
1015 if (Reg == 0) continue;
1016
1017 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +00001018 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +00001019 if (MO.isUse()) {
1020 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +00001021 // and we can freely move its uses. Alternatively, if it's allocatable,
1022 // it could get allocated to something with a def during allocation.
Lei Huangedd54f82017-06-15 18:29:59 +00001023 // However, if the physreg is known to always be caller saved/restored
1024 // then this use is safe to hoist.
1025 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bogner1842f4a2017-10-10 23:50:49 +00001026 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1027 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +00001028 // Otherwise it's safe to move.
1029 continue;
1030 } else if (!MO.isDead()) {
1031 // A def that isn't dead. We can't move it.
1032 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +00001033 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1034 // If the reg is live into the loop, we can't hoist an instruction
1035 // which would clobber it.
1036 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +00001037 }
1038 }
Bill Wendlingfb018d02008-08-20 20:32:05 +00001039
1040 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +00001041 continue;
1042
Evan Cheng0e673912010-10-14 01:16:09 +00001043 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001044 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +00001045
1046 // If the loop contains the definition of an operand, then the instruction
1047 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +00001048 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +00001049 return false;
1050 }
1051
1052 // If we got this far, the instruction is loop invariant!
1053 return true;
1054}
1055
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001056/// Return true if the specified instruction is used by a phi node and hoisting
1057/// it could cause a copy to be inserted.
Matthias Braun09008362018-01-19 06:46:10 +00001058bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001059 SmallVector<const MachineInstr*, 8> Work(1, MI);
1060 do {
1061 MI = Work.pop_back_val();
Matthias Braune67bd6c2015-05-29 02:56:46 +00001062 for (const MachineOperand &MO : MI->operands()) {
1063 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001064 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +00001065 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001066 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1067 continue;
Owen Anderson92fca732014-03-17 19:36:09 +00001068 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001069 // A PHI may cause a copy to be inserted.
Owen Anderson92fca732014-03-17 19:36:09 +00001070 if (UseMI.isPHI()) {
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001071 // A PHI inside the loop causes a copy because the live range of Reg is
1072 // extended across the PHI.
Owen Anderson92fca732014-03-17 19:36:09 +00001073 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001074 return true;
1075 // A PHI in an exit block can cause a copy to be inserted if the PHI
1076 // has multiple predecessors in the loop with different values.
1077 // For now, approximate by rejecting all exit blocks.
Owen Anderson92fca732014-03-17 19:36:09 +00001078 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001079 return true;
1080 continue;
1081 }
1082 // Look past copies as well.
Owen Anderson92fca732014-03-17 19:36:09 +00001083 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1084 Work.push_back(&UseMI);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001085 }
Evan Chengd67705f2011-04-11 21:09:18 +00001086 }
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001087 } while (!Work.empty());
Evan Chengaf6949d2009-02-05 08:45:46 +00001088 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001089}
1090
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001091/// Compute operand latency between a def of 'Reg' and an use in the current
1092/// loop, return true if the target considered it high.
Matthias Braun09008362018-01-19 06:46:10 +00001093bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1094 unsigned DefIdx,
1095 unsigned Reg) const {
Matthias Braun6fee0b02015-06-13 03:42:11 +00001096 if (MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +00001097 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001098
Owen Anderson92fca732014-03-17 19:36:09 +00001099 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1100 if (UseMI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001101 continue;
Owen Anderson92fca732014-03-17 19:36:09 +00001102 if (!CurLoop->contains(UseMI.getParent()))
Evan Cheng0e673912010-10-14 01:16:09 +00001103 continue;
Owen Anderson92fca732014-03-17 19:36:09 +00001104 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1105 const MachineOperand &MO = UseMI.getOperand(i);
Evan Cheng0e673912010-10-14 01:16:09 +00001106 if (!MO.isReg() || !MO.isUse())
1107 continue;
1108 unsigned MOReg = MO.getReg();
1109 if (MOReg != Reg)
1110 continue;
1111
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001112 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng23128422010-10-19 18:58:51 +00001113 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001114 }
1115
Evan Cheng23128422010-10-19 18:58:51 +00001116 // Only look at the first in loop use.
1117 break;
Evan Cheng0e673912010-10-14 01:16:09 +00001118 }
1119
Evan Cheng23128422010-10-19 18:58:51 +00001120 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001121}
1122
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001123/// Return true if the instruction is marked "cheap" or the operand latency
1124/// between its def and a use is one or less.
Matthias Braun09008362018-01-19 06:46:10 +00001125bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001126 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001127 return true;
Evan Chengc8141df2010-10-26 02:08:50 +00001128
1129 bool isCheap = false;
1130 unsigned NumDefs = MI.getDesc().getNumDefs();
1131 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1132 MachineOperand &DefMO = MI.getOperand(i);
1133 if (!DefMO.isReg() || !DefMO.isDef())
1134 continue;
1135 --NumDefs;
1136 unsigned Reg = DefMO.getReg();
1137 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1138 continue;
1139
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001140 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chengc8141df2010-10-26 02:08:50 +00001141 return false;
1142 isCheap = true;
1143 }
1144
1145 return isCheap;
1146}
1147
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001148/// Visit BBs from header to current BB, check if hoisting an instruction of the
1149/// given cost matrix can cause high register pressure.
Matthias Braun09008362018-01-19 06:46:10 +00001150bool
1151MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1152 bool CheapInstr) {
Daniel Jasper6c456f02015-04-14 11:56:25 +00001153 for (const auto &RPIdAndCost : Cost) {
1154 if (RPIdAndCost.second <= 0)
Evan Cheng134982d2010-10-20 22:03:58 +00001155 continue;
1156
Daniel Jasper6c456f02015-04-14 11:56:25 +00001157 unsigned Class = RPIdAndCost.first;
Daniel Jasperefa23ae2015-04-03 16:19:48 +00001158 int Limit = RegLimit[Class];
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001159
1160 // Don't hoist cheap instructions if they would increase register pressure,
1161 // even if we're under the limit.
Hal Finkel9d1500e2015-01-08 22:10:48 +00001162 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001163 return true;
1164
Daniel Jasperefa23ae2015-04-03 16:19:48 +00001165 for (const auto &RP : BackTrace)
Daniel Jasper6c456f02015-04-14 11:56:25 +00001166 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001167 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001168 }
1169
1170 return false;
1171}
1172
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001173/// Traverse the back trace from header to the current block and update their
1174/// register pressures to reflect the effect of hoisting MI from the current
1175/// block to the preheader.
Matthias Braun09008362018-01-19 06:46:10 +00001176void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng134982d2010-10-20 22:03:58 +00001177 // First compute the 'cost' of the instruction, i.e. its contribution
1178 // to register pressure.
Daniel Jasper6221f412015-04-07 16:42:35 +00001179 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1180 /*ConsiderUnseenAsDef=*/false);
Evan Cheng134982d2010-10-20 22:03:58 +00001181
1182 // Update register pressure of blocks from loop header to current block.
Daniel Jasper6221f412015-04-07 16:42:35 +00001183 for (auto &RP : BackTrace)
Daniel Jasper6c456f02015-04-14 11:56:25 +00001184 for (const auto &RPIdAndCost : Cost)
1185 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng134982d2010-10-20 22:03:58 +00001186}
1187
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001188/// Return true if it is potentially profitable to hoist the given loop
1189/// invariant.
Matthias Braun09008362018-01-19 06:46:10 +00001190bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001191 if (MI.isImplicitDef())
1192 return true;
1193
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001194 // Besides removing computation from the loop, hoisting an instruction has
1195 // these effects:
1196 //
1197 // - The value defined by the instruction becomes live across the entire
1198 // loop. This increases register pressure in the loop.
1199 //
1200 // - If the value is used by a PHI in the loop, a copy will be required for
1201 // lowering the PHI after extending the live range.
1202 //
1203 // - When hoisting the last use of a value in the loop, that value no longer
1204 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng61560e22011-09-01 01:45:00 +00001205
Zaara Syeda4561f7d2018-03-23 15:28:15 +00001206 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1207 return true;
1208
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001209 bool CheapInstr = IsCheapInstruction(MI);
1210 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001211
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001212 // Don't hoist a cheap instruction if it would create a copy in the loop.
1213 if (CheapInstr && CreatesCopy) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001214 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001215 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001216 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001217
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001218 // Rematerializable instructions should always be hoisted since the register
1219 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001220 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001221 return true;
1222
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001223 // FIXME: If there are long latency loop-invariant instructions inside the
1224 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001225 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1226 const MachineOperand &MO = MI.getOperand(i);
1227 if (!MO.isReg() || MO.isImplicit())
1228 continue;
1229 unsigned Reg = MO.getReg();
1230 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1231 continue;
Daniel Jasper6221f412015-04-07 16:42:35 +00001232 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001233 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
Daniel Jasper6221f412015-04-07 16:42:35 +00001234 ++NumHighLatency;
1235 return true;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001236 }
1237 }
1238
Daniel Jasper6221f412015-04-07 16:42:35 +00001239 // Estimate register pressure to determine whether to LICM the instruction.
1240 // In low register pressure situation, we can be more aggressive about
1241 // hoisting. Also, favors hoisting long latency instructions even in
1242 // moderately high pressure situation.
1243 // Cheap instructions will only be hoisted if they don't increase register
1244 // pressure at all.
1245 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1246 /*ConsiderUnseenAsDef=*/false);
1247
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001248 // Visit BBs from header to current BB, if hoisting this doesn't cause
1249 // high register pressure, then it's safe to proceed.
1250 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001251 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001252 ++NumLowRP;
1253 return true;
1254 }
1255
1256 // Don't risk increasing register pressure if it would create copies.
1257 if (CreatesCopy) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001258 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesen8b560b82012-04-11 00:00:26 +00001259 return false;
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001260 }
1261
1262 // Do not "speculate" in high register pressure situation. If an
1263 // instruction is not guaranteed to be executed in the loop, it's best to be
1264 // conservative.
1265 if (AvoidSpeculation &&
1266 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001267 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001268 return false;
1269 }
1270
1271 // High register pressure situation, only hoist if the instruction is going
1272 // to be remat'ed.
Justin Lebare7555f02016-09-10 01:03:20 +00001273 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1274 !MI.isDereferenceableInvariantLoad(AA)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001275 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
Jakob Stoklund Olesen71fbed452012-04-11 00:00:28 +00001276 return false;
1277 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001278
1279 return true;
1280}
1281
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001282/// Unfold a load from the given machineinstr if the load itself could be
1283/// hoisted. Return the unfolded and hoistable load, or null if the load
1284/// couldn't be unfolded or if it wouldn't be hoistable.
Matthias Braun09008362018-01-19 06:46:10 +00001285MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001286 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001287 if (MI->canFoldAsLoad())
Craig Topper4ba84432014-04-14 00:51:57 +00001288 return nullptr;
Evan Chenge95f3192010-10-08 18:59:19 +00001289
Dan Gohman5c952302009-10-29 17:47:20 +00001290 // If not, we may be able to unfold a load and hoist that.
1291 // First test whether the instruction is loading from an amenable
1292 // memory location.
Justin Lebare7555f02016-09-10 01:03:20 +00001293 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topper4ba84432014-04-14 00:51:57 +00001294 return nullptr;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001295
Dan Gohman5c952302009-10-29 17:47:20 +00001296 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001297 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001298 unsigned NewOpc =
1299 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1300 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001301 /*UnfoldStore=*/false,
1302 &LoadRegIndex);
Craig Topper4ba84432014-04-14 00:51:57 +00001303 if (NewOpc == 0) return nullptr;
Evan Chenge837dea2011-06-28 19:10:37 +00001304 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bogner1842f4a2017-10-10 23:50:49 +00001305 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +00001306 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman5c952302009-10-29 17:47:20 +00001307 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001308 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001309
Dan Gohman5c952302009-10-29 17:47:20 +00001310 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001311 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1312 /*UnfoldLoad=*/true,
1313 /*UnfoldStore=*/false, NewMIs);
Dan Gohman5c952302009-10-29 17:47:20 +00001314 (void)Success;
1315 assert(Success &&
1316 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1317 "succeeded!");
1318 assert(NewMIs.size() == 2 &&
1319 "Unfolded a load into multiple instructions!");
1320 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001321 MachineBasicBlock::iterator Pos = MI;
1322 MBB->insert(Pos, NewMIs[0]);
1323 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001324 // If unfolding produced a load that wasn't loop-invariant or profitable to
1325 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001326 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001327 NewMIs[0]->eraseFromParent();
1328 NewMIs[1]->eraseFromParent();
Craig Topper4ba84432014-04-14 00:51:57 +00001329 return nullptr;
Dan Gohman5c952302009-10-29 17:47:20 +00001330 }
Evan Cheng134982d2010-10-20 22:03:58 +00001331
1332 // Update register pressure for the unfolded instruction.
1333 UpdateRegPressure(NewMIs[1]);
1334
Dan Gohman5c952302009-10-29 17:47:20 +00001335 // Otherwise we successfully unfolded a load that we can hoist.
1336 MI->eraseFromParent();
1337 return NewMIs[0];
1338}
1339
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001340/// Initialize the CSE map with instructions that are in the current loop
1341/// preheader that may become duplicates of instructions that are hoisted
1342/// out of the loop.
Matthias Braun09008362018-01-19 06:46:10 +00001343void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel3442ec92016-01-06 23:45:05 +00001344 for (MachineInstr &MI : *BB)
1345 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001346}
1347
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001348/// Find an instruction amount PrevMIs that is a duplicate of MI.
1349/// Return this instruction if it's found.
Evan Cheng78e5c112009-11-07 03:52:02 +00001350const MachineInstr*
Matthias Braun09008362018-01-19 06:46:10 +00001351MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1352 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel3442ec92016-01-06 23:45:05 +00001353 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith567409d2016-06-30 00:01:54 +00001354 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001355 return PrevMI;
Sanjay Patel3442ec92016-01-06 23:45:05 +00001356
Craig Topper4ba84432014-04-14 00:51:57 +00001357 return nullptr;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001358}
1359
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001360/// Given a LICM'ed instruction, look for an instruction on the preheader that
1361/// computes the same value. If it's found, do a RAU on with the definition of
1362/// the existing instruction rather than hoisting the instruction to the
1363/// preheader.
Matthias Braun09008362018-01-19 06:46:10 +00001364bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1365 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001366 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1367 // the undef property onto uses.
1368 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001369 return false;
1370
1371 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001372 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001373
1374 // Replace virtual registers defined by MI by their counterparts defined
1375 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001376 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001377 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1378 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001379
1380 // Physical registers may not differ here.
1381 assert((!MO.isReg() || MO.getReg() == 0 ||
1382 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1383 MO.getReg() == Dup->getOperand(i).getReg()) &&
1384 "Instructions with different phys regs are not identical!");
1385
1386 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001387 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1388 Defs.push_back(i);
1389 }
1390
1391 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1392 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1393 unsigned Idx = Defs[i];
1394 unsigned Reg = MI->getOperand(Idx).getReg();
1395 unsigned DupReg = Dup->getOperand(Idx).getReg();
1396 OrigRCs.push_back(MRI->getRegClass(DupReg));
1397
1398 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1399 // Restore old RCs if more than one defs.
1400 for (unsigned j = 0; j != i; ++j)
1401 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1402 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001403 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001404 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001405
Sanjay Patel3442ec92016-01-06 23:45:05 +00001406 for (unsigned Idx : Defs) {
Evan Cheng1025cce2011-10-17 19:50:12 +00001407 unsigned Reg = MI->getOperand(Idx).getReg();
1408 unsigned DupReg = Dup->getOperand(Idx).getReg();
1409 MRI->replaceRegWith(Reg, DupReg);
1410 MRI->clearKillFlags(DupReg);
1411 }
1412
Evan Cheng78e5c112009-11-07 03:52:02 +00001413 MI->eraseFromParent();
1414 ++NumCSEed;
1415 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001416 }
1417 return false;
1418}
1419
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001420/// Return true if the given instruction will be CSE'd if it's hoisted out of
1421/// the loop.
Matthias Braun09008362018-01-19 06:46:10 +00001422bool MachineLICMBase::MayCSE(MachineInstr *MI) {
Evan Cheng7efba852011-10-12 00:09:14 +00001423 unsigned Opcode = MI->getOpcode();
Eugene Zelenko38409752017-09-22 23:46:57 +00001424 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Cheng7efba852011-10-12 00:09:14 +00001425 CI = CSEMap.find(Opcode);
1426 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1427 // the undef property onto uses.
1428 if (CI == CSEMap.end() || MI->isImplicitDef())
1429 return false;
1430
Craig Topper4ba84432014-04-14 00:51:57 +00001431 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Cheng7efba852011-10-12 00:09:14 +00001432}
1433
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001434/// When an instruction is found to use only loop invariant operands
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001435/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001436/// It returns true if the instruction is hoisted.
Matthias Braun09008362018-01-19 06:46:10 +00001437bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001438 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001439 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001440 // If not, try unfolding a hoistable load.
1441 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001442 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001443 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001444
Zaara Syeda4561f7d2018-03-23 15:28:15 +00001445 // If we have hoisted an instruction that may store, it can only be a constant
1446 // store.
1447 if (MI->mayStore())
1448 NumStoreConst++;
1449
Dan Gohmanc475c362009-01-15 22:01:38 +00001450 // Now move the instructions to the predecessor, inserting it before any
1451 // terminator instructions.
Nicola Zaghen0818e782018-05-14 12:53:11 +00001452 LLVM_DEBUG({
1453 dbgs() << "Hoisting " << *MI;
1454 if (MI->getParent()->getBasicBlock())
1455 dbgs() << " from " << printMBBReference(*MI->getParent());
1456 if (Preheader->getBasicBlock())
1457 dbgs() << " to " << printMBBReference(*Preheader);
1458 dbgs() << "\n";
1459 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001460
Evan Cheng777c6b72009-11-03 21:40:02 +00001461 // If this is the first instruction being hoisted to the preheader,
1462 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001463 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001464 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001465 FirstInLoop = false;
1466 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001467
Evan Chengaf6949d2009-02-05 08:45:46 +00001468 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001469 unsigned Opcode = MI->getOpcode();
Eugene Zelenko38409752017-09-22 23:46:57 +00001470 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Cheng777c6b72009-11-03 21:40:02 +00001471 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001472 if (!EliminateCSE(MI, CI)) {
1473 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001474 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001475
Wolfgang Pieb40c40ef2016-12-02 00:37:57 +00001476 // Since we are moving the instruction out of its basic block, we do not
Michael Liao2238d782017-04-26 05:27:20 +00001477 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb40c40ef2016-12-02 00:37:57 +00001478 // experience and adversely affect the accuracy of profiling information.
1479 MI->setDebugLoc(DebugLoc());
1480
Evan Cheng134982d2010-10-20 22:03:58 +00001481 // Update register pressure for BBs from header to this block.
1482 UpdateBackTraceRegPressure(MI);
1483
Dan Gohmane6cd7572010-05-13 20:34:42 +00001484 // Clear the kill flags of any register this instruction defines,
1485 // since they may need to be live throughout the entire loop
1486 // rather than just live for part of it.
Sanjay Patel3442ec92016-01-06 23:45:05 +00001487 for (MachineOperand &MO : MI->operands())
Dan Gohmane6cd7572010-05-13 20:34:42 +00001488 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001489 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001490
Evan Chengaf6949d2009-02-05 08:45:46 +00001491 // Add to the CSE map.
1492 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001493 CI->second.push_back(MI);
Benjamin Kramer63688e62014-10-03 18:33:16 +00001494 else
1495 CSEMap[Opcode].push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001496 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001497
Dan Gohmanc475c362009-01-15 22:01:38 +00001498 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001499 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001500
1501 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001502}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001503
Sanjay Patelf3ba0562015-12-10 16:34:21 +00001504/// Get the preheader for the current loop, splitting a critical edge if needed.
Matthias Braun09008362018-01-19 06:46:10 +00001505MachineBasicBlock *MachineLICMBase::getCurPreheader() {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001506 // Determine the block to which to hoist instructions. If we can't find a
1507 // suitable loop predecessor, we can't do any hoisting.
1508
1509 // If we've tried to get a preheader and failed, don't try again.
1510 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topper4ba84432014-04-14 00:51:57 +00001511 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001512
1513 if (!CurPreheader) {
1514 CurPreheader = CurLoop->getLoopPreheader();
1515 if (!CurPreheader) {
1516 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1517 if (!Pred) {
1518 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topper4ba84432014-04-14 00:51:57 +00001519 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001520 }
1521
Quentin Colombetf2cd1572016-04-21 21:01:13 +00001522 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman853d3fb2010-06-22 17:25:57 +00001523 if (!CurPreheader) {
1524 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topper4ba84432014-04-14 00:51:57 +00001525 return nullptr;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001526 }
1527 }
1528 }
1529 return CurPreheader;
1530}