blob: 34c5cf571c6020cebb7a74e53db155d199ab1efe [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"),
77 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();
Matthias Braun88e21312015-06-13 03:42:11 +0000317 SchedModel.init(ST.getSchedModel(), &ST, TII);
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)
322 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
323 else
324 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000325 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) {
Philip Reames42bd26f2015-12-23 17:05:57 +0000377 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000378 // writes to all slots.
Philip Reames42bd26f2015-12-23 17:05:57 +0000379 if (MI->memoperands_empty())
380 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000381 for (const MachineMemOperand *MemOp : MI->memoperands()) {
382 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000383 continue;
384 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000385 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000386 if (Value->getFrameIndex() == FI)
387 return true;
388 }
389 }
390 return false;
391}
392
Sanjay Patel87c6c072015-12-10 16:34:21 +0000393/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000394/// gather register def and frame object update information.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000395void MachineLICMBase::ProcessMI(MachineInstr *MI,
396 BitVector &PhysRegDefs,
397 BitVector &PhysRegClobbers,
398 SmallSet<int, 32> &StoredFIs,
399 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000400 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000401 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000402 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000403 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000404 if (MO.isFI()) {
405 // Remember if the instruction stores to the frame index.
406 int FI = MO.getIndex();
407 if (!StoredFIs.count(FI) &&
408 MFI->isSpillSlotObjectIndex(FI) &&
409 InstructionStoresToFI(MI, FI))
410 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000411 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000412 continue;
413 }
414
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000415 // We can't hoist an instruction defining a physreg that is clobbered in
416 // the loop.
417 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000418 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000419 continue;
420 }
421
Evan Cheng058b9f02010-04-08 01:03:47 +0000422 if (!MO.isReg())
423 continue;
424 unsigned Reg = MO.getReg();
425 if (!Reg)
426 continue;
427 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
428 "Not expecting virtual register!");
429
Evan Cheng0a2aff22010-04-13 18:16:00 +0000430 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000431 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000432 // If it's using a non-loop-invariant register, then it's obviously not
433 // safe to hoist.
434 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000435 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000436 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000437
438 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000439 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
440 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000441 if (!MO.isDead())
442 // Non-dead implicit def? This cannot be hoisted.
443 RuledOut = true;
444 // No need to check if a dead implicit def is also defined by
445 // another instruction.
446 continue;
447 }
448
449 // FIXME: For now, avoid instructions with multiple defs, unless
450 // it's a dead implicit def.
451 if (Def)
452 RuledOut = true;
453 else
454 Def = Reg;
455
456 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000457 // register, then this is not safe. Two defs is indicated by setting a
458 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000459 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000460 if (PhysRegDefs.test(*AS))
461 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000462 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000463 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000464 if (PhysRegClobbers.test(Reg))
465 // MI defined register is seen defined by another instruction in
466 // the loop, it cannot be a LICM candidate.
467 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000468 }
469
Evan Cheng0a2aff22010-04-13 18:16:00 +0000470 // Only consider reloads for now and remats which do not have register
471 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000472 if (Def && !RuledOut) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000473 int FI = std::numeric_limits<int>::min();
Evan Cheng89e74792010-04-13 20:21:05 +0000474 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000475 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000476 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000477 }
478}
479
Sanjay Patel87c6c072015-12-10 16:34:21 +0000480/// Walk the specified region of the CFG and hoist loop invariants out to the
481/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000482void MachineLICMBase::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000483 MachineBasicBlock *Preheader = getCurPreheader();
484 if (!Preheader)
485 return;
486
Evan Cheng6ea59492010-04-07 00:41:17 +0000487 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000488 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
489 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000490
Evan Cheng058b9f02010-04-08 01:03:47 +0000491 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000492 SmallSet<int, 32> StoredFIs;
493
494 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000495 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000496 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000497 for (MachineBasicBlock *BB : Blocks) {
Bill Wendling918cea22011-10-12 02:58:01 +0000498 // If the header of the loop containing this basic block is a landing pad,
499 // then don't try to hoist instructions out of this loop.
500 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000501 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000502
Evan Cheng6ea59492010-04-07 00:41:17 +0000503 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000504 // FIXME: That means a reload that're reused in successor block(s) will not
505 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000506 for (const auto &LI : BB->liveins()) {
507 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000508 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000509 }
510
Evan Chengf192ca02011-10-11 23:48:44 +0000511 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000512 for (MachineInstr &MI : *BB)
513 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000514 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000515
Evan Cheng7fede872012-03-27 01:50:58 +0000516 // Gather the registers read / clobbered by the terminator.
517 BitVector TermRegs(NumRegs);
518 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
519 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000520 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000521 if (!MO.isReg())
522 continue;
523 unsigned Reg = MO.getReg();
524 if (!Reg)
525 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000526 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
527 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000528 }
529 }
530
Evan Cheng6ea59492010-04-07 00:41:17 +0000531 // Now evaluate whether the potential candidates qualify.
532 // 1. Check if the candidate defined register is defined by another
533 // instruction in the loop.
534 // 2. If the candidate is a load from stack slot (always true for now),
535 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000536 // 3. Make sure candidate def should not clobber
537 // registers read by the terminator. Similarly its def should not be
538 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000539 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000540 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000541 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000542 continue;
543
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000544 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000545 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000546 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000547 MachineInstr *MI = Candidate.MI;
548 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000549 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000550 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000551 unsigned Reg = MO.getReg();
552 if (PhysRegDefs.test(Reg) ||
553 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000554 // If it's using a non-loop-invariant register, then it's obviously
555 // not safe to hoist.
556 Safe = false;
557 break;
558 }
559 }
560 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000561 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000562 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000563 }
564}
565
Sanjay Patel87c6c072015-12-10 16:34:21 +0000566/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
567/// sure it is not killed by any instructions in the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000568void MachineLICMBase::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000569 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000570 for (MachineBasicBlock *BB : Blocks) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000571 if (!BB->isLiveIn(Reg))
572 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000573 for (MachineInstr &MI : *BB) {
574 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000575 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
576 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
577 MO.setIsKill(false);
578 }
579 }
580 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000581}
582
Sanjay Patel87c6c072015-12-10 16:34:21 +0000583/// When an instruction is found to only use loop invariant operands that is
584/// safe to hoist, this instruction is called to do the dirty work.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000585void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000586 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000587
Evan Cheng6ea59492010-04-07 00:41:17 +0000588 // Now move the instructions to the predecessor, inserting it before any
589 // terminator instructions.
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000590 DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader) << " from "
591 << printMBBReference(*MI->getParent()) << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000592
593 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000594 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000595 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000596
Andrew Trick5209c732012-02-08 21:23:00 +0000597 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000598 // loop invariant must be kept live throughout the whole loop. This is
599 // important to ensure later passes do not scavenge the def register.
600 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000601
602 ++NumPostRAHoisted;
603 Changed = true;
604}
605
Sanjay Patel87c6c072015-12-10 16:34:21 +0000606/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
607/// may not be safe to hoist.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000608bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000609 if (SpeculationState != SpeculateUnknown)
610 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000611
Devang Patel453d4012011-10-11 18:09:58 +0000612 if (BB != CurLoop->getHeader()) {
613 // Check loop exiting blocks.
614 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
615 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000616 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
617 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000618 SpeculationState = SpeculateTrue;
619 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000620 }
621 }
622
Evan Chengf192ca02011-10-11 23:48:44 +0000623 SpeculationState = SpeculateFalse;
624 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000625}
626
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000627void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000628 DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000629
Pete Cooper1eed5b52011-12-22 02:05:40 +0000630 // Remember livein register pressure.
631 BackTrace.push_back(RegPressure);
632}
Bill Wendling918cea22011-10-12 02:58:01 +0000633
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000634void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000635 DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000636 BackTrace.pop_back();
637}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000638
Sanjay Patel87c6c072015-12-10 16:34:21 +0000639/// Destroy scope for the MBB that corresponds to the given dominator tree node
640/// if its a leaf or all of its children are done. Walk up the dominator tree to
641/// destroy ancestors which are now done.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000642void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
643 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
644 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000645 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000646 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000647
Pete Cooper1eed5b52011-12-22 02:05:40 +0000648 // Pop scope.
649 ExitScope(Node->getBlock());
650
651 // Now traverse upwards to pop ancestors whose offsprings are all done.
652 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
653 unsigned Left = --OpenChildren[Parent];
654 if (Left != 0)
655 break;
656 ExitScope(Parent->getBlock());
657 Node = Parent;
658 }
659}
660
Sanjay Patel87c6c072015-12-10 16:34:21 +0000661/// Walk the specified loop in the CFG (defined by all blocks dominated by the
662/// specified header block, and that are in the current loop) in depth first
663/// order w.r.t the DominatorTree. This allows us to visit definitions before
664/// uses, allowing us to hoist a loop body in one pass without iteration.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000665void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000666 MachineBasicBlock *Preheader = getCurPreheader();
667 if (!Preheader)
668 return;
669
Pete Cooper1eed5b52011-12-22 02:05:40 +0000670 SmallVector<MachineDomTreeNode*, 32> Scopes;
671 SmallVector<MachineDomTreeNode*, 8> WorkList;
672 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
673 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
674
675 // Perform a DFS walk to determine the order of visit.
676 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000677 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000678 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000679 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000680 MachineBasicBlock *BB = Node->getBlock();
681
682 // If the header of the loop containing this basic block is a landing pad,
683 // then don't try to hoist instructions out of this loop.
684 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000685 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000686 continue;
687
688 // If this subregion is not in the top level loop at all, exit.
689 if (!CurLoop->contains(BB))
690 continue;
691
692 Scopes.push_back(Node);
693 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
694 unsigned NumChildren = Children.size();
695
696 // Don't hoist things out of a large switch statement. This often causes
697 // code to be hoisted that wasn't going to be executed, and increases
698 // register pressure in a situation where it's likely to matter.
699 if (BB->succ_size() >= 25)
700 NumChildren = 0;
701
702 OpenChildren[Node] = NumChildren;
703 // Add children in reverse order as then the next popped worklist node is
704 // the first child of this node. This means we ultimately traverse the
705 // DOM tree in exactly the same order as if we'd recursed.
706 for (int i = (int)NumChildren-1; i >= 0; --i) {
707 MachineDomTreeNode *Child = Children[i];
708 ParentMap[Child] = Node;
709 WorkList.push_back(Child);
710 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000711 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000712
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000713 if (Scopes.size() == 0)
714 return;
715
716 // Compute registers which are livein into the loop headers.
717 RegSeen.clear();
718 BackTrace.clear();
719 InitRegPressure(Preheader);
720
Pete Cooper1eed5b52011-12-22 02:05:40 +0000721 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000722 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000723 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000724
Pete Cooper1eed5b52011-12-22 02:05:40 +0000725 EnterScope(MBB);
726
727 // Process the block
728 SpeculationState = SpeculateUnknown;
729 for (MachineBasicBlock::iterator
730 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
731 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
732 MachineInstr *MI = &*MII;
733 if (!Hoist(MI, Preheader))
734 UpdateRegPressure(MI);
Zaara Syeda65359932018-03-23 15:28:15 +0000735 // If we have hoisted an instruction that may store, it can only be a
736 // constant store.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000737 MII = NextMII;
738 }
739
740 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
741 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000742 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000743}
744
Sanjay Patel87c6c072015-12-10 16:34:21 +0000745/// Sink instructions into loops if profitable. This especially tries to prevent
746/// register spills caused by register pressure if there is little to no
747/// overhead moving instructions into loops.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000748void MachineLICMBase::SinkIntoLoop() {
Daniel Jasper15e69542015-03-14 10:58:38 +0000749 MachineBasicBlock *Preheader = getCurPreheader();
750 if (!Preheader)
751 return;
752
753 SmallVector<MachineInstr *, 8> Candidates;
754 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
755 I != Preheader->instr_end(); ++I) {
756 // We need to ensure that we can safely move this instruction into the loop.
Michael Liaoa5d45372017-04-26 05:27:20 +0000757 // 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 +0000758 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
759 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000760 }
761
762 for (MachineInstr *I : Candidates) {
763 const MachineOperand &MO = I->getOperand(0);
764 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
765 continue;
766 if (!MRI->hasOneDef(MO.getReg()))
767 continue;
768 bool CanSink = true;
769 MachineBasicBlock *B = nullptr;
770 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
771 // FIXME: Come up with a proper cost model that estimates whether sinking
772 // the instruction (and thus possibly executing it on every loop
773 // iteration) is more expensive than a register.
774 // For now assumes that copies are cheap and thus almost always worth it.
775 if (!MI.isCopy()) {
776 CanSink = false;
777 break;
778 }
779 if (!B) {
780 B = MI.getParent();
781 continue;
782 }
783 B = DT->findNearestCommonDominator(B, MI.getParent());
784 if (!B) {
785 CanSink = false;
786 break;
787 }
788 }
789 if (!CanSink || !B || B == Preheader)
790 continue;
791 B->splice(B->getFirstNonPHI(), Preheader, I);
792 }
793}
794
Evan Cheng87066f02010-10-20 22:03:58 +0000795static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
796 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
797}
798
Sanjay Patel87c6c072015-12-10 16:34:21 +0000799/// Find all virtual register references that are liveout of the preheader to
800/// initialize the starting "register pressure". Note this does not count live
801/// through (livein but not used) registers.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000802void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000803 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000804
Evan Cheng87066f02010-10-20 22:03:58 +0000805 // If the preheader has only a single predecessor and it ends with a
806 // fallthrough or an unconditional branch, then scan its predecessor for live
807 // defs as well. This happens whenever the preheader is created by splitting
808 // the critical edge from the loop predecessor to the loop header.
809 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000810 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000811 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000812 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000813 InitRegPressure(*BB->pred_begin());
814 }
815
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000816 for (const MachineInstr &MI : *BB)
817 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000818}
819
Sanjay Patel87c6c072015-12-10 16:34:21 +0000820/// Update estimate of register pressure after the specified instruction.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000821void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
822 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000823 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000824 for (const auto &RPIdAndCost : Cost) {
825 unsigned Class = RPIdAndCost.first;
826 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000827 RegPressure[Class] = 0;
828 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000829 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000830 }
831}
Evan Chengd62719c2010-10-14 01:16:09 +0000832
Sanjay Patel87c6c072015-12-10 16:34:21 +0000833/// Calculate the additional register pressure that the registers used in MI
834/// cause.
835///
836/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
837/// figure out which usages are live-ins.
838/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000839DenseMap<unsigned, int>
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000840MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
841 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000842 DenseMap<unsigned, int> Cost;
843 if (MI->isImplicitDef())
844 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000845 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
846 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000847 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000848 continue;
849 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000850 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000851 continue;
852
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000853 // FIXME: It seems bad to use RegSeen only for some of these calculations.
854 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000855 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
856
857 RegClassWeight W = TRI->getRegClassWeight(RC);
858 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000859 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000860 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000861 else {
862 bool isKill = isOperandKill(MO, MRI);
863 if (isNew && !isKill && ConsiderUnseenAsDef)
864 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000865 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000866 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000867 RCCost = -W.RegWeight;
868 }
869 if (RCCost == 0)
870 continue;
871 const int *PS = TRI->getRegClassPressureSets(RC);
872 for (; *PS != -1; ++PS) {
873 if (Cost.find(*PS) == Cost.end())
874 Cost[*PS] = RCCost;
875 else
876 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000877 }
Evan Chengd62719c2010-10-14 01:16:09 +0000878 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000879 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000880}
881
Sanjay Patel87c6c072015-12-10 16:34:21 +0000882/// Return true if this machine instruction loads from global offset table or
883/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000884static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000885 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liaoa5d45372017-04-26 05:27:20 +0000886
Philip Reames42bd26f2015-12-23 17:05:57 +0000887 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000888 // reads from everything..
Philip Reames42bd26f2015-12-23 17:05:57 +0000889 if (MI.memoperands_empty())
890 return true;
891
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000892 for (MachineMemOperand *MemOp : MI.memoperands())
893 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000894 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000895 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000896
Devang Patel69a45652011-10-17 17:35:01 +0000897 return false;
898}
899
Zaara Syeda65359932018-03-23 15:28:15 +0000900// This function iterates through all the operands of the input store MI and
901// checks that each register operand statisfies isCallerPreservedPhysReg.
902// This means, the value being stored and the address where it is being stored
903// is constant throughout the body of the function (not including prologue and
904// epilogue). When called with an MI that isn't a store, it returns false.
905static bool isInvariantStore(const MachineInstr &MI,
906 const TargetRegisterInfo *TRI,
907 const MachineRegisterInfo *MRI) {
908
909 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
910 (MI.getNumOperands() == 0))
911 return false;
912
913 // Check that all register operands are caller-preserved physical registers.
914 for (const MachineOperand &MO : MI.operands()) {
915 if (MO.isReg()) {
916 unsigned Reg = MO.getReg();
917 // If operand is a virtual register, check if it comes from a copy of a
918 // physical register.
919 if (TargetRegisterInfo::isVirtualRegister(Reg))
920 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
921 if (TargetRegisterInfo::isVirtualRegister(Reg))
922 return false;
923 if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
924 return false;
925 }
926 }
927 return true;
928}
929
930// Return true if the input MI is a copy instruction that feeds an invariant
931// store instruction. This means that the src of the copy has to satisfy
932// isCallerPreservedPhysReg and atleast one of it's users should satisfy
933// isInvariantStore.
934static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
935 const MachineRegisterInfo *MRI,
936 const TargetRegisterInfo *TRI) {
937
938 // FIXME: If targets would like to look through instructions that aren't
939 // pure copies, this can be updated to a query.
940 if (!MI.isCopy())
941 return false;
942
943 const MachineFunction *MF = MI.getMF();
944 // Check that we are copying a constant physical register.
945 unsigned CopySrcReg = MI.getOperand(1).getReg();
946 if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
947 return false;
948
949 if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
950 return false;
951
952 unsigned CopyDstReg = MI.getOperand(0).getReg();
953 // Check if any of the uses of the copy are invariant stores.
954 assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
955 "copy dst is not a virtual reg");
956
957 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
958 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
959 return true;
960 }
961 return false;
962}
963
Sanjay Patel87c6c072015-12-10 16:34:21 +0000964/// Returns true if the instruction may be a suitable candidate for LICM.
965/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000966bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000967 // Check if it's safe to move the instruction.
968 bool DontMoveAcrossStore = true;
Zaara Syeda65359932018-03-23 15:28:15 +0000969 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
970 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
Chris Lattnerc8226f32008-01-10 23:08:24 +0000971 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000972 }
Devang Patel453d4012011-10-11 18:09:58 +0000973
974 // If it is load then check if it is guaranteed to execute by making sure that
975 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000976 // the loop which does not execute this load, so we can't hoist it. Loads
977 // from constant memory are not safe to speculate all the time, for example
978 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000979 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000980 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000981 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000982 return false;
983
Evan Cheng0a2aff22010-04-13 18:16:00 +0000984 return true;
985}
986
Sanjay Patel87c6c072015-12-10 16:34:21 +0000987/// Returns true if the instruction is loop invariant.
988/// I.e., all virtual register operands are defined outside of the loop,
989/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +0000990/// effects that aren't captured by the operands or other flags.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000991bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000992 if (!IsLICMCandidate(I))
993 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000994
Bill Wendling70613b82008-05-12 19:38:32 +0000995 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000996 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000997 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000998 continue;
999
Dan Gohman79618d12009-01-15 22:01:38 +00001000 unsigned Reg = MO.getReg();
1001 if (Reg == 0) continue;
1002
1003 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +00001004 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +00001005 if (MO.isUse()) {
1006 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +00001007 // and we can freely move its uses. Alternatively, if it's allocatable,
1008 // it could get allocated to something with a def during allocation.
Lei Huangb4733ca2017-06-15 18:29:59 +00001009 // However, if the physreg is known to always be caller saved/restored
1010 // then this use is safe to hoist.
1011 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001012 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1013 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001014 // Otherwise it's safe to move.
1015 continue;
1016 } else if (!MO.isDead()) {
1017 // A def that isn't dead. We can't move it.
1018 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +00001019 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1020 // If the reg is live into the loop, we can't hoist an instruction
1021 // which would clobber it.
1022 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001023 }
1024 }
Bill Wendlingcd01e892008-08-20 20:32:05 +00001025
1026 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001027 continue;
1028
Evan Chengd62719c2010-10-14 01:16:09 +00001029 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +00001030 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001031
1032 // If the loop contains the definition of an operand, then the instruction
1033 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001034 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001035 return false;
1036 }
1037
1038 // If we got this far, the instruction is loop invariant!
1039 return true;
1040}
1041
Sanjay Patel87c6c072015-12-10 16:34:21 +00001042/// Return true if the specified instruction is used by a phi node and hoisting
1043/// it could cause a copy to be inserted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001044bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001045 SmallVector<const MachineInstr*, 8> Work(1, MI);
1046 do {
1047 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +00001048 for (const MachineOperand &MO : MI->operands()) {
1049 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001050 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00001051 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001052 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1053 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001054 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001055 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001056 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001057 // A PHI inside the loop causes a copy because the live range of Reg is
1058 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001059 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001060 return true;
1061 // A PHI in an exit block can cause a copy to be inserted if the PHI
1062 // has multiple predecessors in the loop with different values.
1063 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001064 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001065 return true;
1066 continue;
1067 }
1068 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001069 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1070 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001071 }
Evan Chengef42bea2011-04-11 21:09:18 +00001072 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001073 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001074 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001075}
1076
Sanjay Patel87c6c072015-12-10 16:34:21 +00001077/// Compute operand latency between a def of 'Reg' and an use in the current
1078/// loop, return true if the target considered it high.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001079bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1080 unsigned DefIdx,
1081 unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +00001082 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001083 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001084
Owen Andersonb36376e2014-03-17 19:36:09 +00001085 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1086 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001087 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001088 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001089 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001090 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1091 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001092 if (!MO.isReg() || !MO.isUse())
1093 continue;
1094 unsigned MOReg = MO.getReg();
1095 if (MOReg != Reg)
1096 continue;
1097
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001098 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001099 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001100 }
1101
Evan Cheng63c76082010-10-19 18:58:51 +00001102 // Only look at the first in loop use.
1103 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001104 }
1105
Evan Cheng63c76082010-10-19 18:58:51 +00001106 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001107}
1108
Sanjay Patel87c6c072015-12-10 16:34:21 +00001109/// Return true if the instruction is marked "cheap" or the operand latency
1110/// between its def and a use is one or less.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001111bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001112 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001113 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001114
1115 bool isCheap = false;
1116 unsigned NumDefs = MI.getDesc().getNumDefs();
1117 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1118 MachineOperand &DefMO = MI.getOperand(i);
1119 if (!DefMO.isReg() || !DefMO.isDef())
1120 continue;
1121 --NumDefs;
1122 unsigned Reg = DefMO.getReg();
1123 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1124 continue;
1125
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001126 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001127 return false;
1128 isCheap = true;
1129 }
1130
1131 return isCheap;
1132}
1133
Sanjay Patel87c6c072015-12-10 16:34:21 +00001134/// Visit BBs from header to current BB, check if hoisting an instruction of the
1135/// given cost matrix can cause high register pressure.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001136bool
1137MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1138 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001139 for (const auto &RPIdAndCost : Cost) {
1140 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001141 continue;
1142
Daniel Jasper274928f2015-04-14 11:56:25 +00001143 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001144 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001145
1146 // Don't hoist cheap instructions if they would increase register pressure,
1147 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001148 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001149 return true;
1150
Daniel Jasperefece522015-04-03 16:19:48 +00001151 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001152 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001153 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001154 }
1155
1156 return false;
1157}
1158
Sanjay Patel87c6c072015-12-10 16:34:21 +00001159/// Traverse the back trace from header to the current block and update their
1160/// register pressures to reflect the effect of hoisting MI from the current
1161/// block to the preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001162void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001163 // First compute the 'cost' of the instruction, i.e. its contribution
1164 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001165 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1166 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001167
1168 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001169 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001170 for (const auto &RPIdAndCost : Cost)
1171 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001172}
1173
Sanjay Patel87c6c072015-12-10 16:34:21 +00001174/// Return true if it is potentially profitable to hoist the given loop
1175/// invariant.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001176bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001177 if (MI.isImplicitDef())
1178 return true;
1179
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001180 // Besides removing computation from the loop, hoisting an instruction has
1181 // these effects:
1182 //
1183 // - The value defined by the instruction becomes live across the entire
1184 // loop. This increases register pressure in the loop.
1185 //
1186 // - If the value is used by a PHI in the loop, a copy will be required for
1187 // lowering the PHI after extending the live range.
1188 //
1189 // - When hoisting the last use of a value in the loop, that value no longer
1190 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001191
Zaara Syeda65359932018-03-23 15:28:15 +00001192 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1193 return true;
1194
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001195 bool CheapInstr = IsCheapInstruction(MI);
1196 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001197
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001198 // Don't hoist a cheap instruction if it would create a copy in the loop.
1199 if (CheapInstr && CreatesCopy) {
1200 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1201 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001202 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001203
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001204 // Rematerializable instructions should always be hoisted since the register
1205 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001206 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001207 return true;
1208
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001209 // FIXME: If there are long latency loop-invariant instructions inside the
1210 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001211 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1212 const MachineOperand &MO = MI.getOperand(i);
1213 if (!MO.isReg() || MO.isImplicit())
1214 continue;
1215 unsigned Reg = MO.getReg();
1216 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1217 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001218 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1219 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1220 ++NumHighLatency;
1221 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001222 }
1223 }
1224
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001225 // Estimate register pressure to determine whether to LICM the instruction.
1226 // In low register pressure situation, we can be more aggressive about
1227 // hoisting. Also, favors hoisting long latency instructions even in
1228 // moderately high pressure situation.
1229 // Cheap instructions will only be hoisted if they don't increase register
1230 // pressure at all.
1231 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1232 /*ConsiderUnseenAsDef=*/false);
1233
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001234 // Visit BBs from header to current BB, if hoisting this doesn't cause
1235 // high register pressure, then it's safe to proceed.
1236 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1237 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1238 ++NumLowRP;
1239 return true;
1240 }
1241
1242 // Don't risk increasing register pressure if it would create copies.
1243 if (CreatesCopy) {
1244 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001245 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001246 }
1247
1248 // Do not "speculate" in high register pressure situation. If an
1249 // instruction is not guaranteed to be executed in the loop, it's best to be
1250 // conservative.
1251 if (AvoidSpeculation &&
1252 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1253 DEBUG(dbgs() << "Won't speculate: " << MI);
1254 return false;
1255 }
1256
1257 // High register pressure situation, only hoist if the instruction is going
1258 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001259 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1260 !MI.isDereferenceableInvariantLoad(AA)) {
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001261 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1262 return false;
1263 }
Evan Cheng399660c2009-02-05 08:45:46 +00001264
1265 return true;
1266}
1267
Sanjay Patel87c6c072015-12-10 16:34:21 +00001268/// Unfold a load from the given machineinstr if the load itself could be
1269/// hoisted. Return the unfolded and hoistable load, or null if the load
1270/// couldn't be unfolded or if it wouldn't be hoistable.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001271MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001272 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001273 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001274 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001275
Dan Gohman104f57c2009-10-29 17:47:20 +00001276 // If not, we may be able to unfold a load and hoist that.
1277 // First test whether the instruction is loading from an amenable
1278 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001279 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001280 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001281
Dan Gohman104f57c2009-10-29 17:47:20 +00001282 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001283 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001284 unsigned NewOpc =
1285 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1286 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001287 /*UnfoldStore=*/false,
1288 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001289 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001290 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001291 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001292 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001293 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001294 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001295
Dan Gohman104f57c2009-10-29 17:47:20 +00001296 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001297 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1298 /*UnfoldLoad=*/true,
1299 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001300 (void)Success;
1301 assert(Success &&
1302 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1303 "succeeded!");
1304 assert(NewMIs.size() == 2 &&
1305 "Unfolded a load into multiple instructions!");
1306 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001307 MachineBasicBlock::iterator Pos = MI;
1308 MBB->insert(Pos, NewMIs[0]);
1309 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001310 // If unfolding produced a load that wasn't loop-invariant or profitable to
1311 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001312 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001313 NewMIs[0]->eraseFromParent();
1314 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001315 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001316 }
Evan Cheng87066f02010-10-20 22:03:58 +00001317
1318 // Update register pressure for the unfolded instruction.
1319 UpdateRegPressure(NewMIs[1]);
1320
Dan Gohman104f57c2009-10-29 17:47:20 +00001321 // Otherwise we successfully unfolded a load that we can hoist.
1322 MI->eraseFromParent();
1323 return NewMIs[0];
1324}
1325
Sanjay Patel87c6c072015-12-10 16:34:21 +00001326/// Initialize the CSE map with instructions that are in the current loop
1327/// preheader that may become duplicates of instructions that are hoisted
1328/// out of the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001329void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001330 for (MachineInstr &MI : *BB)
1331 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001332}
1333
Sanjay Patel87c6c072015-12-10 16:34:21 +00001334/// Find an instruction amount PrevMIs that is a duplicate of MI.
1335/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001336const MachineInstr*
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001337MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1338 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001339 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001340 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001341 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001342
Craig Topperc0196b12014-04-14 00:51:57 +00001343 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001344}
1345
Sanjay Patel87c6c072015-12-10 16:34:21 +00001346/// Given a LICM'ed instruction, look for an instruction on the preheader that
1347/// computes the same value. If it's found, do a RAU on with the definition of
1348/// the existing instruction rather than hoisting the instruction to the
1349/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001350bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1351 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001352 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1353 // the undef property onto uses.
1354 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001355 return false;
1356
1357 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001358 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001359
1360 // Replace virtual registers defined by MI by their counterparts defined
1361 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001362 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001363 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1364 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001365
1366 // Physical registers may not differ here.
1367 assert((!MO.isReg() || MO.getReg() == 0 ||
1368 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1369 MO.getReg() == Dup->getOperand(i).getReg()) &&
1370 "Instructions with different phys regs are not identical!");
1371
1372 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001373 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1374 Defs.push_back(i);
1375 }
1376
1377 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1378 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1379 unsigned Idx = Defs[i];
1380 unsigned Reg = MI->getOperand(Idx).getReg();
1381 unsigned DupReg = Dup->getOperand(Idx).getReg();
1382 OrigRCs.push_back(MRI->getRegClass(DupReg));
1383
1384 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1385 // Restore old RCs if more than one defs.
1386 for (unsigned j = 0; j != i; ++j)
1387 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1388 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001389 }
Evan Cheng921152f2009-11-05 00:51:13 +00001390 }
Evan Chengaa563df2011-10-17 19:50:12 +00001391
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001392 for (unsigned Idx : Defs) {
Evan Chengaa563df2011-10-17 19:50:12 +00001393 unsigned Reg = MI->getOperand(Idx).getReg();
1394 unsigned DupReg = Dup->getOperand(Idx).getReg();
1395 MRI->replaceRegWith(Reg, DupReg);
1396 MRI->clearKillFlags(DupReg);
1397 }
1398
Evan Cheng7ff83192009-11-07 03:52:02 +00001399 MI->eraseFromParent();
1400 ++NumCSEed;
1401 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001402 }
1403 return false;
1404}
1405
Sanjay Patel87c6c072015-12-10 16:34:21 +00001406/// Return true if the given instruction will be CSE'd if it's hoisted out of
1407/// the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001408bool MachineLICMBase::MayCSE(MachineInstr *MI) {
Evan Chengaf138952011-10-12 00:09:14 +00001409 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001410 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengaf138952011-10-12 00:09:14 +00001411 CI = CSEMap.find(Opcode);
1412 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1413 // the undef property onto uses.
1414 if (CI == CSEMap.end() || MI->isImplicitDef())
1415 return false;
1416
Craig Topperc0196b12014-04-14 00:51:57 +00001417 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001418}
1419
Sanjay Patel87c6c072015-12-10 16:34:21 +00001420/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001421/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001422/// It returns true if the instruction is hoisted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001423bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001424 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001425 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001426 // If not, try unfolding a hoistable load.
1427 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001428 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001429 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001430
Zaara Syeda65359932018-03-23 15:28:15 +00001431 // If we have hoisted an instruction that may store, it can only be a constant
1432 // store.
1433 if (MI->mayStore())
1434 NumStoreConst++;
1435
Dan Gohman79618d12009-01-15 22:01:38 +00001436 // Now move the instructions to the predecessor, inserting it before any
1437 // terminator instructions.
1438 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001439 dbgs() << "Hoisting " << *MI;
Dan Gohman1b44f102009-10-28 03:21:57 +00001440 if (MI->getParent()->getBasicBlock())
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001441 dbgs() << " from " << printMBBReference(*MI->getParent());
Justin Lebarf6f4a2a2016-05-23 18:56:07 +00001442 if (Preheader->getBasicBlock())
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001443 dbgs() << " to " << printMBBReference(*Preheader);
David Greene55cf95c2010-01-05 00:03:48 +00001444 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001445 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001446
Evan Chengf42b5af2009-11-03 21:40:02 +00001447 // If this is the first instruction being hoisted to the preheader,
1448 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001449 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001450 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001451 FirstInLoop = false;
1452 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001453
Evan Cheng399660c2009-02-05 08:45:46 +00001454 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001455 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001456 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengf42b5af2009-11-03 21:40:02 +00001457 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001458 if (!EliminateCSE(MI, CI)) {
1459 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001460 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001461
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001462 // Since we are moving the instruction out of its basic block, we do not
Michael Liaoa5d45372017-04-26 05:27:20 +00001463 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001464 // experience and adversely affect the accuracy of profiling information.
1465 MI->setDebugLoc(DebugLoc());
1466
Evan Cheng87066f02010-10-20 22:03:58 +00001467 // Update register pressure for BBs from header to this block.
1468 UpdateBackTraceRegPressure(MI);
1469
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001470 // Clear the kill flags of any register this instruction defines,
1471 // since they may need to be live throughout the entire loop
1472 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001473 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001474 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001475 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001476
Evan Cheng399660c2009-02-05 08:45:46 +00001477 // Add to the CSE map.
1478 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001479 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001480 else
1481 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001482 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001483
Dan Gohman79618d12009-01-15 22:01:38 +00001484 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001485 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001486
1487 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001488}
Dan Gohman3570f812010-06-22 17:25:57 +00001489
Sanjay Patel87c6c072015-12-10 16:34:21 +00001490/// Get the preheader for the current loop, splitting a critical edge if needed.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001491MachineBasicBlock *MachineLICMBase::getCurPreheader() {
Dan Gohman3570f812010-06-22 17:25:57 +00001492 // Determine the block to which to hoist instructions. If we can't find a
1493 // suitable loop predecessor, we can't do any hoisting.
1494
1495 // If we've tried to get a preheader and failed, don't try again.
1496 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001497 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001498
1499 if (!CurPreheader) {
1500 CurPreheader = CurLoop->getLoopPreheader();
1501 if (!CurPreheader) {
1502 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1503 if (!Pred) {
1504 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001505 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001506 }
1507
Quentin Colombet23341a82016-04-21 21:01:13 +00001508 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001509 if (!CurPreheader) {
1510 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001511 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001512 }
1513 }
1514 }
1515 return CurPreheader;
1516}