blob: 194125feea0db3bd831b0e6b02a13632addfd54f [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Bill Wendlingfb706bc2007-12-07 21:42:31 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs loop invariant code motion on machine instructions. We
10// attempt to remove as much code from the body of a loop as possible.
11//
Dan Gohman79618d12009-01-15 22:01:38 +000012// This pass is not intended to be a replacement or a complete alternative
13// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
14// constructs that are not exposed before lowering and instruction selection.
15//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000016//===----------------------------------------------------------------------===//
17
Eugene Zelenkof1933322017-09-22 23:46:57 +000018#include "llvm/ADT/BitVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000022#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Victor Huangedab7dd2019-11-11 21:32:56 +000026#include "llvm/CodeGen/MachineBlockFrequencyInfo.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);
Victor Huangedab7dd2019-11-11 21:32:56 +000078// The default threshold of 100 (i.e. if target block is 100 times hotter)
79// is based on empirical data on a single target and is subject to tuning.
80static cl::opt<unsigned>
81BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
82 cl::desc("Do not hoist instructions if target"
83 "block is N times hotter than the source."),
84 cl::init(100), cl::Hidden);
85
86enum class UseBFI { None, PGO, All };
87
88static cl::opt<UseBFI>
89DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
90 cl::desc("Disable hoisting instructions to"
91 " hotter blocks"),
92 cl::init(UseBFI::None), cl::Hidden,
93 cl::values(clEnumValN(UseBFI::None, "none",
94 "disable the feature"),
95 clEnumValN(UseBFI::PGO, "pgo",
96 "enable the feature when using profile data"),
97 clEnumValN(UseBFI::All, "all",
98 "enable the feature with/wo profile data")));
Daniel Jasper15e69542015-03-14 10:58:38 +000099
Evan Cheng44436302010-10-16 02:20:26 +0000100STATISTIC(NumHoisted,
101 "Number of machine instructions hoisted out of loops");
102STATISTIC(NumLowRP,
103 "Number of instructions hoisted in low reg pressure situation");
104STATISTIC(NumHighLatency,
105 "Number of high latency instructions hoisted");
106STATISTIC(NumCSEed,
107 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +0000108STATISTIC(NumPostRAHoisted,
109 "Number of machine instructions hoisted out of loops post regalloc");
Zaara Syeda65359932018-03-23 15:28:15 +0000110STATISTIC(NumStoreConst,
111 "Number of stores of const phys reg hoisted out of loops");
Victor Huangedab7dd2019-11-11 21:32:56 +0000112STATISTIC(NumNotHoistedDueToHotness,
113 "Number of instructions not hoisted due to block frequency");
Bill Wendling43751732007-12-08 01:47:01 +0000114
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000115namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000116
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000117 class MachineLICMBase : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +0000118 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000119 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000120 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +0000121 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +0000122 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +0000123 TargetSchedModel SchedModel;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000124 bool PreRegAlloc;
Victor Huangedab7dd2019-11-11 21:32:56 +0000125 bool HasProfileData;
Bill Wendlingb678ae72007-12-11 19:40:06 +0000126
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000127 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000128 AliasAnalysis *AA; // Alias analysis info.
Victor Huangedab7dd2019-11-11 21:32:56 +0000129 MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info
Evan Cheng058b9f02010-04-08 01:03:47 +0000130 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +0000131 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000132
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000133 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +0000134 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +0000135 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +0000136 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +0000137 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +0000138
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000139 // Exit blocks for CurLoop.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000140 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000141
142 bool isExitBlock(const MachineBasicBlock *MBB) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000143 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000144 }
145
Evan Chengd62719c2010-10-14 01:16:09 +0000146 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000147 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000148 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000149
Daniel Jasper274928f2015-04-14 11:56:25 +0000150 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000151 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000152 SmallVector<unsigned, 8> RegLimit;
153
Evan Cheng44436302010-10-16 02:20:26 +0000154 // Register pressure on path leading from loop preheader to current BB.
155 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
156
Dale Johannesen329d4742010-07-29 17:45:24 +0000157 // For each opcode, keep a list of potential CSE instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000158 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000159
Evan Chengf192ca02011-10-11 23:48:44 +0000160 enum {
161 SpeculateFalse = 0,
162 SpeculateTrue = 1,
163 SpeculateUnknown = 2
164 };
165
Devang Patel453d4012011-10-11 18:09:58 +0000166 // If a MBB does not dominate loop exiting blocks then it may not safe
167 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000168 // Tri-state: 0 - false, 1 - true, 2 - unknown
169 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000170
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000171 public:
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000172 MachineLICMBase(char &PassID, bool PreRegAlloc)
173 : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000174
Craig Topper4584cd52014-03-07 09:26:03 +0000175 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000176
Craig Topper4584cd52014-03-07 09:26:03 +0000177 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000178 AU.addRequired<MachineLoopInfo>();
Victor Huangedab7dd2019-11-11 21:32:56 +0000179 if (DisableHoistingToHotterBlocks != UseBFI::None)
180 AU.addRequired<MachineBlockFrequencyInfo>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000181 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000182 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000183 AU.addPreserved<MachineLoopInfo>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000184 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000185 }
Evan Cheng399660c2009-02-05 08:45:46 +0000186
Craig Topper4584cd52014-03-07 09:26:03 +0000187 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000188 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000189 RegPressure.clear();
190 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000191 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000192 CSEMap.clear();
193 }
194
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000195 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000196 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000197 struct CandidateInfo {
198 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000199 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000200 int FI;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000201
Evan Cheng0a2aff22010-04-13 18:16:00 +0000202 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
203 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000204 };
205
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000206 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000207
Evan Cheng058b9f02010-04-08 01:03:47 +0000208 void HoistPostRA(MachineInstr *MI, unsigned Def);
209
Sanjay Patel87c6c072015-12-10 16:34:21 +0000210 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
211 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000212 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000213
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000214 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000215
Evan Cheng0a2aff22010-04-13 18:16:00 +0000216 bool IsLICMCandidate(MachineInstr &I);
217
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000218 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000219
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000220 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000221
Evan Chenge96b8d72010-10-26 02:08:50 +0000222 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
223 unsigned Reg) const;
224
225 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000226
Daniel Jasperefece522015-04-03 16:19:48 +0000227 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
228 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000229
Evan Cheng87066f02010-10-20 22:03:58 +0000230 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000231
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000232 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000233
Devang Patel453d4012011-10-11 18:09:58 +0000234 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
235
Pete Cooper1eed5b52011-12-22 02:05:40 +0000236 void EnterScope(MachineBasicBlock *MBB);
237
238 void ExitScope(MachineBasicBlock *MBB);
239
Sanjay Patel87c6c072015-12-10 16:34:21 +0000240 void ExitScopeIfDone(
241 MachineDomTreeNode *Node,
242 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
243 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000244
Fangrui Songcb0bab82018-07-16 18:51:40 +0000245 void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000246
Pete Cooper1eed5b52011-12-22 02:05:40 +0000247 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000248
Daniel Jasper15e69542015-03-14 10:58:38 +0000249 void SinkIntoLoop();
250
Evan Chengd62719c2010-10-14 01:16:09 +0000251 void InitRegPressure(MachineBasicBlock *BB);
252
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000253 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
254 bool ConsiderSeen,
255 bool ConsiderUnseenAsDef);
256
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000257 void UpdateRegPressure(const MachineInstr *MI,
258 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000259
Dan Gohman104f57c2009-10-29 17:47:20 +0000260 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
261
Sanjay Patel87c6c072015-12-10 16:34:21 +0000262 const MachineInstr *
263 LookForDuplicate(const MachineInstr *MI,
264 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000265
Sanjay Patel87c6c072015-12-10 16:34:21 +0000266 bool EliminateCSE(
267 MachineInstr *MI,
268 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000269
Evan Chengaf138952011-10-12 00:09:14 +0000270 bool MayCSE(MachineInstr *MI);
271
Evan Cheng87066f02010-10-20 22:03:58 +0000272 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000273
Evan Chengf42b5af2009-11-03 21:40:02 +0000274 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000275
Victor Huangedab7dd2019-11-11 21:32:56 +0000276 bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
277 MachineBasicBlock *TgtBlock);
Dan Gohman3570f812010-06-22 17:25:57 +0000278 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000279 };
Eugene Zelenkof1933322017-09-22 23:46:57 +0000280
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000281 class MachineLICM : public MachineLICMBase {
282 public:
283 static char ID;
284 MachineLICM() : MachineLICMBase(ID, false) {
285 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
286 }
287 };
288
289 class EarlyMachineLICM : public MachineLICMBase {
290 public:
291 static char ID;
292 EarlyMachineLICM() : MachineLICMBase(ID, true) {
293 initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
294 }
295 };
296
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000297} // end anonymous namespace
298
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000299char MachineLICM::ID;
300char EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000301
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000302char &llvm::MachineLICMID = MachineLICM::ID;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000303char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000304
Matthias Braun1527baa2017-05-25 21:26:32 +0000305INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
306 "Machine Loop Invariant Code Motion", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000307INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Victor Huangedab7dd2019-11-11 21:32:56 +0000308INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000309INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000310INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000311INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
312 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000313
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000314INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
315 "Early Machine Loop Invariant Code Motion", false, false)
316INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Victor Huangedab7dd2019-11-11 21:32:56 +0000317INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000318INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
319INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
320INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
321 "Early Machine Loop Invariant Code Motion", false, false)
322
Sanjay Patel87c6c072015-12-10 16:34:21 +0000323/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000324static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000325 // Check whether this loop even has a unique predecessor.
326 if (!CurLoop->getLoopPredecessor())
327 return false;
328 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000329 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000330 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000331 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000332 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000333 return true;
334}
335
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000336bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000337 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000338 return false;
339
Evan Cheng032f3262010-05-29 00:06:36 +0000340 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000341 const TargetSubtargetInfo &ST = MF.getSubtarget();
342 TII = ST.getInstrInfo();
343 TLI = ST.getTargetLowering();
344 TRI = ST.getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000345 MFI = &MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000346 MRI = &MF.getRegInfo();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000347 SchedModel.init(&ST);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000348
Andrew Trickc40815d2012-02-08 21:23:03 +0000349 PreRegAlloc = MRI->isSSA();
Victor Huangedab7dd2019-11-11 21:32:56 +0000350 HasProfileData = MF.getFunction().hasProfileData();
Andrew Trickc40815d2012-02-08 21:23:03 +0000351
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000352 if (PreRegAlloc)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000354 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000355 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
356 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000357
Evan Chengd62719c2010-10-14 01:16:09 +0000358 if (PreRegAlloc) {
359 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000360 unsigned NumRPS = TRI->getNumRegPressureSets();
361 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000362 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000363 RegLimit.resize(NumRPS);
364 for (unsigned i = 0, e = NumRPS; i != e; ++i)
365 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000366 }
367
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000368 // Get our Loop information...
Victor Huangedab7dd2019-11-11 21:32:56 +0000369 if (DisableHoistingToHotterBlocks != UseBFI::None)
370 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Evan Cheng058b9f02010-04-08 01:03:47 +0000371 MLI = &getAnalysis<MachineLoopInfo>();
372 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000373 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000374
Dan Gohman7929c442010-07-09 18:49:45 +0000375 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
376 while (!Worklist.empty()) {
377 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000378 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000379 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000380
Evan Cheng058b9f02010-04-08 01:03:47 +0000381 // If this is done before regalloc, only visit outer-most preheader-sporting
382 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000383 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
384 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000385 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000386 }
Dan Gohman79618d12009-01-15 22:01:38 +0000387
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000388 CurLoop->getExitBlocks(ExitBlocks);
389
Evan Cheng6ea59492010-04-07 00:41:17 +0000390 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000391 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000392 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000393 // CSEMap is initialized for loop header when the first instruction is
394 // being hoisted.
395 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000396 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000397 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000398 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000399
400 if (SinkInstsToAvoidSpills)
401 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000402 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000403 }
404
405 return Changed;
406}
407
Sanjay Patel87c6c072015-12-10 16:34:21 +0000408/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000409static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Geoff Berry8e4958e2018-05-04 19:25:09 +0000410 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
411 // true since they have no memory operands.
412 if (!MI->mayStore())
413 return false;
Philip Reames42bd26f2015-12-23 17:05:57 +0000414 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000415 // writes to all slots.
Philip Reames42bd26f2015-12-23 17:05:57 +0000416 if (MI->memoperands_empty())
417 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000418 for (const MachineMemOperand *MemOp : MI->memoperands()) {
419 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000420 continue;
421 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000422 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000423 if (Value->getFrameIndex() == FI)
424 return true;
425 }
426 }
427 return false;
428}
429
Sanjay Patel87c6c072015-12-10 16:34:21 +0000430/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000431/// gather register def and frame object update information.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000432void MachineLICMBase::ProcessMI(MachineInstr *MI,
433 BitVector &PhysRegDefs,
434 BitVector &PhysRegClobbers,
435 SmallSet<int, 32> &StoredFIs,
436 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000437 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000438 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000439 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000440 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000441 if (MO.isFI()) {
442 // Remember if the instruction stores to the frame index.
443 int FI = MO.getIndex();
444 if (!StoredFIs.count(FI) &&
445 MFI->isSpillSlotObjectIndex(FI) &&
446 InstructionStoresToFI(MI, FI))
447 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000448 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000449 continue;
450 }
451
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000452 // We can't hoist an instruction defining a physreg that is clobbered in
453 // the loop.
454 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000455 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000456 continue;
457 }
458
Evan Cheng058b9f02010-04-08 01:03:47 +0000459 if (!MO.isReg())
460 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000461 Register Reg = MO.getReg();
Evan Cheng058b9f02010-04-08 01:03:47 +0000462 if (!Reg)
463 continue;
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000464 assert(Register::isPhysicalRegister(Reg) &&
Evan Cheng058b9f02010-04-08 01:03:47 +0000465 "Not expecting virtual register!");
466
Evan Cheng0a2aff22010-04-13 18:16:00 +0000467 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000468 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000469 // If it's using a non-loop-invariant register, then it's obviously not
470 // safe to hoist.
471 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000472 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000473 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000474
475 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000476 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
477 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000478 if (!MO.isDead())
479 // Non-dead implicit def? This cannot be hoisted.
480 RuledOut = true;
481 // No need to check if a dead implicit def is also defined by
482 // another instruction.
483 continue;
484 }
485
486 // FIXME: For now, avoid instructions with multiple defs, unless
487 // it's a dead implicit def.
488 if (Def)
489 RuledOut = true;
490 else
491 Def = Reg;
492
493 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000494 // register, then this is not safe. Two defs is indicated by setting a
495 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000496 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000497 if (PhysRegDefs.test(*AS))
498 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000499 }
Craig Topper69342022018-12-05 03:41:26 +0000500 // Need a second loop because MCRegAliasIterator can visit the same
501 // register twice.
502 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
503 PhysRegDefs.set(*AS);
504
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000505 if (PhysRegClobbers.test(Reg))
506 // MI defined register is seen defined by another instruction in
507 // the loop, it cannot be a LICM candidate.
508 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000509 }
510
Evan Cheng0a2aff22010-04-13 18:16:00 +0000511 // Only consider reloads for now and remats which do not have register
512 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000513 if (Def && !RuledOut) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000514 int FI = std::numeric_limits<int>::min();
Evan Cheng89e74792010-04-13 20:21:05 +0000515 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000516 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000517 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000518 }
519}
520
Sanjay Patel87c6c072015-12-10 16:34:21 +0000521/// Walk the specified region of the CFG and hoist loop invariants out to the
522/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000523void MachineLICMBase::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000524 MachineBasicBlock *Preheader = getCurPreheader();
525 if (!Preheader)
526 return;
527
Evan Cheng6ea59492010-04-07 00:41:17 +0000528 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000529 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
530 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000531
Evan Cheng058b9f02010-04-08 01:03:47 +0000532 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000533 SmallSet<int, 32> StoredFIs;
534
535 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000536 // collect potential LICM candidates.
Benjamin Kramer28559a22018-09-10 12:32:06 +0000537 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Bill Wendling918cea22011-10-12 02:58:01 +0000538 // If the header of the loop containing this basic block is a landing pad,
539 // then don't try to hoist instructions out of this loop.
540 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000541 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000542
Evan Cheng6ea59492010-04-07 00:41:17 +0000543 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000544 // FIXME: That means a reload that're reused in successor block(s) will not
545 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000546 for (const auto &LI : BB->liveins()) {
547 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000548 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000549 }
550
Evan Chengf192ca02011-10-11 23:48:44 +0000551 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000552 for (MachineInstr &MI : *BB)
553 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000554 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000555
Evan Cheng7fede872012-03-27 01:50:58 +0000556 // Gather the registers read / clobbered by the terminator.
557 BitVector TermRegs(NumRegs);
558 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
559 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000560 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000561 if (!MO.isReg())
562 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000563 Register Reg = MO.getReg();
Evan Cheng7fede872012-03-27 01:50:58 +0000564 if (!Reg)
565 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000566 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
567 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000568 }
569 }
570
Evan Cheng6ea59492010-04-07 00:41:17 +0000571 // Now evaluate whether the potential candidates qualify.
572 // 1. Check if the candidate defined register is defined by another
573 // instruction in the loop.
574 // 2. If the candidate is a load from stack slot (always true for now),
575 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000576 // 3. Make sure candidate def should not clobber
577 // registers read by the terminator. Similarly its def should not be
578 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000579 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000580 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000581 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000582 continue;
583
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000584 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000585 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000586 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000587 MachineInstr *MI = Candidate.MI;
588 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000589 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000590 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000591 Register Reg = MO.getReg();
Evan Cheng7fede872012-03-27 01:50:58 +0000592 if (PhysRegDefs.test(Reg) ||
593 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000594 // If it's using a non-loop-invariant register, then it's obviously
595 // not safe to hoist.
596 Safe = false;
597 break;
598 }
599 }
600 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000601 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000602 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000603 }
604}
605
Sanjay Patel87c6c072015-12-10 16:34:21 +0000606/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
607/// sure it is not killed by any instructions in the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000608void MachineLICMBase::AddToLiveIns(unsigned Reg) {
Benjamin Kramer28559a22018-09-10 12:32:06 +0000609 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000610 if (!BB->isLiveIn(Reg))
611 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000612 for (MachineInstr &MI : *BB) {
613 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000614 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
615 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
616 MO.setIsKill(false);
617 }
618 }
619 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000620}
621
Sanjay Patel87c6c072015-12-10 16:34:21 +0000622/// When an instruction is found to only use loop invariant operands that is
623/// safe to hoist, this instruction is called to do the dirty work.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000624void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000625 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000626
Evan Cheng6ea59492010-04-07 00:41:17 +0000627 // Now move the instructions to the predecessor, inserting it before any
628 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000629 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
630 << " from " << printMBBReference(*MI->getParent()) << ": "
631 << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000632
633 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000634 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000635 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000636
Andrew Trick5209c732012-02-08 21:23:00 +0000637 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000638 // loop invariant must be kept live throughout the whole loop. This is
639 // important to ensure later passes do not scavenge the def register.
640 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000641
642 ++NumPostRAHoisted;
643 Changed = true;
644}
645
Sanjay Patel87c6c072015-12-10 16:34:21 +0000646/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
647/// may not be safe to hoist.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000648bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000649 if (SpeculationState != SpeculateUnknown)
650 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000651
Devang Patel453d4012011-10-11 18:09:58 +0000652 if (BB != CurLoop->getHeader()) {
653 // Check loop exiting blocks.
654 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
655 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000656 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
657 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000658 SpeculationState = SpeculateTrue;
659 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000660 }
661 }
662
Evan Chengf192ca02011-10-11 23:48:44 +0000663 SpeculationState = SpeculateFalse;
664 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000665}
666
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000667void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000668 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000669
Pete Cooper1eed5b52011-12-22 02:05:40 +0000670 // Remember livein register pressure.
671 BackTrace.push_back(RegPressure);
672}
Bill Wendling918cea22011-10-12 02:58:01 +0000673
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000674void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000675 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000676 BackTrace.pop_back();
677}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000678
Sanjay Patel87c6c072015-12-10 16:34:21 +0000679/// Destroy scope for the MBB that corresponds to the given dominator tree node
680/// if its a leaf or all of its children are done. Walk up the dominator tree to
681/// destroy ancestors which are now done.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000682void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
683 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
684 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000685 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000686 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000687
Pete Cooper1eed5b52011-12-22 02:05:40 +0000688 // Pop scope.
689 ExitScope(Node->getBlock());
690
691 // Now traverse upwards to pop ancestors whose offsprings are all done.
692 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
693 unsigned Left = --OpenChildren[Parent];
694 if (Left != 0)
695 break;
696 ExitScope(Parent->getBlock());
697 Node = Parent;
698 }
699}
700
Sanjay Patel87c6c072015-12-10 16:34:21 +0000701/// Walk the specified loop in the CFG (defined by all blocks dominated by the
702/// specified header block, and that are in the current loop) in depth first
703/// order w.r.t the DominatorTree. This allows us to visit definitions before
704/// uses, allowing us to hoist a loop body in one pass without iteration.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000705void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000706 MachineBasicBlock *Preheader = getCurPreheader();
707 if (!Preheader)
708 return;
709
Pete Cooper1eed5b52011-12-22 02:05:40 +0000710 SmallVector<MachineDomTreeNode*, 32> Scopes;
711 SmallVector<MachineDomTreeNode*, 8> WorkList;
712 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
713 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
714
715 // Perform a DFS walk to determine the order of visit.
716 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000717 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000718 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000719 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000720 MachineBasicBlock *BB = Node->getBlock();
721
722 // If the header of the loop containing this basic block is a landing pad,
723 // then don't try to hoist instructions out of this loop.
724 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000725 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000726 continue;
727
728 // If this subregion is not in the top level loop at all, exit.
729 if (!CurLoop->contains(BB))
730 continue;
731
732 Scopes.push_back(Node);
733 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
734 unsigned NumChildren = Children.size();
735
736 // Don't hoist things out of a large switch statement. This often causes
737 // code to be hoisted that wasn't going to be executed, and increases
738 // register pressure in a situation where it's likely to matter.
739 if (BB->succ_size() >= 25)
740 NumChildren = 0;
741
742 OpenChildren[Node] = NumChildren;
743 // Add children in reverse order as then the next popped worklist node is
744 // the first child of this node. This means we ultimately traverse the
745 // DOM tree in exactly the same order as if we'd recursed.
746 for (int i = (int)NumChildren-1; i >= 0; --i) {
747 MachineDomTreeNode *Child = Children[i];
748 ParentMap[Child] = Node;
749 WorkList.push_back(Child);
750 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000751 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000752
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000753 if (Scopes.size() == 0)
754 return;
755
756 // Compute registers which are livein into the loop headers.
757 RegSeen.clear();
758 BackTrace.clear();
759 InitRegPressure(Preheader);
760
Pete Cooper1eed5b52011-12-22 02:05:40 +0000761 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000762 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000763 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000764
Pete Cooper1eed5b52011-12-22 02:05:40 +0000765 EnterScope(MBB);
766
767 // Process the block
768 SpeculationState = SpeculateUnknown;
769 for (MachineBasicBlock::iterator
770 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
771 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
772 MachineInstr *MI = &*MII;
773 if (!Hoist(MI, Preheader))
774 UpdateRegPressure(MI);
Zaara Syeda65359932018-03-23 15:28:15 +0000775 // If we have hoisted an instruction that may store, it can only be a
776 // constant store.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000777 MII = NextMII;
778 }
779
780 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
781 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000782 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000783}
784
Sanjay Patel87c6c072015-12-10 16:34:21 +0000785/// Sink instructions into loops if profitable. This especially tries to prevent
786/// register spills caused by register pressure if there is little to no
787/// overhead moving instructions into loops.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000788void MachineLICMBase::SinkIntoLoop() {
Daniel Jasper15e69542015-03-14 10:58:38 +0000789 MachineBasicBlock *Preheader = getCurPreheader();
790 if (!Preheader)
791 return;
792
793 SmallVector<MachineInstr *, 8> Candidates;
794 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
795 I != Preheader->instr_end(); ++I) {
796 // We need to ensure that we can safely move this instruction into the loop.
Michael Liaoa5d45372017-04-26 05:27:20 +0000797 // 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 +0000798 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
799 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000800 }
801
802 for (MachineInstr *I : Candidates) {
803 const MachineOperand &MO = I->getOperand(0);
804 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
805 continue;
806 if (!MRI->hasOneDef(MO.getReg()))
807 continue;
808 bool CanSink = true;
809 MachineBasicBlock *B = nullptr;
810 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
811 // FIXME: Come up with a proper cost model that estimates whether sinking
812 // the instruction (and thus possibly executing it on every loop
813 // iteration) is more expensive than a register.
814 // For now assumes that copies are cheap and thus almost always worth it.
815 if (!MI.isCopy()) {
816 CanSink = false;
817 break;
818 }
819 if (!B) {
820 B = MI.getParent();
821 continue;
822 }
823 B = DT->findNearestCommonDominator(B, MI.getParent());
824 if (!B) {
825 CanSink = false;
826 break;
827 }
828 }
829 if (!CanSink || !B || B == Preheader)
830 continue;
831 B->splice(B->getFirstNonPHI(), Preheader, I);
832 }
833}
834
Evan Cheng87066f02010-10-20 22:03:58 +0000835static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
836 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
837}
838
Sanjay Patel87c6c072015-12-10 16:34:21 +0000839/// Find all virtual register references that are liveout of the preheader to
840/// initialize the starting "register pressure". Note this does not count live
841/// through (livein but not used) registers.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000842void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000843 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000844
Evan Cheng87066f02010-10-20 22:03:58 +0000845 // If the preheader has only a single predecessor and it ends with a
846 // fallthrough or an unconditional branch, then scan its predecessor for live
847 // defs as well. This happens whenever the preheader is created by splitting
848 // the critical edge from the loop predecessor to the loop header.
849 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000850 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000851 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000852 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000853 InitRegPressure(*BB->pred_begin());
854 }
855
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000856 for (const MachineInstr &MI : *BB)
857 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000858}
859
Sanjay Patel87c6c072015-12-10 16:34:21 +0000860/// Update estimate of register pressure after the specified instruction.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000861void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
862 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000863 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000864 for (const auto &RPIdAndCost : Cost) {
865 unsigned Class = RPIdAndCost.first;
866 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000867 RegPressure[Class] = 0;
868 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000869 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000870 }
871}
Evan Chengd62719c2010-10-14 01:16:09 +0000872
Sanjay Patel87c6c072015-12-10 16:34:21 +0000873/// Calculate the additional register pressure that the registers used in MI
874/// cause.
875///
876/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
877/// figure out which usages are live-ins.
878/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000879DenseMap<unsigned, int>
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000880MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
881 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000882 DenseMap<unsigned, int> Cost;
883 if (MI->isImplicitDef())
884 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000885 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
886 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000887 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000888 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000889 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000890 if (!Register::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000891 continue;
892
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000893 // FIXME: It seems bad to use RegSeen only for some of these calculations.
894 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000895 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
896
897 RegClassWeight W = TRI->getRegClassWeight(RC);
898 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000899 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000900 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000901 else {
902 bool isKill = isOperandKill(MO, MRI);
903 if (isNew && !isKill && ConsiderUnseenAsDef)
904 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000905 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000906 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000907 RCCost = -W.RegWeight;
908 }
909 if (RCCost == 0)
910 continue;
911 const int *PS = TRI->getRegClassPressureSets(RC);
912 for (; *PS != -1; ++PS) {
913 if (Cost.find(*PS) == Cost.end())
914 Cost[*PS] = RCCost;
915 else
916 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000917 }
Evan Chengd62719c2010-10-14 01:16:09 +0000918 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000919 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000920}
921
Sanjay Patel87c6c072015-12-10 16:34:21 +0000922/// Return true if this machine instruction loads from global offset table or
923/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000924static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000925 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liaoa5d45372017-04-26 05:27:20 +0000926
Philip Reames42bd26f2015-12-23 17:05:57 +0000927 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000928 // reads from everything..
Philip Reames42bd26f2015-12-23 17:05:57 +0000929 if (MI.memoperands_empty())
930 return true;
931
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000932 for (MachineMemOperand *MemOp : MI.memoperands())
933 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000934 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000935 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000936
Devang Patel69a45652011-10-17 17:35:01 +0000937 return false;
938}
939
Zaara Syeda65359932018-03-23 15:28:15 +0000940// This function iterates through all the operands of the input store MI and
941// checks that each register operand statisfies isCallerPreservedPhysReg.
942// This means, the value being stored and the address where it is being stored
943// is constant throughout the body of the function (not including prologue and
944// epilogue). When called with an MI that isn't a store, it returns false.
Zaara Syeda935474fe2018-04-09 14:50:02 +0000945// A future improvement can be to check if the store registers are constant
946// throughout the loop rather than throughout the funtion.
Zaara Syeda65359932018-03-23 15:28:15 +0000947static bool isInvariantStore(const MachineInstr &MI,
948 const TargetRegisterInfo *TRI,
949 const MachineRegisterInfo *MRI) {
950
Zaara Syeda935474fe2018-04-09 14:50:02 +0000951 bool FoundCallerPresReg = false;
Zaara Syeda65359932018-03-23 15:28:15 +0000952 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
953 (MI.getNumOperands() == 0))
954 return false;
955
956 // Check that all register operands are caller-preserved physical registers.
957 for (const MachineOperand &MO : MI.operands()) {
958 if (MO.isReg()) {
Daniel Sanders0c476112019-08-15 19:22:08 +0000959 Register Reg = MO.getReg();
Zaara Syeda65359932018-03-23 15:28:15 +0000960 // If operand is a virtual register, check if it comes from a copy of a
961 // physical register.
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000962 if (Register::isVirtualRegister(Reg))
Zaara Syeda65359932018-03-23 15:28:15 +0000963 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000964 if (Register::isVirtualRegister(Reg))
Zaara Syeda65359932018-03-23 15:28:15 +0000965 return false;
966 if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
967 return false;
Zaara Syeda935474fe2018-04-09 14:50:02 +0000968 else
969 FoundCallerPresReg = true;
970 } else if (!MO.isImm()) {
971 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000972 }
973 }
Zaara Syeda935474fe2018-04-09 14:50:02 +0000974 return FoundCallerPresReg;
Zaara Syeda65359932018-03-23 15:28:15 +0000975}
976
977// Return true if the input MI is a copy instruction that feeds an invariant
978// store instruction. This means that the src of the copy has to satisfy
979// isCallerPreservedPhysReg and atleast one of it's users should satisfy
980// isInvariantStore.
981static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
982 const MachineRegisterInfo *MRI,
983 const TargetRegisterInfo *TRI) {
984
985 // FIXME: If targets would like to look through instructions that aren't
986 // pure copies, this can be updated to a query.
987 if (!MI.isCopy())
988 return false;
989
990 const MachineFunction *MF = MI.getMF();
991 // Check that we are copying a constant physical register.
Daniel Sanders0c476112019-08-15 19:22:08 +0000992 Register CopySrcReg = MI.getOperand(1).getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000993 if (Register::isVirtualRegister(CopySrcReg))
Zaara Syeda65359932018-03-23 15:28:15 +0000994 return false;
995
996 if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
997 return false;
998
Daniel Sanders0c476112019-08-15 19:22:08 +0000999 Register CopyDstReg = MI.getOperand(0).getReg();
Zaara Syeda65359932018-03-23 15:28:15 +00001000 // Check if any of the uses of the copy are invariant stores.
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001001 assert(Register::isVirtualRegister(CopyDstReg) &&
1002 "copy dst is not a virtual reg");
Zaara Syeda65359932018-03-23 15:28:15 +00001003
1004 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
1005 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
1006 return true;
1007 }
1008 return false;
1009}
1010
Sanjay Patel87c6c072015-12-10 16:34:21 +00001011/// Returns true if the instruction may be a suitable candidate for LICM.
1012/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001013bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +00001014 // Check if it's safe to move the instruction.
1015 bool DontMoveAcrossStore = true;
Zaara Syeda65359932018-03-23 15:28:15 +00001016 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
1017 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
Chris Lattnerc8226f32008-01-10 23:08:24 +00001018 return false;
Zaara Syeda65359932018-03-23 15:28:15 +00001019 }
Devang Patel453d4012011-10-11 18:09:58 +00001020
1021 // If it is load then check if it is guaranteed to execute by making sure that
1022 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +00001023 // the loop which does not execute this load, so we can't hoist it. Loads
1024 // from constant memory are not safe to speculate all the time, for example
1025 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +00001026 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +00001027 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +00001028 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +00001029 return false;
1030
Evan Cheng0a2aff22010-04-13 18:16:00 +00001031 return true;
1032}
1033
Sanjay Patel87c6c072015-12-10 16:34:21 +00001034/// Returns true if the instruction is loop invariant.
1035/// I.e., all virtual register operands are defined outside of the loop,
1036/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +00001037/// effects that aren't captured by the operands or other flags.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001038bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
Evan Cheng0a2aff22010-04-13 18:16:00 +00001039 if (!IsLICMCandidate(I))
1040 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +00001041
Bill Wendling70613b82008-05-12 19:38:32 +00001042 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001043 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001044 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +00001045 continue;
1046
Daniel Sanders0c476112019-08-15 19:22:08 +00001047 Register Reg = MO.getReg();
Dan Gohman79618d12009-01-15 22:01:38 +00001048 if (Reg == 0) continue;
1049
1050 // Don't hoist an instruction that uses or defines a physical register.
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001051 if (Register::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +00001052 if (MO.isUse()) {
1053 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +00001054 // and we can freely move its uses. Alternatively, if it's allocatable,
1055 // it could get allocated to something with a def during allocation.
Lei Huangb4733ca2017-06-15 18:29:59 +00001056 // However, if the physreg is known to always be caller saved/restored
1057 // then this use is safe to hoist.
1058 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001059 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1060 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001061 // Otherwise it's safe to move.
1062 continue;
1063 } else if (!MO.isDead()) {
1064 // A def that isn't dead. We can't move it.
1065 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +00001066 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1067 // If the reg is live into the loop, we can't hoist an instruction
1068 // which would clobber it.
1069 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001070 }
1071 }
Bill Wendlingcd01e892008-08-20 20:32:05 +00001072
1073 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001074 continue;
1075
Evan Chengd62719c2010-10-14 01:16:09 +00001076 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +00001077 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001078
1079 // If the loop contains the definition of an operand, then the instruction
1080 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001081 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001082 return false;
1083 }
1084
1085 // If we got this far, the instruction is loop invariant!
1086 return true;
1087}
1088
Sanjay Patel87c6c072015-12-10 16:34:21 +00001089/// Return true if the specified instruction is used by a phi node and hoisting
1090/// it could cause a copy to be inserted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001091bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001092 SmallVector<const MachineInstr*, 8> Work(1, MI);
1093 do {
1094 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +00001095 for (const MachineOperand &MO : MI->operands()) {
1096 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001097 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +00001098 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001099 if (!Register::isVirtualRegister(Reg))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001100 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001101 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001102 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001103 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001104 // A PHI inside the loop causes a copy because the live range of Reg is
1105 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001106 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001107 return true;
1108 // A PHI in an exit block can cause a copy to be inserted if the PHI
1109 // has multiple predecessors in the loop with different values.
1110 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001111 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001112 return true;
1113 continue;
1114 }
1115 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001116 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1117 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001118 }
Evan Chengef42bea2011-04-11 21:09:18 +00001119 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001120 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001121 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001122}
1123
Sanjay Patel87c6c072015-12-10 16:34:21 +00001124/// Compute operand latency between a def of 'Reg' and an use in the current
1125/// loop, return true if the target considered it high.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001126bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1127 unsigned DefIdx,
1128 unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +00001129 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001130 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001131
Owen Andersonb36376e2014-03-17 19:36:09 +00001132 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1133 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001134 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001135 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001136 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001137 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1138 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001139 if (!MO.isReg() || !MO.isUse())
1140 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +00001141 Register MOReg = MO.getReg();
Evan Chengd62719c2010-10-14 01:16:09 +00001142 if (MOReg != Reg)
1143 continue;
1144
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001145 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001146 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001147 }
1148
Evan Cheng63c76082010-10-19 18:58:51 +00001149 // Only look at the first in loop use.
1150 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001151 }
1152
Evan Cheng63c76082010-10-19 18:58:51 +00001153 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001154}
1155
Sanjay Patel87c6c072015-12-10 16:34:21 +00001156/// Return true if the instruction is marked "cheap" or the operand latency
1157/// between its def and a use is one or less.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001158bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001159 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001160 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001161
1162 bool isCheap = false;
1163 unsigned NumDefs = MI.getDesc().getNumDefs();
1164 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1165 MachineOperand &DefMO = MI.getOperand(i);
1166 if (!DefMO.isReg() || !DefMO.isDef())
1167 continue;
1168 --NumDefs;
Daniel Sanders0c476112019-08-15 19:22:08 +00001169 Register Reg = DefMO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001170 if (Register::isPhysicalRegister(Reg))
Evan Chenge96b8d72010-10-26 02:08:50 +00001171 continue;
1172
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001173 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001174 return false;
1175 isCheap = true;
1176 }
1177
1178 return isCheap;
1179}
1180
Sanjay Patel87c6c072015-12-10 16:34:21 +00001181/// Visit BBs from header to current BB, check if hoisting an instruction of the
1182/// given cost matrix can cause high register pressure.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001183bool
1184MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1185 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001186 for (const auto &RPIdAndCost : Cost) {
1187 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001188 continue;
1189
Daniel Jasper274928f2015-04-14 11:56:25 +00001190 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001191 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001192
1193 // Don't hoist cheap instructions if they would increase register pressure,
1194 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001195 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001196 return true;
1197
Daniel Jasperefece522015-04-03 16:19:48 +00001198 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001199 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001200 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001201 }
1202
1203 return false;
1204}
1205
Sanjay Patel87c6c072015-12-10 16:34:21 +00001206/// Traverse the back trace from header to the current block and update their
1207/// register pressures to reflect the effect of hoisting MI from the current
1208/// block to the preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001209void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001210 // First compute the 'cost' of the instruction, i.e. its contribution
1211 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001212 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1213 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001214
1215 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001216 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001217 for (const auto &RPIdAndCost : Cost)
1218 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001219}
1220
Sanjay Patel87c6c072015-12-10 16:34:21 +00001221/// Return true if it is potentially profitable to hoist the given loop
1222/// invariant.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001223bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001224 if (MI.isImplicitDef())
1225 return true;
1226
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001227 // Besides removing computation from the loop, hoisting an instruction has
1228 // these effects:
1229 //
1230 // - The value defined by the instruction becomes live across the entire
1231 // loop. This increases register pressure in the loop.
1232 //
1233 // - If the value is used by a PHI in the loop, a copy will be required for
1234 // lowering the PHI after extending the live range.
1235 //
1236 // - When hoisting the last use of a value in the loop, that value no longer
1237 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001238
Zaara Syeda65359932018-03-23 15:28:15 +00001239 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1240 return true;
1241
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001242 bool CheapInstr = IsCheapInstruction(MI);
1243 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001244
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001245 // Don't hoist a cheap instruction if it would create a copy in the loop.
1246 if (CheapInstr && CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001247 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001248 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001249 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001250
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001251 // Rematerializable instructions should always be hoisted since the register
1252 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001253 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001254 return true;
1255
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001256 // FIXME: If there are long latency loop-invariant instructions inside the
1257 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001258 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1259 const MachineOperand &MO = MI.getOperand(i);
1260 if (!MO.isReg() || MO.isImplicit())
1261 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +00001262 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001263 if (!Register::isVirtualRegister(Reg))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001264 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001265 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001266 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001267 ++NumHighLatency;
1268 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001269 }
1270 }
1271
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001272 // Estimate register pressure to determine whether to LICM the instruction.
1273 // In low register pressure situation, we can be more aggressive about
1274 // hoisting. Also, favors hoisting long latency instructions even in
1275 // moderately high pressure situation.
1276 // Cheap instructions will only be hoisted if they don't increase register
1277 // pressure at all.
1278 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1279 /*ConsiderUnseenAsDef=*/false);
1280
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001281 // Visit BBs from header to current BB, if hoisting this doesn't cause
1282 // high register pressure, then it's safe to proceed.
1283 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001284 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001285 ++NumLowRP;
1286 return true;
1287 }
1288
1289 // Don't risk increasing register pressure if it would create copies.
1290 if (CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001291 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001292 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001293 }
1294
1295 // Do not "speculate" in high register pressure situation. If an
1296 // instruction is not guaranteed to be executed in the loop, it's best to be
1297 // conservative.
1298 if (AvoidSpeculation &&
1299 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001300 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001301 return false;
1302 }
1303
1304 // High register pressure situation, only hoist if the instruction is going
1305 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001306 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1307 !MI.isDereferenceableInvariantLoad(AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001308 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001309 return false;
1310 }
Evan Cheng399660c2009-02-05 08:45:46 +00001311
1312 return true;
1313}
1314
Sanjay Patel87c6c072015-12-10 16:34:21 +00001315/// Unfold a load from the given machineinstr if the load itself could be
1316/// hoisted. Return the unfolded and hoistable load, or null if the load
1317/// couldn't be unfolded or if it wouldn't be hoistable.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001318MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001319 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001320 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001321 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001322
Dan Gohman104f57c2009-10-29 17:47:20 +00001323 // If not, we may be able to unfold a load and hoist that.
1324 // First test whether the instruction is loading from an amenable
1325 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001326 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001327 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001328
Dan Gohman104f57c2009-10-29 17:47:20 +00001329 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001330 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001331 unsigned NewOpc =
1332 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1333 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001334 /*UnfoldStore=*/false,
1335 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001336 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001337 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001338 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001339 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001340 // Ok, we're unfolding. Create a temporary register and do the unfold.
Daniel Sanders0c476112019-08-15 19:22:08 +00001341 Register Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001342
Dan Gohman104f57c2009-10-29 17:47:20 +00001343 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001344 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1345 /*UnfoldLoad=*/true,
1346 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001347 (void)Success;
1348 assert(Success &&
1349 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1350 "succeeded!");
1351 assert(NewMIs.size() == 2 &&
1352 "Unfolded a load into multiple instructions!");
1353 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001354 MachineBasicBlock::iterator Pos = MI;
1355 MBB->insert(Pos, NewMIs[0]);
1356 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001357 // If unfolding produced a load that wasn't loop-invariant or profitable to
1358 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001359 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001360 NewMIs[0]->eraseFromParent();
1361 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001362 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001363 }
Evan Cheng87066f02010-10-20 22:03:58 +00001364
1365 // Update register pressure for the unfolded instruction.
1366 UpdateRegPressure(NewMIs[1]);
1367
Dan Gohman104f57c2009-10-29 17:47:20 +00001368 // Otherwise we successfully unfolded a load that we can hoist.
1369 MI->eraseFromParent();
1370 return NewMIs[0];
1371}
1372
Sanjay Patel87c6c072015-12-10 16:34:21 +00001373/// Initialize the CSE map with instructions that are in the current loop
1374/// preheader that may become duplicates of instructions that are hoisted
1375/// out of the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001376void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001377 for (MachineInstr &MI : *BB)
1378 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001379}
1380
Sanjay Patel87c6c072015-12-10 16:34:21 +00001381/// Find an instruction amount PrevMIs that is a duplicate of MI.
1382/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001383const MachineInstr*
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001384MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1385 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001386 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001387 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001388 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001389
Craig Topperc0196b12014-04-14 00:51:57 +00001390 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001391}
1392
Sanjay Patel87c6c072015-12-10 16:34:21 +00001393/// Given a LICM'ed instruction, look for an instruction on the preheader that
1394/// computes the same value. If it's found, do a RAU on with the definition of
1395/// the existing instruction rather than hoisting the instruction to the
1396/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001397bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1398 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001399 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1400 // the undef property onto uses.
1401 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001402 return false;
1403
1404 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001405 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001406
1407 // Replace virtual registers defined by MI by their counterparts defined
1408 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001409 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001410 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1411 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001412
1413 // Physical registers may not differ here.
1414 assert((!MO.isReg() || MO.getReg() == 0 ||
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001415 !Register::isPhysicalRegister(MO.getReg()) ||
Dan Gohman34021b72010-02-28 01:33:43 +00001416 MO.getReg() == Dup->getOperand(i).getReg()) &&
1417 "Instructions with different phys regs are not identical!");
1418
1419 if (MO.isReg() && MO.isDef() &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +00001420 !Register::isPhysicalRegister(MO.getReg()))
Evan Chengaa563df2011-10-17 19:50:12 +00001421 Defs.push_back(i);
1422 }
1423
1424 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1425 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1426 unsigned Idx = Defs[i];
Daniel Sanders0c476112019-08-15 19:22:08 +00001427 Register Reg = MI->getOperand(Idx).getReg();
1428 Register DupReg = Dup->getOperand(Idx).getReg();
Evan Chengaa563df2011-10-17 19:50:12 +00001429 OrigRCs.push_back(MRI->getRegClass(DupReg));
1430
1431 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1432 // Restore old RCs if more than one defs.
1433 for (unsigned j = 0; j != i; ++j)
1434 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1435 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001436 }
Evan Cheng921152f2009-11-05 00:51:13 +00001437 }
Evan Chengaa563df2011-10-17 19:50:12 +00001438
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001439 for (unsigned Idx : Defs) {
Daniel Sanders0c476112019-08-15 19:22:08 +00001440 Register Reg = MI->getOperand(Idx).getReg();
1441 Register DupReg = Dup->getOperand(Idx).getReg();
Evan Chengaa563df2011-10-17 19:50:12 +00001442 MRI->replaceRegWith(Reg, DupReg);
1443 MRI->clearKillFlags(DupReg);
1444 }
1445
Evan Cheng7ff83192009-11-07 03:52:02 +00001446 MI->eraseFromParent();
1447 ++NumCSEed;
1448 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001449 }
1450 return false;
1451}
1452
Sanjay Patel87c6c072015-12-10 16:34:21 +00001453/// Return true if the given instruction will be CSE'd if it's hoisted out of
1454/// the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001455bool MachineLICMBase::MayCSE(MachineInstr *MI) {
Evan Chengaf138952011-10-12 00:09:14 +00001456 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001457 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengaf138952011-10-12 00:09:14 +00001458 CI = CSEMap.find(Opcode);
1459 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1460 // the undef property onto uses.
1461 if (CI == CSEMap.end() || MI->isImplicitDef())
1462 return false;
1463
Craig Topperc0196b12014-04-14 00:51:57 +00001464 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001465}
1466
Sanjay Patel87c6c072015-12-10 16:34:21 +00001467/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001468/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001469/// It returns true if the instruction is hoisted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001470bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Victor Huangedab7dd2019-11-11 21:32:56 +00001471 MachineBasicBlock *SrcBlock = MI->getParent();
1472
1473 // Disable the instruction hoisting due to block hotness
1474 if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1475 (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1476 isTgtHotterThanSrc(SrcBlock, Preheader)) {
1477 ++NumNotHoistedDueToHotness;
1478 return false;
1479 }
Dan Gohman1b44f102009-10-28 03:21:57 +00001480 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001481 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001482 // If not, try unfolding a hoistable load.
1483 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001484 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001485 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001486
Zaara Syeda65359932018-03-23 15:28:15 +00001487 // If we have hoisted an instruction that may store, it can only be a constant
1488 // store.
1489 if (MI->mayStore())
1490 NumStoreConst++;
1491
Dan Gohman79618d12009-01-15 22:01:38 +00001492 // Now move the instructions to the predecessor, inserting it before any
1493 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001494 LLVM_DEBUG({
1495 dbgs() << "Hoisting " << *MI;
1496 if (MI->getParent()->getBasicBlock())
1497 dbgs() << " from " << printMBBReference(*MI->getParent());
1498 if (Preheader->getBasicBlock())
1499 dbgs() << " to " << printMBBReference(*Preheader);
1500 dbgs() << "\n";
1501 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001502
Evan Chengf42b5af2009-11-03 21:40:02 +00001503 // If this is the first instruction being hoisted to the preheader,
1504 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001505 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001506 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001507 FirstInLoop = false;
1508 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001509
Evan Cheng399660c2009-02-05 08:45:46 +00001510 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001511 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001512 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengf42b5af2009-11-03 21:40:02 +00001513 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001514 if (!EliminateCSE(MI, CI)) {
1515 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001516 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001517
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001518 // Since we are moving the instruction out of its basic block, we do not
Michael Liaoa5d45372017-04-26 05:27:20 +00001519 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001520 // experience and adversely affect the accuracy of profiling information.
1521 MI->setDebugLoc(DebugLoc());
1522
Evan Cheng87066f02010-10-20 22:03:58 +00001523 // Update register pressure for BBs from header to this block.
1524 UpdateBackTraceRegPressure(MI);
1525
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001526 // Clear the kill flags of any register this instruction defines,
1527 // since they may need to be live throughout the entire loop
1528 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001529 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001530 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001531 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001532
Evan Cheng399660c2009-02-05 08:45:46 +00001533 // Add to the CSE map.
1534 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001535 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001536 else
1537 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001538 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001539
Dan Gohman79618d12009-01-15 22:01:38 +00001540 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001541 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001542
1543 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001544}
Dan Gohman3570f812010-06-22 17:25:57 +00001545
Sanjay Patel87c6c072015-12-10 16:34:21 +00001546/// Get the preheader for the current loop, splitting a critical edge if needed.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001547MachineBasicBlock *MachineLICMBase::getCurPreheader() {
Dan Gohman3570f812010-06-22 17:25:57 +00001548 // Determine the block to which to hoist instructions. If we can't find a
1549 // suitable loop predecessor, we can't do any hoisting.
1550
1551 // If we've tried to get a preheader and failed, don't try again.
1552 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001553 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001554
1555 if (!CurPreheader) {
1556 CurPreheader = CurLoop->getLoopPreheader();
1557 if (!CurPreheader) {
1558 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1559 if (!Pred) {
1560 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001561 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001562 }
1563
Quentin Colombet23341a82016-04-21 21:01:13 +00001564 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001565 if (!CurPreheader) {
1566 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001567 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001568 }
1569 }
1570 }
1571 return CurPreheader;
1572}
Victor Huangedab7dd2019-11-11 21:32:56 +00001573
1574/// Is the target basic block at least "BlockFrequencyRatioThreshold"
1575/// times hotter than the source basic block.
1576bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1577 MachineBasicBlock *TgtBlock) {
1578 // Parse source and target basic block frequency from MBFI
1579 uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1580 uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1581
1582 // Disable the hoisting if source block frequency is zero
1583 if (!SrcBF)
1584 return true;
1585
1586 double Ratio = (double)DstBF / SrcBF;
1587
1588 // Compare the block frequency ratio with the threshold
1589 return Ratio > BlockFrequencyRatioThreshold;
1590}