blob: e2d92009f2176fb2ece0d819bef415d8a8d1b6bf [file] [log] [blame]
Eugene Zelenkof1933322017-09-22 23:46:57 +00001//===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
Bill Wendlingfb706bc2007-12-07 21:42:31 +00002//
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
Eugene Zelenkof1933322017-09-22 23:46:57 +000019#include "llvm/ADT/BitVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000023#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000032#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000033#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000034#include "llvm/CodeGen/MachineOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000036#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000037#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetLowering.h"
39#include "llvm/CodeGen/TargetRegisterInfo.h"
Matthias Braun88e21312015-06-13 03:42:11 +000040#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkof1933322017-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 Chengb35afca2011-10-12 21:33:49 +000047#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000048#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000050#include <algorithm>
51#include <cassert>
52#include <limits>
53#include <vector>
54
Bill Wendlingfb706bc2007-12-07 21:42:31 +000055using namespace llvm;
56
Matthias Braun1527baa2017-05-25 21:26:32 +000057#define DEBUG_TYPE "machinelicm"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058
Evan Chengb35afca2011-10-12 21:33:49 +000059static cl::opt<bool>
60AvoidSpeculation("avoid-speculation",
61 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000062 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000063
Hal Finkel0709f512015-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 Jasper15e69542015-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 Syeda65359932018-03-23 15:28:15 +000074static cl::opt<bool>
75HoistConstStores("hoist-const-stores",
76 cl::desc("Hoist invariant stores"),
Zaara Syeda935474fe2018-04-09 14:50:02 +000077 cl::init(true), cl::Hidden);
Daniel Jasper15e69542015-03-14 10:58:38 +000078
Evan Cheng44436302010-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 Cheng6ea59492010-04-07 00:41:17 +000087STATISTIC(NumPostRAHoisted,
88 "Number of machine instructions hoisted out of loops post regalloc");
Zaara Syeda65359932018-03-23 15:28:15 +000089STATISTIC(NumStoreConst,
90 "Number of stores of const phys reg hoisted out of loops");
Bill Wendling43751732007-12-08 01:47:01 +000091
Bill Wendlingfb706bc2007-12-07 21:42:31 +000092namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000093
Matthias Braun4a7c8e72018-01-19 06:46:10 +000094 class MachineLICMBase : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000095 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000096 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000097 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000098 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000099 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +0000100 TargetSchedModel SchedModel;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000101 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +0000102
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000103 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000104 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +0000105 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +0000106 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000107
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000108 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +0000109 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +0000110 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +0000111 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +0000112 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +0000113
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000114 // Exit blocks for CurLoop.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000115 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000116
117 bool isExitBlock(const MachineBasicBlock *MBB) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000118 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000119 }
120
Evan Chengd62719c2010-10-14 01:16:09 +0000121 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000122 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000123 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000124
Daniel Jasper274928f2015-04-14 11:56:25 +0000125 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000126 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000127 SmallVector<unsigned, 8> RegLimit;
128
Evan Cheng44436302010-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 Johannesen329d4742010-07-29 17:45:24 +0000132 // For each opcode, keep a list of potential CSE instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000133 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000134
Evan Chengf192ca02011-10-11 23:48:44 +0000135 enum {
136 SpeculateFalse = 0,
137 SpeculateTrue = 1,
138 SpeculateUnknown = 2
139 };
140
Devang Patel453d4012011-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 Chengf192ca02011-10-11 23:48:44 +0000143 // Tri-state: 0 - false, 1 - true, 2 - unknown
144 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000145
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000146 public:
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000147 MachineLICMBase(char &PassID, bool PreRegAlloc)
148 : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000149
Craig Topper4584cd52014-03-07 09:26:03 +0000150 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000151
Craig Topper4584cd52014-03-07 09:26:03 +0000152 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000153 AU.addRequired<MachineLoopInfo>();
154 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000155 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000156 AU.addPreserved<MachineLoopInfo>();
157 AU.addPreserved<MachineDominatorTree>();
158 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000159 }
Evan Cheng399660c2009-02-05 08:45:46 +0000160
Craig Topper4584cd52014-03-07 09:26:03 +0000161 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000162 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000163 RegPressure.clear();
164 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000165 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000166 CSEMap.clear();
167 }
168
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000169 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000170 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000171 struct CandidateInfo {
172 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000173 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000174 int FI;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000175
Evan Cheng0a2aff22010-04-13 18:16:00 +0000176 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
177 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000178 };
179
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000180 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000181
Evan Cheng058b9f02010-04-08 01:03:47 +0000182 void HoistPostRA(MachineInstr *MI, unsigned Def);
183
Sanjay Patel87c6c072015-12-10 16:34:21 +0000184 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
185 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000186 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000187
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000188 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000189
Evan Cheng0a2aff22010-04-13 18:16:00 +0000190 bool IsLICMCandidate(MachineInstr &I);
191
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000192 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000193
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000194 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000195
Evan Chenge96b8d72010-10-26 02:08:50 +0000196 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
197 unsigned Reg) const;
198
199 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000200
Daniel Jasperefece522015-04-03 16:19:48 +0000201 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
202 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000203
Evan Cheng87066f02010-10-20 22:03:58 +0000204 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000205
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000206 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000207
Devang Patel453d4012011-10-11 18:09:58 +0000208 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
209
Pete Cooper1eed5b52011-12-22 02:05:40 +0000210 void EnterScope(MachineBasicBlock *MBB);
211
212 void ExitScope(MachineBasicBlock *MBB);
213
Sanjay Patel87c6c072015-12-10 16:34:21 +0000214 void ExitScopeIfDone(
215 MachineDomTreeNode *Node,
216 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
217 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000218
Pete Cooper1eed5b52011-12-22 02:05:40 +0000219 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000220
Pete Cooper1eed5b52011-12-22 02:05:40 +0000221 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000222
Daniel Jasper15e69542015-03-14 10:58:38 +0000223 void SinkIntoLoop();
224
Evan Chengd62719c2010-10-14 01:16:09 +0000225 void InitRegPressure(MachineBasicBlock *BB);
226
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000227 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
228 bool ConsiderSeen,
229 bool ConsiderUnseenAsDef);
230
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000231 void UpdateRegPressure(const MachineInstr *MI,
232 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000233
Dan Gohman104f57c2009-10-29 17:47:20 +0000234 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
235
Sanjay Patel87c6c072015-12-10 16:34:21 +0000236 const MachineInstr *
237 LookForDuplicate(const MachineInstr *MI,
238 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000239
Sanjay Patel87c6c072015-12-10 16:34:21 +0000240 bool EliminateCSE(
241 MachineInstr *MI,
242 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000243
Evan Chengaf138952011-10-12 00:09:14 +0000244 bool MayCSE(MachineInstr *MI);
245
Evan Cheng87066f02010-10-20 22:03:58 +0000246 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000247
Evan Chengf42b5af2009-11-03 21:40:02 +0000248 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000249
Dan Gohman3570f812010-06-22 17:25:57 +0000250 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000251 };
Eugene Zelenkof1933322017-09-22 23:46:57 +0000252
Matthias Braun4a7c8e72018-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 Wendlingfb706bc2007-12-07 21:42:31 +0000269} // end anonymous namespace
270
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000271char MachineLICM::ID;
272char EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000273
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000274char &llvm::MachineLICMID = MachineLICM::ID;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000275char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000276
Matthias Braun1527baa2017-05-25 21:26:32 +0000277INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
278 "Machine Loop Invariant Code Motion", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000279INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
280INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000281INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000282INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
283 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000284
Matthias Braun4a7c8e72018-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 Patel87c6c072015-12-10 16:34:21 +0000293/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000294static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-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 Gohman79618d12009-01-15 22:01:38 +0000299 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000300 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000301 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000302 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000303 return true;
304}
305
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000306bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000307 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000308 return false;
309
Evan Cheng032f3262010-05-29 00:06:36 +0000310 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000311 const TargetSubtargetInfo &ST = MF.getSubtarget();
312 TII = ST.getInstrInfo();
313 TLI = ST.getTargetLowering();
314 TRI = ST.getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000315 MFI = &MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000316 MRI = &MF.getRegInfo();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000317 SchedModel.init(&ST);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000318
Andrew Trickc40815d2012-02-08 21:23:03 +0000319 PreRegAlloc = MRI->isSSA();
320
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000321 if (PreRegAlloc)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000322 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000323 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000324 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
325 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000326
Evan Chengd62719c2010-10-14 01:16:09 +0000327 if (PreRegAlloc) {
328 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000329 unsigned NumRPS = TRI->getNumRegPressureSets();
330 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000331 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-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 Chengd62719c2010-10-14 01:16:09 +0000335 }
336
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000337 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000338 MLI = &getAnalysis<MachineLoopInfo>();
339 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000340 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000341
Dan Gohman7929c442010-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 Topperc0196b12014-04-14 00:51:57 +0000345 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000346 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000347
Evan Cheng058b9f02010-04-08 01:03:47 +0000348 // If this is done before regalloc, only visit outer-most preheader-sporting
349 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000350 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
351 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000352 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000353 }
Dan Gohman79618d12009-01-15 22:01:38 +0000354
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000355 CurLoop->getExitBlocks(ExitBlocks);
356
Evan Cheng6ea59492010-04-07 00:41:17 +0000357 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000358 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000359 else {
Evan Cheng5fdb57c2010-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 Cheng032f3262010-05-29 00:06:36 +0000363 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000364 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000365 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000366
367 if (SinkInstsToAvoidSpills)
368 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000369 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000370 }
371
372 return Changed;
373}
374
Sanjay Patel87c6c072015-12-10 16:34:21 +0000375/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000376static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Geoff Berry8e4958e2018-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 Reames42bd26f2015-12-23 17:05:57 +0000381 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000382 // writes to all slots.
Philip Reames42bd26f2015-12-23 17:05:57 +0000383 if (MI->memoperands_empty())
384 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000385 for (const MachineMemOperand *MemOp : MI->memoperands()) {
386 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000387 continue;
388 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000389 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000390 if (Value->getFrameIndex() == FI)
391 return true;
392 }
393 }
394 return false;
395}
396
Sanjay Patel87c6c072015-12-10 16:34:21 +0000397/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000398/// gather register def and frame object update information.
Matthias Braun4a7c8e72018-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 Cheng058b9f02010-04-08 01:03:47 +0000404 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000405 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000406 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000407 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-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 Cheng89e74792010-04-13 20:21:05 +0000415 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000416 continue;
417 }
418
Jakob Stoklund Olesen6b17ef52012-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 Olesen5e1ac452012-02-02 23:52:57 +0000422 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000423 continue;
424 }
425
Evan Cheng058b9f02010-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 Cheng0a2aff22010-04-13 18:16:00 +0000434 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000435 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-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 Cheng058b9f02010-04-08 01:03:47 +0000439 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000440 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000441
442 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000443 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
444 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-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 Olesen6b17ef52012-01-20 22:27:12 +0000461 // register, then this is not safe. Two defs is indicated by setting a
462 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000463 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000464 if (PhysRegDefs.test(*AS))
465 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000466 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000467 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000468 if (PhysRegClobbers.test(Reg))
469 // MI defined register is seen defined by another instruction in
470 // the loop, it cannot be a LICM candidate.
471 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000472 }
473
Evan Cheng0a2aff22010-04-13 18:16:00 +0000474 // Only consider reloads for now and remats which do not have register
475 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000476 if (Def && !RuledOut) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000477 int FI = std::numeric_limits<int>::min();
Evan Cheng89e74792010-04-13 20:21:05 +0000478 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000479 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000480 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000481 }
482}
483
Sanjay Patel87c6c072015-12-10 16:34:21 +0000484/// Walk the specified region of the CFG and hoist loop invariants out to the
485/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000486void MachineLICMBase::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000487 MachineBasicBlock *Preheader = getCurPreheader();
488 if (!Preheader)
489 return;
490
Evan Cheng6ea59492010-04-07 00:41:17 +0000491 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000492 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
493 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000494
Evan Cheng058b9f02010-04-08 01:03:47 +0000495 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000496 SmallSet<int, 32> StoredFIs;
497
498 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000499 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000500 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000501 for (MachineBasicBlock *BB : Blocks) {
Bill Wendling918cea22011-10-12 02:58:01 +0000502 // If the header of the loop containing this basic block is a landing pad,
503 // then don't try to hoist instructions out of this loop.
504 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000505 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000506
Evan Cheng6ea59492010-04-07 00:41:17 +0000507 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000508 // FIXME: That means a reload that're reused in successor block(s) will not
509 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000510 for (const auto &LI : BB->liveins()) {
511 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000512 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000513 }
514
Evan Chengf192ca02011-10-11 23:48:44 +0000515 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000516 for (MachineInstr &MI : *BB)
517 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000518 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000519
Evan Cheng7fede872012-03-27 01:50:58 +0000520 // Gather the registers read / clobbered by the terminator.
521 BitVector TermRegs(NumRegs);
522 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
523 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000524 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000525 if (!MO.isReg())
526 continue;
527 unsigned Reg = MO.getReg();
528 if (!Reg)
529 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000530 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
531 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000532 }
533 }
534
Evan Cheng6ea59492010-04-07 00:41:17 +0000535 // Now evaluate whether the potential candidates qualify.
536 // 1. Check if the candidate defined register is defined by another
537 // instruction in the loop.
538 // 2. If the candidate is a load from stack slot (always true for now),
539 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000540 // 3. Make sure candidate def should not clobber
541 // registers read by the terminator. Similarly its def should not be
542 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000543 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000544 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000545 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000546 continue;
547
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000548 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000549 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000550 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000551 MachineInstr *MI = Candidate.MI;
552 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000553 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000554 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000555 unsigned Reg = MO.getReg();
556 if (PhysRegDefs.test(Reg) ||
557 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000558 // If it's using a non-loop-invariant register, then it's obviously
559 // not safe to hoist.
560 Safe = false;
561 break;
562 }
563 }
564 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000565 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000566 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000567 }
568}
569
Sanjay Patel87c6c072015-12-10 16:34:21 +0000570/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
571/// sure it is not killed by any instructions in the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000572void MachineLICMBase::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000573 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000574 for (MachineBasicBlock *BB : Blocks) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000575 if (!BB->isLiveIn(Reg))
576 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000577 for (MachineInstr &MI : *BB) {
578 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000579 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
580 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
581 MO.setIsKill(false);
582 }
583 }
584 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000585}
586
Sanjay Patel87c6c072015-12-10 16:34:21 +0000587/// When an instruction is found to only use loop invariant operands that is
588/// safe to hoist, this instruction is called to do the dirty work.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000589void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000590 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000591
Evan Cheng6ea59492010-04-07 00:41:17 +0000592 // Now move the instructions to the predecessor, inserting it before any
593 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000594 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
595 << " from " << printMBBReference(*MI->getParent()) << ": "
596 << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000597
598 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000599 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000600 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000601
Andrew Trick5209c732012-02-08 21:23:00 +0000602 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000603 // loop invariant must be kept live throughout the whole loop. This is
604 // important to ensure later passes do not scavenge the def register.
605 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000606
607 ++NumPostRAHoisted;
608 Changed = true;
609}
610
Sanjay Patel87c6c072015-12-10 16:34:21 +0000611/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
612/// may not be safe to hoist.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000613bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000614 if (SpeculationState != SpeculateUnknown)
615 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000616
Devang Patel453d4012011-10-11 18:09:58 +0000617 if (BB != CurLoop->getHeader()) {
618 // Check loop exiting blocks.
619 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
620 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000621 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
622 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000623 SpeculationState = SpeculateTrue;
624 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000625 }
626 }
627
Evan Chengf192ca02011-10-11 23:48:44 +0000628 SpeculationState = SpeculateFalse;
629 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000630}
631
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000632void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000633 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000634
Pete Cooper1eed5b52011-12-22 02:05:40 +0000635 // Remember livein register pressure.
636 BackTrace.push_back(RegPressure);
637}
Bill Wendling918cea22011-10-12 02:58:01 +0000638
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000639void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000640 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000641 BackTrace.pop_back();
642}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000643
Sanjay Patel87c6c072015-12-10 16:34:21 +0000644/// Destroy scope for the MBB that corresponds to the given dominator tree node
645/// if its a leaf or all of its children are done. Walk up the dominator tree to
646/// destroy ancestors which are now done.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000647void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
648 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
649 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000650 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000651 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000652
Pete Cooper1eed5b52011-12-22 02:05:40 +0000653 // Pop scope.
654 ExitScope(Node->getBlock());
655
656 // Now traverse upwards to pop ancestors whose offsprings are all done.
657 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
658 unsigned Left = --OpenChildren[Parent];
659 if (Left != 0)
660 break;
661 ExitScope(Parent->getBlock());
662 Node = Parent;
663 }
664}
665
Sanjay Patel87c6c072015-12-10 16:34:21 +0000666/// Walk the specified loop in the CFG (defined by all blocks dominated by the
667/// specified header block, and that are in the current loop) in depth first
668/// order w.r.t the DominatorTree. This allows us to visit definitions before
669/// uses, allowing us to hoist a loop body in one pass without iteration.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000670void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000671 MachineBasicBlock *Preheader = getCurPreheader();
672 if (!Preheader)
673 return;
674
Pete Cooper1eed5b52011-12-22 02:05:40 +0000675 SmallVector<MachineDomTreeNode*, 32> Scopes;
676 SmallVector<MachineDomTreeNode*, 8> WorkList;
677 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
678 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
679
680 // Perform a DFS walk to determine the order of visit.
681 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000682 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000683 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000684 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000685 MachineBasicBlock *BB = Node->getBlock();
686
687 // If the header of the loop containing this basic block is a landing pad,
688 // then don't try to hoist instructions out of this loop.
689 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000690 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000691 continue;
692
693 // If this subregion is not in the top level loop at all, exit.
694 if (!CurLoop->contains(BB))
695 continue;
696
697 Scopes.push_back(Node);
698 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
699 unsigned NumChildren = Children.size();
700
701 // Don't hoist things out of a large switch statement. This often causes
702 // code to be hoisted that wasn't going to be executed, and increases
703 // register pressure in a situation where it's likely to matter.
704 if (BB->succ_size() >= 25)
705 NumChildren = 0;
706
707 OpenChildren[Node] = NumChildren;
708 // Add children in reverse order as then the next popped worklist node is
709 // the first child of this node. This means we ultimately traverse the
710 // DOM tree in exactly the same order as if we'd recursed.
711 for (int i = (int)NumChildren-1; i >= 0; --i) {
712 MachineDomTreeNode *Child = Children[i];
713 ParentMap[Child] = Node;
714 WorkList.push_back(Child);
715 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000716 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000717
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000718 if (Scopes.size() == 0)
719 return;
720
721 // Compute registers which are livein into the loop headers.
722 RegSeen.clear();
723 BackTrace.clear();
724 InitRegPressure(Preheader);
725
Pete Cooper1eed5b52011-12-22 02:05:40 +0000726 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000727 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000728 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000729
Pete Cooper1eed5b52011-12-22 02:05:40 +0000730 EnterScope(MBB);
731
732 // Process the block
733 SpeculationState = SpeculateUnknown;
734 for (MachineBasicBlock::iterator
735 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
736 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
737 MachineInstr *MI = &*MII;
738 if (!Hoist(MI, Preheader))
739 UpdateRegPressure(MI);
Zaara Syeda65359932018-03-23 15:28:15 +0000740 // If we have hoisted an instruction that may store, it can only be a
741 // constant store.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000742 MII = NextMII;
743 }
744
745 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
746 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000747 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000748}
749
Sanjay Patel87c6c072015-12-10 16:34:21 +0000750/// Sink instructions into loops if profitable. This especially tries to prevent
751/// register spills caused by register pressure if there is little to no
752/// overhead moving instructions into loops.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000753void MachineLICMBase::SinkIntoLoop() {
Daniel Jasper15e69542015-03-14 10:58:38 +0000754 MachineBasicBlock *Preheader = getCurPreheader();
755 if (!Preheader)
756 return;
757
758 SmallVector<MachineInstr *, 8> Candidates;
759 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
760 I != Preheader->instr_end(); ++I) {
761 // We need to ensure that we can safely move this instruction into the loop.
Michael Liaoa5d45372017-04-26 05:27:20 +0000762 // 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 +0000763 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
764 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000765 }
766
767 for (MachineInstr *I : Candidates) {
768 const MachineOperand &MO = I->getOperand(0);
769 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
770 continue;
771 if (!MRI->hasOneDef(MO.getReg()))
772 continue;
773 bool CanSink = true;
774 MachineBasicBlock *B = nullptr;
775 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
776 // FIXME: Come up with a proper cost model that estimates whether sinking
777 // the instruction (and thus possibly executing it on every loop
778 // iteration) is more expensive than a register.
779 // For now assumes that copies are cheap and thus almost always worth it.
780 if (!MI.isCopy()) {
781 CanSink = false;
782 break;
783 }
784 if (!B) {
785 B = MI.getParent();
786 continue;
787 }
788 B = DT->findNearestCommonDominator(B, MI.getParent());
789 if (!B) {
790 CanSink = false;
791 break;
792 }
793 }
794 if (!CanSink || !B || B == Preheader)
795 continue;
796 B->splice(B->getFirstNonPHI(), Preheader, I);
797 }
798}
799
Evan Cheng87066f02010-10-20 22:03:58 +0000800static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
801 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
802}
803
Sanjay Patel87c6c072015-12-10 16:34:21 +0000804/// Find all virtual register references that are liveout of the preheader to
805/// initialize the starting "register pressure". Note this does not count live
806/// through (livein but not used) registers.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000807void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000808 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000809
Evan Cheng87066f02010-10-20 22:03:58 +0000810 // If the preheader has only a single predecessor and it ends with a
811 // fallthrough or an unconditional branch, then scan its predecessor for live
812 // defs as well. This happens whenever the preheader is created by splitting
813 // the critical edge from the loop predecessor to the loop header.
814 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000815 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000816 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000817 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000818 InitRegPressure(*BB->pred_begin());
819 }
820
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000821 for (const MachineInstr &MI : *BB)
822 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000823}
824
Sanjay Patel87c6c072015-12-10 16:34:21 +0000825/// Update estimate of register pressure after the specified instruction.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000826void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
827 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000828 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000829 for (const auto &RPIdAndCost : Cost) {
830 unsigned Class = RPIdAndCost.first;
831 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000832 RegPressure[Class] = 0;
833 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000834 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000835 }
836}
Evan Chengd62719c2010-10-14 01:16:09 +0000837
Sanjay Patel87c6c072015-12-10 16:34:21 +0000838/// Calculate the additional register pressure that the registers used in MI
839/// cause.
840///
841/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
842/// figure out which usages are live-ins.
843/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000844DenseMap<unsigned, int>
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000845MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
846 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000847 DenseMap<unsigned, int> Cost;
848 if (MI->isImplicitDef())
849 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000850 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
851 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000852 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000853 continue;
854 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000855 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000856 continue;
857
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000858 // FIXME: It seems bad to use RegSeen only for some of these calculations.
859 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000860 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
861
862 RegClassWeight W = TRI->getRegClassWeight(RC);
863 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000864 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000865 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000866 else {
867 bool isKill = isOperandKill(MO, MRI);
868 if (isNew && !isKill && ConsiderUnseenAsDef)
869 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000870 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000871 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000872 RCCost = -W.RegWeight;
873 }
874 if (RCCost == 0)
875 continue;
876 const int *PS = TRI->getRegClassPressureSets(RC);
877 for (; *PS != -1; ++PS) {
878 if (Cost.find(*PS) == Cost.end())
879 Cost[*PS] = RCCost;
880 else
881 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000882 }
Evan Chengd62719c2010-10-14 01:16:09 +0000883 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000884 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000885}
886
Sanjay Patel87c6c072015-12-10 16:34:21 +0000887/// Return true if this machine instruction loads from global offset table or
888/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000889static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000890 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liaoa5d45372017-04-26 05:27:20 +0000891
Philip Reames42bd26f2015-12-23 17:05:57 +0000892 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000893 // reads from everything..
Philip Reames42bd26f2015-12-23 17:05:57 +0000894 if (MI.memoperands_empty())
895 return true;
896
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000897 for (MachineMemOperand *MemOp : MI.memoperands())
898 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000899 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000900 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000901
Devang Patel69a45652011-10-17 17:35:01 +0000902 return false;
903}
904
Zaara Syeda65359932018-03-23 15:28:15 +0000905// This function iterates through all the operands of the input store MI and
906// checks that each register operand statisfies isCallerPreservedPhysReg.
907// This means, the value being stored and the address where it is being stored
908// is constant throughout the body of the function (not including prologue and
909// epilogue). When called with an MI that isn't a store, it returns false.
Zaara Syeda935474fe2018-04-09 14:50:02 +0000910// A future improvement can be to check if the store registers are constant
911// throughout the loop rather than throughout the funtion.
Zaara Syeda65359932018-03-23 15:28:15 +0000912static bool isInvariantStore(const MachineInstr &MI,
913 const TargetRegisterInfo *TRI,
914 const MachineRegisterInfo *MRI) {
915
Zaara Syeda935474fe2018-04-09 14:50:02 +0000916 bool FoundCallerPresReg = false;
Zaara Syeda65359932018-03-23 15:28:15 +0000917 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
918 (MI.getNumOperands() == 0))
919 return false;
920
921 // Check that all register operands are caller-preserved physical registers.
922 for (const MachineOperand &MO : MI.operands()) {
923 if (MO.isReg()) {
924 unsigned Reg = MO.getReg();
925 // If operand is a virtual register, check if it comes from a copy of a
926 // physical register.
927 if (TargetRegisterInfo::isVirtualRegister(Reg))
928 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
929 if (TargetRegisterInfo::isVirtualRegister(Reg))
930 return false;
931 if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
932 return false;
Zaara Syeda935474fe2018-04-09 14:50:02 +0000933 else
934 FoundCallerPresReg = true;
935 } else if (!MO.isImm()) {
936 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000937 }
938 }
Zaara Syeda935474fe2018-04-09 14:50:02 +0000939 return FoundCallerPresReg;
Zaara Syeda65359932018-03-23 15:28:15 +0000940}
941
942// Return true if the input MI is a copy instruction that feeds an invariant
943// store instruction. This means that the src of the copy has to satisfy
944// isCallerPreservedPhysReg and atleast one of it's users should satisfy
945// isInvariantStore.
946static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
947 const MachineRegisterInfo *MRI,
948 const TargetRegisterInfo *TRI) {
949
950 // FIXME: If targets would like to look through instructions that aren't
951 // pure copies, this can be updated to a query.
952 if (!MI.isCopy())
953 return false;
954
955 const MachineFunction *MF = MI.getMF();
956 // Check that we are copying a constant physical register.
957 unsigned CopySrcReg = MI.getOperand(1).getReg();
958 if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
959 return false;
960
961 if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
962 return false;
963
964 unsigned CopyDstReg = MI.getOperand(0).getReg();
965 // Check if any of the uses of the copy are invariant stores.
966 assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
967 "copy dst is not a virtual reg");
968
969 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
970 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
971 return true;
972 }
973 return false;
974}
975
Sanjay Patel87c6c072015-12-10 16:34:21 +0000976/// Returns true if the instruction may be a suitable candidate for LICM.
977/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000978bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000979 // Check if it's safe to move the instruction.
980 bool DontMoveAcrossStore = true;
Zaara Syeda65359932018-03-23 15:28:15 +0000981 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
982 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
Chris Lattnerc8226f32008-01-10 23:08:24 +0000983 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000984 }
Devang Patel453d4012011-10-11 18:09:58 +0000985
986 // If it is load then check if it is guaranteed to execute by making sure that
987 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000988 // the loop which does not execute this load, so we can't hoist it. Loads
989 // from constant memory are not safe to speculate all the time, for example
990 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000991 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000992 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000993 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000994 return false;
995
Evan Cheng0a2aff22010-04-13 18:16:00 +0000996 return true;
997}
998
Sanjay Patel87c6c072015-12-10 16:34:21 +0000999/// Returns true if the instruction is loop invariant.
1000/// I.e., all virtual register operands are defined outside of the loop,
1001/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +00001002/// effects that aren't captured by the operands or other flags.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001003bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
Evan Cheng0a2aff22010-04-13 18:16:00 +00001004 if (!IsLICMCandidate(I))
1005 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +00001006
Bill Wendling70613b82008-05-12 19:38:32 +00001007 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001008 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001009 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +00001010 continue;
1011
Dan Gohman79618d12009-01-15 22:01:38 +00001012 unsigned Reg = MO.getReg();
1013 if (Reg == 0) continue;
1014
1015 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +00001016 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +00001017 if (MO.isUse()) {
1018 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +00001019 // and we can freely move its uses. Alternatively, if it's allocatable,
1020 // it could get allocated to something with a def during allocation.
Lei Huangb4733ca2017-06-15 18:29:59 +00001021 // However, if the physreg is known to always be caller saved/restored
1022 // then this use is safe to hoist.
1023 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001024 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1025 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001026 // Otherwise it's safe to move.
1027 continue;
1028 } else if (!MO.isDead()) {
1029 // A def that isn't dead. We can't move it.
1030 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +00001031 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1032 // If the reg is live into the loop, we can't hoist an instruction
1033 // which would clobber it.
1034 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001035 }
1036 }
Bill Wendlingcd01e892008-08-20 20:32:05 +00001037
1038 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001039 continue;
1040
Evan Chengd62719c2010-10-14 01:16:09 +00001041 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +00001042 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001043
1044 // If the loop contains the definition of an operand, then the instruction
1045 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001046 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001047 return false;
1048 }
1049
1050 // If we got this far, the instruction is loop invariant!
1051 return true;
1052}
1053
Sanjay Patel87c6c072015-12-10 16:34:21 +00001054/// Return true if the specified instruction is used by a phi node and hoisting
1055/// it could cause a copy to be inserted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001056bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001057 SmallVector<const MachineInstr*, 8> Work(1, MI);
1058 do {
1059 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +00001060 for (const MachineOperand &MO : MI->operands()) {
1061 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001062 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00001063 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001064 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1065 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001066 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001067 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001068 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001069 // A PHI inside the loop causes a copy because the live range of Reg is
1070 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001071 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001072 return true;
1073 // A PHI in an exit block can cause a copy to be inserted if the PHI
1074 // has multiple predecessors in the loop with different values.
1075 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001076 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001077 return true;
1078 continue;
1079 }
1080 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001081 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1082 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001083 }
Evan Chengef42bea2011-04-11 21:09:18 +00001084 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001085 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001086 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001087}
1088
Sanjay Patel87c6c072015-12-10 16:34:21 +00001089/// Compute operand latency between a def of 'Reg' and an use in the current
1090/// loop, return true if the target considered it high.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001091bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1092 unsigned DefIdx,
1093 unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +00001094 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001095 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001096
Owen Andersonb36376e2014-03-17 19:36:09 +00001097 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1098 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001099 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001100 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001101 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001102 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1103 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001104 if (!MO.isReg() || !MO.isUse())
1105 continue;
1106 unsigned MOReg = MO.getReg();
1107 if (MOReg != Reg)
1108 continue;
1109
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001110 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001111 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001112 }
1113
Evan Cheng63c76082010-10-19 18:58:51 +00001114 // Only look at the first in loop use.
1115 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001116 }
1117
Evan Cheng63c76082010-10-19 18:58:51 +00001118 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001119}
1120
Sanjay Patel87c6c072015-12-10 16:34:21 +00001121/// Return true if the instruction is marked "cheap" or the operand latency
1122/// between its def and a use is one or less.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001123bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001124 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001125 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001126
1127 bool isCheap = false;
1128 unsigned NumDefs = MI.getDesc().getNumDefs();
1129 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1130 MachineOperand &DefMO = MI.getOperand(i);
1131 if (!DefMO.isReg() || !DefMO.isDef())
1132 continue;
1133 --NumDefs;
1134 unsigned Reg = DefMO.getReg();
1135 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1136 continue;
1137
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001138 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001139 return false;
1140 isCheap = true;
1141 }
1142
1143 return isCheap;
1144}
1145
Sanjay Patel87c6c072015-12-10 16:34:21 +00001146/// Visit BBs from header to current BB, check if hoisting an instruction of the
1147/// given cost matrix can cause high register pressure.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001148bool
1149MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1150 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001151 for (const auto &RPIdAndCost : Cost) {
1152 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001153 continue;
1154
Daniel Jasper274928f2015-04-14 11:56:25 +00001155 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001156 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001157
1158 // Don't hoist cheap instructions if they would increase register pressure,
1159 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001160 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001161 return true;
1162
Daniel Jasperefece522015-04-03 16:19:48 +00001163 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001164 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001165 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001166 }
1167
1168 return false;
1169}
1170
Sanjay Patel87c6c072015-12-10 16:34:21 +00001171/// Traverse the back trace from header to the current block and update their
1172/// register pressures to reflect the effect of hoisting MI from the current
1173/// block to the preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001174void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001175 // First compute the 'cost' of the instruction, i.e. its contribution
1176 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001177 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1178 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001179
1180 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001181 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001182 for (const auto &RPIdAndCost : Cost)
1183 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001184}
1185
Sanjay Patel87c6c072015-12-10 16:34:21 +00001186/// Return true if it is potentially profitable to hoist the given loop
1187/// invariant.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001188bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001189 if (MI.isImplicitDef())
1190 return true;
1191
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001192 // Besides removing computation from the loop, hoisting an instruction has
1193 // these effects:
1194 //
1195 // - The value defined by the instruction becomes live across the entire
1196 // loop. This increases register pressure in the loop.
1197 //
1198 // - If the value is used by a PHI in the loop, a copy will be required for
1199 // lowering the PHI after extending the live range.
1200 //
1201 // - When hoisting the last use of a value in the loop, that value no longer
1202 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001203
Zaara Syeda65359932018-03-23 15:28:15 +00001204 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1205 return true;
1206
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001207 bool CheapInstr = IsCheapInstruction(MI);
1208 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001209
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001210 // Don't hoist a cheap instruction if it would create a copy in the loop.
1211 if (CheapInstr && CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001212 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001213 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001214 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001215
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001216 // Rematerializable instructions should always be hoisted since the register
1217 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001218 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001219 return true;
1220
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001221 // FIXME: If there are long latency loop-invariant instructions inside the
1222 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001223 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1224 const MachineOperand &MO = MI.getOperand(i);
1225 if (!MO.isReg() || MO.isImplicit())
1226 continue;
1227 unsigned Reg = MO.getReg();
1228 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1229 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001230 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001231 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001232 ++NumHighLatency;
1233 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001234 }
1235 }
1236
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001237 // Estimate register pressure to determine whether to LICM the instruction.
1238 // In low register pressure situation, we can be more aggressive about
1239 // hoisting. Also, favors hoisting long latency instructions even in
1240 // moderately high pressure situation.
1241 // Cheap instructions will only be hoisted if they don't increase register
1242 // pressure at all.
1243 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1244 /*ConsiderUnseenAsDef=*/false);
1245
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001246 // Visit BBs from header to current BB, if hoisting this doesn't cause
1247 // high register pressure, then it's safe to proceed.
1248 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001249 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001250 ++NumLowRP;
1251 return true;
1252 }
1253
1254 // Don't risk increasing register pressure if it would create copies.
1255 if (CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001256 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001257 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001258 }
1259
1260 // Do not "speculate" in high register pressure situation. If an
1261 // instruction is not guaranteed to be executed in the loop, it's best to be
1262 // conservative.
1263 if (AvoidSpeculation &&
1264 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001265 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001266 return false;
1267 }
1268
1269 // High register pressure situation, only hoist if the instruction is going
1270 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001271 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1272 !MI.isDereferenceableInvariantLoad(AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001273 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001274 return false;
1275 }
Evan Cheng399660c2009-02-05 08:45:46 +00001276
1277 return true;
1278}
1279
Sanjay Patel87c6c072015-12-10 16:34:21 +00001280/// Unfold a load from the given machineinstr if the load itself could be
1281/// hoisted. Return the unfolded and hoistable load, or null if the load
1282/// couldn't be unfolded or if it wouldn't be hoistable.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001283MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001284 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001285 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001286 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001287
Dan Gohman104f57c2009-10-29 17:47:20 +00001288 // If not, we may be able to unfold a load and hoist that.
1289 // First test whether the instruction is loading from an amenable
1290 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001291 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001292 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001293
Dan Gohman104f57c2009-10-29 17:47:20 +00001294 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001295 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001296 unsigned NewOpc =
1297 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1298 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001299 /*UnfoldStore=*/false,
1300 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001301 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001302 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001303 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001304 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001305 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001306 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001307
Dan Gohman104f57c2009-10-29 17:47:20 +00001308 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001309 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1310 /*UnfoldLoad=*/true,
1311 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001312 (void)Success;
1313 assert(Success &&
1314 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1315 "succeeded!");
1316 assert(NewMIs.size() == 2 &&
1317 "Unfolded a load into multiple instructions!");
1318 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001319 MachineBasicBlock::iterator Pos = MI;
1320 MBB->insert(Pos, NewMIs[0]);
1321 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001322 // If unfolding produced a load that wasn't loop-invariant or profitable to
1323 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001324 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001325 NewMIs[0]->eraseFromParent();
1326 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001327 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001328 }
Evan Cheng87066f02010-10-20 22:03:58 +00001329
1330 // Update register pressure for the unfolded instruction.
1331 UpdateRegPressure(NewMIs[1]);
1332
Dan Gohman104f57c2009-10-29 17:47:20 +00001333 // Otherwise we successfully unfolded a load that we can hoist.
1334 MI->eraseFromParent();
1335 return NewMIs[0];
1336}
1337
Sanjay Patel87c6c072015-12-10 16:34:21 +00001338/// Initialize the CSE map with instructions that are in the current loop
1339/// preheader that may become duplicates of instructions that are hoisted
1340/// out of the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001341void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001342 for (MachineInstr &MI : *BB)
1343 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001344}
1345
Sanjay Patel87c6c072015-12-10 16:34:21 +00001346/// Find an instruction amount PrevMIs that is a duplicate of MI.
1347/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001348const MachineInstr*
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001349MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1350 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001351 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001352 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001353 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001354
Craig Topperc0196b12014-04-14 00:51:57 +00001355 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001356}
1357
Sanjay Patel87c6c072015-12-10 16:34:21 +00001358/// Given a LICM'ed instruction, look for an instruction on the preheader that
1359/// computes the same value. If it's found, do a RAU on with the definition of
1360/// the existing instruction rather than hoisting the instruction to the
1361/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001362bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1363 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001364 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1365 // the undef property onto uses.
1366 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001367 return false;
1368
1369 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001370 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001371
1372 // Replace virtual registers defined by MI by their counterparts defined
1373 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001374 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001375 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1376 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001377
1378 // Physical registers may not differ here.
1379 assert((!MO.isReg() || MO.getReg() == 0 ||
1380 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1381 MO.getReg() == Dup->getOperand(i).getReg()) &&
1382 "Instructions with different phys regs are not identical!");
1383
1384 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001385 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1386 Defs.push_back(i);
1387 }
1388
1389 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1390 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1391 unsigned Idx = Defs[i];
1392 unsigned Reg = MI->getOperand(Idx).getReg();
1393 unsigned DupReg = Dup->getOperand(Idx).getReg();
1394 OrigRCs.push_back(MRI->getRegClass(DupReg));
1395
1396 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1397 // Restore old RCs if more than one defs.
1398 for (unsigned j = 0; j != i; ++j)
1399 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1400 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001401 }
Evan Cheng921152f2009-11-05 00:51:13 +00001402 }
Evan Chengaa563df2011-10-17 19:50:12 +00001403
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001404 for (unsigned Idx : Defs) {
Evan Chengaa563df2011-10-17 19:50:12 +00001405 unsigned Reg = MI->getOperand(Idx).getReg();
1406 unsigned DupReg = Dup->getOperand(Idx).getReg();
1407 MRI->replaceRegWith(Reg, DupReg);
1408 MRI->clearKillFlags(DupReg);
1409 }
1410
Evan Cheng7ff83192009-11-07 03:52:02 +00001411 MI->eraseFromParent();
1412 ++NumCSEed;
1413 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001414 }
1415 return false;
1416}
1417
Sanjay Patel87c6c072015-12-10 16:34:21 +00001418/// Return true if the given instruction will be CSE'd if it's hoisted out of
1419/// the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001420bool MachineLICMBase::MayCSE(MachineInstr *MI) {
Evan Chengaf138952011-10-12 00:09:14 +00001421 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001422 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengaf138952011-10-12 00:09:14 +00001423 CI = CSEMap.find(Opcode);
1424 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1425 // the undef property onto uses.
1426 if (CI == CSEMap.end() || MI->isImplicitDef())
1427 return false;
1428
Craig Topperc0196b12014-04-14 00:51:57 +00001429 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001430}
1431
Sanjay Patel87c6c072015-12-10 16:34:21 +00001432/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001433/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001434/// It returns true if the instruction is hoisted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001435bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001436 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001437 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001438 // If not, try unfolding a hoistable load.
1439 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001440 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001441 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001442
Zaara Syeda65359932018-03-23 15:28:15 +00001443 // If we have hoisted an instruction that may store, it can only be a constant
1444 // store.
1445 if (MI->mayStore())
1446 NumStoreConst++;
1447
Dan Gohman79618d12009-01-15 22:01:38 +00001448 // Now move the instructions to the predecessor, inserting it before any
1449 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001450 LLVM_DEBUG({
1451 dbgs() << "Hoisting " << *MI;
1452 if (MI->getParent()->getBasicBlock())
1453 dbgs() << " from " << printMBBReference(*MI->getParent());
1454 if (Preheader->getBasicBlock())
1455 dbgs() << " to " << printMBBReference(*Preheader);
1456 dbgs() << "\n";
1457 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001458
Evan Chengf42b5af2009-11-03 21:40:02 +00001459 // If this is the first instruction being hoisted to the preheader,
1460 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001461 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001462 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001463 FirstInLoop = false;
1464 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001465
Evan Cheng399660c2009-02-05 08:45:46 +00001466 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001467 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001468 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengf42b5af2009-11-03 21:40:02 +00001469 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001470 if (!EliminateCSE(MI, CI)) {
1471 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001472 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001473
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001474 // Since we are moving the instruction out of its basic block, we do not
Michael Liaoa5d45372017-04-26 05:27:20 +00001475 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001476 // experience and adversely affect the accuracy of profiling information.
1477 MI->setDebugLoc(DebugLoc());
1478
Evan Cheng87066f02010-10-20 22:03:58 +00001479 // Update register pressure for BBs from header to this block.
1480 UpdateBackTraceRegPressure(MI);
1481
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001482 // Clear the kill flags of any register this instruction defines,
1483 // since they may need to be live throughout the entire loop
1484 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001485 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001486 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001487 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001488
Evan Cheng399660c2009-02-05 08:45:46 +00001489 // Add to the CSE map.
1490 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001491 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001492 else
1493 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001494 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001495
Dan Gohman79618d12009-01-15 22:01:38 +00001496 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001497 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001498
1499 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001500}
Dan Gohman3570f812010-06-22 17:25:57 +00001501
Sanjay Patel87c6c072015-12-10 16:34:21 +00001502/// Get the preheader for the current loop, splitting a critical edge if needed.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001503MachineBasicBlock *MachineLICMBase::getCurPreheader() {
Dan Gohman3570f812010-06-22 17:25:57 +00001504 // Determine the block to which to hoist instructions. If we can't find a
1505 // suitable loop predecessor, we can't do any hoisting.
1506
1507 // If we've tried to get a preheader and failed, don't try again.
1508 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001509 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001510
1511 if (!CurPreheader) {
1512 CurPreheader = CurLoop->getLoopPreheader();
1513 if (!CurPreheader) {
1514 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1515 if (!Pred) {
1516 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001517 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001518 }
1519
Quentin Colombet23341a82016-04-21 21:01:13 +00001520 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001521 if (!CurPreheader) {
1522 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001523 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001524 }
1525 }
1526 }
1527 return CurPreheader;
1528}