blob: 519cb4703ca9b727c514c268105d7133cf941dc5 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===//
Evan Cheng036aa492010-03-02 02:38:24 +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
Evan Cheng036aa492010-03-02 02:38:24 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs global common subexpression elimination on machine
Evan Cheng10194a42010-03-02 19:02:27 +000010// instructions using a scoped hash table based value numbering scheme. It
Evan Cheng036aa492010-03-02 02:38:24 +000011// must be run while the machine function is still in SSA form.
12//
13//===----------------------------------------------------------------------===//
14
Evan Cheng4b2ef562010-04-21 00:21:07 +000015#include "llvm/ADT/DenseMap.h"
Evan Cheng036aa492010-03-02 02:38:24 +000016#include "llvm/ADT/ScopedHashTable.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000017#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng2b3f25e2010-10-29 23:36:03 +000018#include "llvm/ADT/SmallSet.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000019#include "llvm/ADT/SmallVector.h"
Evan Cheng036aa492010-03-02 02:38:24 +000020#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000022#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineInstr.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000027#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000029#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000030#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetOpcodes.h"
32#include "llvm/CodeGen/TargetRegisterInfo.h"
33#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000034#include "llvm/MC/MCInstrDesc.h"
35#include "llvm/MC/MCRegisterInfo.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/Allocator.h"
Evan Cheng036aa492010-03-02 02:38:24 +000038#include "llvm/Support/Debug.h"
Cameron Zwarich18f164f2011-01-03 04:07:46 +000039#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000040#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000041#include <cassert>
42#include <iterator>
43#include <utility>
44#include <vector>
45
Evan Cheng036aa492010-03-02 02:38:24 +000046using namespace llvm;
47
Chandler Carruth1b9dde02014-04-22 02:02:50 +000048#define DEBUG_TYPE "machine-cse"
49
Evan Chengb386cd32010-03-03 21:20:05 +000050STATISTIC(NumCoalesces, "Number of copies coalesced");
51STATISTIC(NumCSEs, "Number of common subexpression eliminated");
Evan Cheng2b3f25e2010-10-29 23:36:03 +000052STATISTIC(NumPhysCSEs,
53 "Number of physreg referencing common subexpr eliminated");
Evan Cheng0be41442012-01-10 02:02:58 +000054STATISTIC(NumCrossBBCSEs,
55 "Number of cross-MBB physreg referencing CS eliminated");
Evan Chengb7ff5a02010-12-15 22:16:21 +000056STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
Bob Wilson30093b52010-06-03 18:28:31 +000057
Evan Cheng036aa492010-03-02 02:38:24 +000058namespace {
Eugene Zelenko5df3d892017-08-24 21:21:39 +000059
Evan Cheng036aa492010-03-02 02:38:24 +000060 class MachineCSE : public MachineFunctionPass {
Evan Cheng4eab0082010-03-03 02:48:20 +000061 const TargetInstrInfo *TII;
Evan Cheng36f8aab2010-03-04 01:33:55 +000062 const TargetRegisterInfo *TRI;
Evan Cheng1abd1a92010-03-04 21:18:08 +000063 AliasAnalysis *AA;
Evan Cheng19e44b42010-03-09 03:21:12 +000064 MachineDominatorTree *DT;
65 MachineRegisterInfo *MRI;
Eugene Zelenko5df3d892017-08-24 21:21:39 +000066
Evan Cheng036aa492010-03-02 02:38:24 +000067 public:
68 static char ID; // Pass identification
Eugene Zelenko5df3d892017-08-24 21:21:39 +000069
70 MachineCSE() : MachineFunctionPass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000071 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
72 }
Evan Cheng036aa492010-03-02 02:38:24 +000073
Craig Topper4584cd52014-03-07 09:26:03 +000074 bool runOnMachineFunction(MachineFunction &MF) override;
Andrew Trick9e761992012-02-08 21:22:43 +000075
Craig Topper4584cd52014-03-07 09:26:03 +000076 void getAnalysisUsage(AnalysisUsage &AU) const override {
Evan Cheng036aa492010-03-02 02:38:24 +000077 AU.setPreservesCFG();
78 MachineFunctionPass::getAnalysisUsage(AU);
Chandler Carruth7b560d42015-09-09 17:55:00 +000079 AU.addRequired<AAResultsWrapperPass>();
Evan Chenge0db9d02010-08-17 20:57:42 +000080 AU.addPreservedID(MachineLoopInfoID);
Evan Cheng036aa492010-03-02 02:38:24 +000081 AU.addRequired<MachineDominatorTree>();
82 AU.addPreserved<MachineDominatorTree>();
83 }
84
Craig Topper4584cd52014-03-07 09:26:03 +000085 void releaseMemory() override {
Evan Chengb08377e2010-09-17 21:59:42 +000086 ScopeMap.clear();
87 Exps.clear();
88 }
89
Evan Cheng036aa492010-03-02 02:38:24 +000090 private:
Eugene Zelenko5df3d892017-08-24 21:21:39 +000091 using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
92 ScopedHashTableVal<MachineInstr *, unsigned>>;
93 using ScopedHTType =
94 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
95 AllocatorTy>;
96 using ScopeType = ScopedHTType::ScopeTy;
David Greencb5a48b2019-02-20 10:22:18 +000097 using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
Eugene Zelenko5df3d892017-08-24 21:21:39 +000098
99 unsigned LookAheadLimit = 0;
100 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
Cameron Zwarich18f164f2011-01-03 04:07:46 +0000101 ScopedHTType VNT;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000102 SmallVector<MachineInstr *, 64> Exps;
103 unsigned CurrVN = 0;
Evan Chengb386cd32010-03-03 21:20:05 +0000104
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000105 bool PerformTrivialCopyPropagation(MachineInstr *MI,
106 MachineBasicBlock *MBB);
Evan Cheng36f8aab2010-03-04 01:33:55 +0000107 bool isPhysDefTriviallyDead(unsigned Reg,
108 MachineBasicBlock::const_iterator I,
Nick Lewycky765c6992012-07-05 06:19:21 +0000109 MachineBasicBlock::const_iterator E) const;
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000110 bool hasLivePhysRegDefUses(const MachineInstr *MI,
111 const MachineBasicBlock *MBB,
David Greencb5a48b2019-02-20 10:22:18 +0000112 SmallSet<unsigned, 8> &PhysRefs,
113 PhysDefVector &PhysDefs, bool &PhysUseDef) const;
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000114 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
David Greencb5a48b2019-02-20 10:22:18 +0000115 SmallSet<unsigned, 8> &PhysRefs,
116 PhysDefVector &PhysDefs, bool &NonLocal) const;
Evan Cheng1abd1a92010-03-04 21:18:08 +0000117 bool isCSECandidate(MachineInstr *MI);
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000118 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
David L. Jones0ff41b82019-05-27 06:00:00 +0000119 MachineInstr *CSMI, MachineInstr *MI);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000120 void EnterScope(MachineBasicBlock *MBB);
121 void ExitScope(MachineBasicBlock *MBB);
David L. Jones0ff41b82019-05-27 06:00:00 +0000122 bool ProcessBlock(MachineBasicBlock *MBB);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000123 void ExitScopeIfDone(MachineDomTreeNode *Node,
Bill Wendlingd1634052012-07-19 00:04:14 +0000124 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000125 bool PerformCSE(MachineDomTreeNode *Node);
Evan Cheng036aa492010-03-02 02:38:24 +0000126 };
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000127
Evan Cheng036aa492010-03-02 02:38:24 +0000128} // end anonymous namespace
129
130char MachineCSE::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000131
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000132char &llvm::MachineCSEID = MachineCSE::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000133
Matthias Braun1527baa2017-05-25 21:26:32 +0000134INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE,
135 "Machine Common Subexpression Elimination", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000136INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000137INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000138INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE,
139 "Machine Common Subexpression Elimination", false, false)
Evan Cheng036aa492010-03-02 02:38:24 +0000140
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000141/// The source register of a COPY machine instruction can be propagated to all
142/// its users, and this propagation could increase the probability of finding
143/// common subexpressions. If the COPY has only one user, the COPY itself can
144/// be removed.
145bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
146 MachineBasicBlock *MBB) {
Evan Cheng4eab0082010-03-03 02:48:20 +0000147 bool Changed = false;
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000148 for (MachineOperand &MO : MI->operands()) {
Evan Chengb386cd32010-03-03 21:20:05 +0000149 if (!MO.isReg() || !MO.isUse())
150 continue;
151 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000152 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengb386cd32010-03-03 21:20:05 +0000153 continue;
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000154 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
Evan Chengb386cd32010-03-03 21:20:05 +0000155 MachineInstr *DefMI = MRI->getVRegDef(Reg);
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000156 if (!DefMI->isCopy())
157 continue;
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000158 unsigned SrcReg = DefMI->getOperand(1).getReg();
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000159 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
160 continue;
Andrew Tricke3398282013-12-17 04:50:45 +0000161 if (DefMI->getOperand(0).getSubReg())
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000162 continue;
Andrew Tricke4083f92013-12-17 19:29:36 +0000163 // FIXME: We should trivially coalesce subregister copies to expose CSE
164 // opportunities on instructions with truncated operands (see
165 // cse-add-with-overflow.ll). This can be done here as follows:
166 // if (SrcSubReg)
167 // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
168 // SrcSubReg);
169 // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
170 //
171 // The 2-addr pass has been updated to handle coalesced subregs. However,
172 // some machine-specific code still can't handle it.
173 // To handle it properly we also need a way find a constrained subregister
174 // class given a super-reg class and subreg index.
175 if (DefMI->getOperand(1).getSubReg())
176 continue;
Justin Bognera9346e02018-01-18 02:06:56 +0000177 if (!MRI->constrainRegAttrs(SrcReg, Reg))
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000178 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000179 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
180 LLVM_DEBUG(dbgs() << "*** to: " << *MI);
Carlos Alberto Enciso06adfa12018-08-30 07:17:41 +0000181
Carlos Alberto Enciso81d8ef22018-10-01 08:14:44 +0000182 // Update matching debug values.
183 DefMI->changeDebugValuesDefReg(SrcReg);
Carlos Alberto Enciso06adfa12018-08-30 07:17:41 +0000184
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000185 // Propagate SrcReg of copies to MI.
Andrew Tricke4083f92013-12-17 19:29:36 +0000186 MO.setReg(SrcReg);
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000187 MRI->clearKillFlags(SrcReg);
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000188 // Coalesce single use copies.
189 if (OnlyOneUse) {
190 DefMI->eraseFromParent();
191 ++NumCoalesces;
192 }
Jakob Stoklund Olesen00264622010-07-08 16:40:22 +0000193 Changed = true;
Evan Cheng4eab0082010-03-03 02:48:20 +0000194 }
195
196 return Changed;
197}
198
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000199bool
200MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
201 MachineBasicBlock::const_iterator I,
202 MachineBasicBlock::const_iterator E) const {
Eric Christopher53ff9922010-05-21 23:40:03 +0000203 unsigned LookAheadLeft = LookAheadLimit;
Evan Chengc7d721a2010-03-23 20:33:48 +0000204 while (LookAheadLeft) {
Evan Chengcf7be392010-03-24 01:50:28 +0000205 // Skip over dbg_value's.
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000206 I = skipDebugInstructionsForward(I, E);
Evan Chengcf7be392010-03-24 01:50:28 +0000207
Evan Cheng36f8aab2010-03-04 01:33:55 +0000208 if (I == E)
Mikael Holmen2676f822017-05-24 09:35:23 +0000209 // Reached end of block, we don't know if register is dead or not.
210 return false;
Evan Cheng36f8aab2010-03-04 01:33:55 +0000211
Evan Cheng36f8aab2010-03-04 01:33:55 +0000212 bool SeenDef = false;
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000213 for (const MachineOperand &MO : I->operands()) {
Jakob Stoklund Olesen4c5ad2b2012-02-28 02:08:50 +0000214 if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
215 SeenDef = true;
Evan Cheng36f8aab2010-03-04 01:33:55 +0000216 if (!MO.isReg() || !MO.getReg())
217 continue;
218 if (!TRI->regsOverlap(MO.getReg(), Reg))
219 continue;
220 if (MO.isUse())
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000221 // Found a use!
Evan Cheng36f8aab2010-03-04 01:33:55 +0000222 return false;
223 SeenDef = true;
224 }
225 if (SeenDef)
Andrew Trick9e761992012-02-08 21:22:43 +0000226 // See a def of Reg (or an alias) before encountering any use, it's
Evan Cheng36f8aab2010-03-04 01:33:55 +0000227 // trivially dead.
228 return true;
Evan Chengc7d721a2010-03-23 20:33:48 +0000229
230 --LookAheadLeft;
Evan Cheng36f8aab2010-03-04 01:33:55 +0000231 ++I;
232 }
233 return false;
234}
235
Roman Tereshin8d6ff4c2018-10-20 00:06:15 +0000236static bool isCallerPreservedOrConstPhysReg(unsigned Reg,
237 const MachineFunction &MF,
238 const TargetRegisterInfo &TRI) {
239 // MachineRegisterInfo::isConstantPhysReg directly called by
240 // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
241 // reserved registers to be frozen. That doesn't cause a problem post-ISel as
242 // most (if not all) targets freeze reserved registers right after ISel.
243 //
244 // It does cause issues mid-GlobalISel, however, hence the additional
245 // reservedRegsFrozen check.
246 const MachineRegisterInfo &MRI = MF.getRegInfo();
247 return TRI.isCallerPreservedPhysReg(Reg, MF) ||
248 (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
249}
250
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000251/// hasLivePhysRegDefUses - Return true if the specified instruction read/write
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000252/// physical registers (except for dead defs of physical registers). It also
Evan Chenga03e6f82010-06-04 23:28:13 +0000253/// returns the physical register def by reference if it's the only one and the
254/// instruction does not uses a physical register.
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000255bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
256 const MachineBasicBlock *MBB,
David Greencb5a48b2019-02-20 10:22:18 +0000257 SmallSet<unsigned, 8> &PhysRefs,
258 PhysDefVector &PhysDefs,
259 bool &PhysUseDef) const {
Ulrich Weigand39468772012-11-13 18:40:58 +0000260 // First, add all uses to PhysRefs.
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000261 for (const MachineOperand &MO : MI->operands()) {
Ulrich Weigand39468772012-11-13 18:40:58 +0000262 if (!MO.isReg() || MO.isDef())
Evan Cheng4eab0082010-03-03 02:48:20 +0000263 continue;
264 unsigned Reg = MO.getReg();
265 if (!Reg)
266 continue;
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000267 if (TargetRegisterInfo::isVirtualRegister(Reg))
268 continue;
Tony Jiangf75f4d62017-11-20 16:55:07 +0000269 // Reading either caller preserved or constant physregs is ok.
Roman Tereshin8d6ff4c2018-10-20 00:06:15 +0000270 if (!isCallerPreservedOrConstPhysReg(Reg, *MI->getMF(), *TRI))
Benjamin Kramer59c8b412012-08-11 20:42:59 +0000271 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
Benjamin Krameref6494f2012-08-11 19:05:13 +0000272 PhysRefs.insert(*AI);
Ulrich Weigand39468772012-11-13 18:40:58 +0000273 }
274
275 // Next, collect all defs into PhysDefs. If any is already in PhysRefs
276 // (which currently contains only uses), set the PhysUseDef flag.
277 PhysUseDef = false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000278 MachineBasicBlock::const_iterator I = MI; I = std::next(I);
David Greencb5a48b2019-02-20 10:22:18 +0000279 for (const auto &MOP : llvm::enumerate(MI->operands())) {
280 const MachineOperand &MO = MOP.value();
Ulrich Weigand39468772012-11-13 18:40:58 +0000281 if (!MO.isReg() || !MO.isDef())
282 continue;
283 unsigned Reg = MO.getReg();
284 if (!Reg)
285 continue;
286 if (TargetRegisterInfo::isVirtualRegister(Reg))
287 continue;
288 // Check against PhysRefs even if the def is "dead".
289 if (PhysRefs.count(Reg))
290 PhysUseDef = true;
291 // If the def is dead, it's ok. But the def may not marked "dead". That's
292 // common since this pass is run before livevariables. We can scan
293 // forward a few instructions and check if it is obviously dead.
294 if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end()))
David Greencb5a48b2019-02-20 10:22:18 +0000295 PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
Evan Cheng36f8aab2010-03-04 01:33:55 +0000296 }
297
Ulrich Weigand39468772012-11-13 18:40:58 +0000298 // Finally, add all defs to PhysRefs as well.
299 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
David Greencb5a48b2019-02-20 10:22:18 +0000300 for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
301 ++AI)
Ulrich Weigand39468772012-11-13 18:40:58 +0000302 PhysRefs.insert(*AI);
303
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000304 return !PhysRefs.empty();
Evan Cheng036aa492010-03-02 02:38:24 +0000305}
306
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000307bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
David Greencb5a48b2019-02-20 10:22:18 +0000308 SmallSet<unsigned, 8> &PhysRefs,
309 PhysDefVector &PhysDefs,
Evan Cheng0be41442012-01-10 02:02:58 +0000310 bool &NonLocal) const {
Eli Friedman54019622011-05-06 05:23:07 +0000311 // For now conservatively returns false if the common subexpression is
Evan Cheng0be41442012-01-10 02:02:58 +0000312 // not in the same basic block as the given instruction. The only exception
313 // is if the common subexpression is in the sole predecessor block.
314 const MachineBasicBlock *MBB = MI->getParent();
315 const MachineBasicBlock *CSMBB = CSMI->getParent();
316
317 bool CrossMBB = false;
318 if (CSMBB != MBB) {
Evan Chengd9725a32012-01-11 00:38:11 +0000319 if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
Evan Cheng0be41442012-01-10 02:02:58 +0000320 return false;
Evan Chengd9725a32012-01-11 00:38:11 +0000321
322 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
David Greencb5a48b2019-02-20 10:22:18 +0000323 if (MRI->isAllocatable(PhysDefs[i].second) ||
324 MRI->isReserved(PhysDefs[i].second))
Lang Hames5bade3d2012-02-17 00:27:16 +0000325 // Avoid extending live range of physical registers if they are
326 //allocatable or reserved.
Evan Chengd9725a32012-01-11 00:38:11 +0000327 return false;
328 }
329 CrossMBB = true;
Evan Cheng0be41442012-01-10 02:02:58 +0000330 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000331 MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
Eli Friedman54019622011-05-06 05:23:07 +0000332 MachineBasicBlock::const_iterator E = MI;
Evan Cheng0be41442012-01-10 02:02:58 +0000333 MachineBasicBlock::const_iterator EE = CSMBB->end();
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000334 unsigned LookAheadLeft = LookAheadLimit;
335 while (LookAheadLeft) {
Eli Friedman54019622011-05-06 05:23:07 +0000336 // Skip over dbg_value's.
Shiva Chen801bf7e2018-05-09 02:42:00 +0000337 while (I != E && I != EE && I->isDebugInstr())
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000338 ++I;
Eli Friedman54019622011-05-06 05:23:07 +0000339
Evan Cheng0be41442012-01-10 02:02:58 +0000340 if (I == EE) {
341 assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
Duncan Sandsae22c602012-02-05 14:20:11 +0000342 (void)CrossMBB;
Evan Cheng0be41442012-01-10 02:02:58 +0000343 CrossMBB = false;
344 NonLocal = true;
345 I = MBB->begin();
346 EE = MBB->end();
347 continue;
348 }
349
Eli Friedman54019622011-05-06 05:23:07 +0000350 if (I == E)
351 return true;
352
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000353 for (const MachineOperand &MO : I->operands()) {
Jakob Stoklund Olesen4c5ad2b2012-02-28 02:08:50 +0000354 // RegMasks go on instructions like calls that clobber lots of physregs.
355 // Don't attempt to CSE across such an instruction.
356 if (MO.isRegMask())
357 return false;
Eli Friedman54019622011-05-06 05:23:07 +0000358 if (!MO.isReg() || !MO.isDef())
359 continue;
360 unsigned MOReg = MO.getReg();
361 if (TargetRegisterInfo::isVirtualRegister(MOReg))
362 continue;
363 if (PhysRefs.count(MOReg))
364 return false;
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000365 }
Eli Friedman54019622011-05-06 05:23:07 +0000366
367 --LookAheadLeft;
368 ++I;
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000369 }
370
371 return false;
372}
373
Evan Cheng1abd1a92010-03-04 21:18:08 +0000374bool MachineCSE::isCSECandidate(MachineInstr *MI) {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000375 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
Shiva Chen801bf7e2018-05-09 02:42:00 +0000376 MI->isInlineAsm() || MI->isDebugInstr())
Evan Chengc9e86212010-03-08 23:49:12 +0000377 return false;
378
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000379 // Ignore copies.
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000380 if (MI->isCopyLike())
Evan Cheng1abd1a92010-03-04 21:18:08 +0000381 return false;
382
383 // Ignore stuff that we obviously can't move.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000384 if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
Ulrich Weigand6c5d5ce2019-06-05 22:33:10 +0000385 MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects())
Evan Cheng1abd1a92010-03-04 21:18:08 +0000386 return false;
387
Evan Cheng7f8e5632011-12-07 07:15:52 +0000388 if (MI->mayLoad()) {
Evan Cheng1abd1a92010-03-04 21:18:08 +0000389 // Okay, this instruction does a load. As a refinement, we allow the target
390 // to decide whether the loaded value is actually a constant. If so, we can
391 // actually use it as a load.
Justin Lebard98cf002016-09-10 01:03:20 +0000392 if (!MI->isDereferenceableInvariantLoad(AA))
Evan Cheng1abd1a92010-03-04 21:18:08 +0000393 // FIXME: we should be able to hoist loads with no other side effects if
394 // there are no other instructions which can change memory in this loop.
395 // This is a trivial form of alias analysis.
396 return false;
397 }
Tim Shene885d5e2016-04-19 19:40:37 +0000398
399 // Ignore stack guard loads, otherwise the register that holds CSEed value may
400 // be spilled and get loaded back with corrupted data.
401 if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
402 return false;
403
Evan Cheng1abd1a92010-03-04 21:18:08 +0000404 return true;
405}
406
Evan Cheng19e44b42010-03-09 03:21:12 +0000407/// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
David L. Jones0ff41b82019-05-27 06:00:00 +0000408/// common expression that defines Reg.
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000409bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
David L. Jones0ff41b82019-05-27 06:00:00 +0000410 MachineInstr *CSMI, MachineInstr *MI) {
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000411 // FIXME: Heuristics that works around the lack the live range splitting.
412
Manman Rencb36b8c2012-08-07 06:16:46 +0000413 // If CSReg is used at all uses of Reg, CSE should not increase register
414 // pressure of CSReg.
415 bool MayIncreasePressure = true;
416 if (TargetRegisterInfo::isVirtualRegister(CSReg) &&
417 TargetRegisterInfo::isVirtualRegister(Reg)) {
418 MayIncreasePressure = false;
419 SmallPtrSet<MachineInstr*, 8> CSUses;
Owen Andersonb36376e2014-03-17 19:36:09 +0000420 for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
421 CSUses.insert(&MI);
Manman Rencb36b8c2012-08-07 06:16:46 +0000422 }
Owen Andersonb36376e2014-03-17 19:36:09 +0000423 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
424 if (!CSUses.count(&MI)) {
Manman Rencb36b8c2012-08-07 06:16:46 +0000425 MayIncreasePressure = true;
426 break;
427 }
428 }
429 }
430 if (!MayIncreasePressure) return true;
431
Chris Lattner6c8b8dd2011-01-10 07:51:31 +0000432 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
433 // an immediate predecessor. We don't want to increase register pressure and
434 // end up causing other computation to be spilled.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000435 if (TII->isAsCheapAsAMove(*MI)) {
David L. Jones0ff41b82019-05-27 06:00:00 +0000436 MachineBasicBlock *CSBB = CSMI->getParent();
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000437 MachineBasicBlock *BB = MI->getParent();
Chris Lattner6c8b8dd2011-01-10 07:51:31 +0000438 if (CSBB != BB && !CSBB->isSuccessor(BB))
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000439 return false;
440 }
441
442 // Heuristics #2: If the expression doesn't not use a vr and the only use
443 // of the redundant computation are copies, do not cse.
444 bool HasVRegUse = false;
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000445 for (const MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000446 if (MO.isReg() && MO.isUse() &&
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000447 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
448 HasVRegUse = true;
449 break;
450 }
451 }
452 if (!HasVRegUse) {
453 bool HasNonCopyUse = false;
Owen Andersonb36376e2014-03-17 19:36:09 +0000454 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000455 // Ignore copies.
Owen Andersonb36376e2014-03-17 19:36:09 +0000456 if (!MI.isCopyLike()) {
Evan Cheng4c5f7a72010-03-10 02:12:03 +0000457 HasNonCopyUse = true;
458 break;
459 }
460 }
461 if (!HasNonCopyUse)
462 return false;
463 }
464
465 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
466 // it unless the defined value is already used in the BB of the new use.
Evan Cheng19e44b42010-03-09 03:21:12 +0000467 bool HasPHI = false;
Michael Zolotukhin131e7492018-05-04 01:40:05 +0000468 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
469 HasPHI |= UseMI.isPHI();
470 if (UseMI.getParent() == MI->getParent())
471 return true;
Evan Cheng19e44b42010-03-09 03:21:12 +0000472 }
473
Michael Zolotukhin131e7492018-05-04 01:40:05 +0000474 return !HasPHI;
Evan Cheng19e44b42010-03-09 03:21:12 +0000475}
476
Evan Cheng4b2ef562010-04-21 00:21:07 +0000477void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000478 LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Evan Cheng4b2ef562010-04-21 00:21:07 +0000479 ScopeType *Scope = new ScopeType(VNT);
480 ScopeMap[MBB] = Scope;
481}
482
483void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000484 LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
Evan Cheng4b2ef562010-04-21 00:21:07 +0000485 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
486 assert(SI != ScopeMap.end());
Evan Cheng4b2ef562010-04-21 00:21:07 +0000487 delete SI->second;
Jakub Staszakf18753b2012-11-26 22:14:19 +0000488 ScopeMap.erase(SI);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000489}
490
David L. Jones0ff41b82019-05-27 06:00:00 +0000491bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
Evan Cheng4eab0082010-03-03 02:48:20 +0000492 bool Changed = false;
493
Evan Cheng19e44b42010-03-09 03:21:12 +0000494 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
Manman Ren1be131b2012-08-08 00:51:41 +0000495 SmallVector<unsigned, 2> ImplicitDefsToUpdate;
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000496 SmallVector<unsigned, 2> ImplicitDefs;
Evan Chengb386cd32010-03-03 21:20:05 +0000497 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
Evan Cheng4eab0082010-03-03 02:48:20 +0000498 MachineInstr *MI = &*I;
Evan Chengb386cd32010-03-03 21:20:05 +0000499 ++I;
Evan Cheng1abd1a92010-03-04 21:18:08 +0000500
501 if (!isCSECandidate(MI))
Evan Cheng4eab0082010-03-03 02:48:20 +0000502 continue;
Evan Cheng4eab0082010-03-03 02:48:20 +0000503
504 bool FoundCSE = VNT.count(MI);
505 if (!FoundCSE) {
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000506 // Using trivial copy propagation to find more CSE opportunities.
507 if (PerformTrivialCopyPropagation(MI, MBB)) {
Evan Chengfe917ef2011-04-11 18:47:20 +0000508 Changed = true;
509
Evan Cheng604bc162010-04-02 02:21:24 +0000510 // After coalescing MI itself may become a copy.
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000511 if (MI->isCopyLike())
Evan Cheng604bc162010-04-02 02:21:24 +0000512 continue;
Jiangning Liudd6e12d2014-08-11 05:17:19 +0000513
514 // Try again to see if CSE is possible.
Evan Cheng4eab0082010-03-03 02:48:20 +0000515 FoundCSE = VNT.count(MI);
Evan Cheng604bc162010-04-02 02:21:24 +0000516 }
Evan Cheng4eab0082010-03-03 02:48:20 +0000517 }
Evan Chengb7ff5a02010-12-15 22:16:21 +0000518
519 // Commute commutable instructions.
520 bool Commuted = false;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000521 if (!FoundCSE && MI->isCommutable()) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000522 if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) {
Evan Chengb7ff5a02010-12-15 22:16:21 +0000523 Commuted = true;
524 FoundCSE = VNT.count(NewMI);
Evan Chengfe917ef2011-04-11 18:47:20 +0000525 if (NewMI != MI) {
Evan Chengb7ff5a02010-12-15 22:16:21 +0000526 // New instruction. It doesn't need to be kept.
527 NewMI->eraseFromParent();
Evan Chengfe917ef2011-04-11 18:47:20 +0000528 Changed = true;
529 } else if (!FoundCSE)
Evan Chengb7ff5a02010-12-15 22:16:21 +0000530 // MI was changed but it didn't help, commute it back!
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000531 (void)TII->commuteInstruction(*MI);
Evan Chengb7ff5a02010-12-15 22:16:21 +0000532 }
533 }
Evan Cheng4eab0082010-03-03 02:48:20 +0000534
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000535 // If the instruction defines physical registers and the values *may* be
Evan Cheng29226412010-03-03 23:59:08 +0000536 // used, then it's not safe to replace it with a common subexpression.
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000537 // It's also not safe if the instruction uses physical registers.
Evan Cheng0be41442012-01-10 02:02:58 +0000538 bool CrossMBBPhysDef = false;
Nick Lewycky765c6992012-07-05 06:19:21 +0000539 SmallSet<unsigned, 8> PhysRefs;
David Greencb5a48b2019-02-20 10:22:18 +0000540 PhysDefVector PhysDefs;
Ulrich Weigand39468772012-11-13 18:40:58 +0000541 bool PhysUseDef = false;
542 if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
543 PhysDefs, PhysUseDef)) {
Evan Cheng29226412010-03-03 23:59:08 +0000544 FoundCSE = false;
545
Evan Cheng0be41442012-01-10 02:02:58 +0000546 // ... Unless the CS is local or is in the sole predecessor block
547 // and it also defines the physical register which is not clobbered
548 // in between and the physical register uses were not clobbered.
Ulrich Weigand39468772012-11-13 18:40:58 +0000549 // This can never be the case if the instruction both uses and
550 // defines the same physical register, which was detected above.
551 if (!PhysUseDef) {
552 unsigned CSVN = VNT.lookup(MI);
553 MachineInstr *CSMI = Exps[CSVN];
554 if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
555 FoundCSE = true;
556 }
Evan Cheng2c8bdea2010-05-21 21:22:19 +0000557 }
558
Evan Chengb386cd32010-03-03 21:20:05 +0000559 if (!FoundCSE) {
560 VNT.insert(MI, CurrVN++);
561 Exps.push_back(MI);
562 continue;
563 }
564
565 // Found a common subexpression, eliminate it.
566 unsigned CSVN = VNT.lookup(MI);
567 MachineInstr *CSMI = Exps[CSVN];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "Examining: " << *MI);
569 LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
Evan Cheng19e44b42010-03-09 03:21:12 +0000570
571 // Check if it's profitable to perform this CSE.
572 bool DoCSE = true;
Roman Tereshinb2d3f2e2018-06-12 18:30:37 +0000573 unsigned NumDefs = MI->getNumDefs();
Andrew Trickcccd82f2013-12-16 19:36:18 +0000574
Evan Chengb386cd32010-03-03 21:20:05 +0000575 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
576 MachineOperand &MO = MI->getOperand(i);
577 if (!MO.isReg() || !MO.isDef())
578 continue;
579 unsigned OldReg = MO.getReg();
580 unsigned NewReg = CSMI->getOperand(i).getReg();
Manman Ren1be131b2012-08-08 00:51:41 +0000581
582 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
583 // we should make sure it is not dead at CSMI.
584 if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
585 ImplicitDefsToUpdate.push_back(i);
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000586
587 // Keep track of implicit defs of CSMI and MI, to clear possibly
588 // made-redundant kill flags.
589 if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
590 ImplicitDefs.push_back(OldReg);
591
Manman Ren1be131b2012-08-08 00:51:41 +0000592 if (OldReg == NewReg) {
593 --NumDefs;
Evan Cheng0f5f5472010-03-06 01:14:19 +0000594 continue;
Manman Ren1be131b2012-08-08 00:51:41 +0000595 }
Bill Wendling3e5409d2011-10-12 23:03:40 +0000596
Evan Cheng0f5f5472010-03-06 01:14:19 +0000597 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
Evan Chengb386cd32010-03-03 21:20:05 +0000598 TargetRegisterInfo::isVirtualRegister(NewReg) &&
599 "Do not CSE physical register defs!");
Bill Wendling3e5409d2011-10-12 23:03:40 +0000600
David L. Jones0ff41b82019-05-27 06:00:00 +0000601 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000602 LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
Evan Cheng19e44b42010-03-09 03:21:12 +0000603 DoCSE = false;
604 break;
605 }
Bill Wendling3e5409d2011-10-12 23:03:40 +0000606
Justin Bognera9346e02018-01-18 02:06:56 +0000607 // Don't perform CSE if the result of the new instruction cannot exist
608 // within the constraints (register class, bank, or low-level type) of
609 // the old instruction.
610 if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000611 LLVM_DEBUG(
612 dbgs() << "*** Not the same register constraints, avoid CSE!\n");
Bill Wendling3e5409d2011-10-12 23:03:40 +0000613 DoCSE = false;
614 break;
615 }
616
Evan Cheng19e44b42010-03-09 03:21:12 +0000617 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
Evan Chengb386cd32010-03-03 21:20:05 +0000618 --NumDefs;
619 }
Evan Cheng19e44b42010-03-09 03:21:12 +0000620
621 // Actually perform the elimination.
622 if (DoCSE) {
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000623 for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
624 unsigned OldReg = CSEPair.first;
625 unsigned NewReg = CSEPair.second;
Matthias Braun26e7ea62015-02-04 19:35:16 +0000626 // OldReg may have been unused but is used now, clear the Dead flag
627 MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
628 assert(Def != nullptr && "CSEd register has no unique definition?");
629 Def->clearRegisterDeads(NewReg);
630 // Replace with NewReg and clear kill flags which may be wrong now.
631 MRI->replaceRegWith(OldReg, NewReg);
632 MRI->clearKillFlags(NewReg);
Dan Gohman7767d272010-05-13 19:24:00 +0000633 }
Evan Cheng0be41442012-01-10 02:02:58 +0000634
Manman Ren1be131b2012-08-08 00:51:41 +0000635 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
636 // we should make sure it is not dead at CSMI.
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000637 for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
638 CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
David Greencb5a48b2019-02-20 10:22:18 +0000639 for (auto PhysDef : PhysDefs)
640 if (!MI->getOperand(PhysDef.first).isDead())
641 CSMI->getOperand(PhysDef.first).setIsDead(false);
Manman Ren1be131b2012-08-08 00:51:41 +0000642
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000643 // Go through implicit defs of CSMI and MI, and clear the kill flags on
644 // their uses in all the instructions between CSMI and MI.
645 // We might have made some of the kill flags redundant, consider:
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000646 // subs ... implicit-def %nzcv <- CSMI
647 // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
648 // subs ... implicit-def %nzcv <- MI, to be eliminated
649 // csinc ... implicit killed %nzcv
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000650 // Since we eliminated MI, and reused a register imp-def'd by CSMI
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000651 // (here %nzcv), that register, if it was killed before MI, should have
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000652 // that kill flag removed, because it's lifetime was extended.
653 if (CSMI->getParent() == MI->getParent()) {
654 for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
655 for (auto ImplicitDef : ImplicitDefs)
656 if (MachineOperand *MO = II->findRegisterUseOperand(
657 ImplicitDef, /*isKill=*/true, TRI))
658 MO->setIsKill(false);
659 } else {
660 // If the instructions aren't in the same BB, bail out and clear the
661 // kill flag on all uses of the imp-def'd register.
662 for (auto ImplicitDef : ImplicitDefs)
663 MRI->clearKillFlags(ImplicitDef);
664 }
665
Evan Cheng0be41442012-01-10 02:02:58 +0000666 if (CrossMBBPhysDef) {
667 // Add physical register defs now coming in from a predecessor to MBB
668 // livein list.
669 while (!PhysDefs.empty()) {
David Greencb5a48b2019-02-20 10:22:18 +0000670 auto LiveIn = PhysDefs.pop_back_val();
671 if (!MBB->isLiveIn(LiveIn.second))
672 MBB->addLiveIn(LiveIn.second);
Evan Cheng0be41442012-01-10 02:02:58 +0000673 }
674 ++NumCrossBBCSEs;
675 }
676
Evan Cheng19e44b42010-03-09 03:21:12 +0000677 MI->eraseFromParent();
678 ++NumCSEs;
Evan Cheng2b3f25e2010-10-29 23:36:03 +0000679 if (!PhysRefs.empty())
Evan Chenga03e6f82010-06-04 23:28:13 +0000680 ++NumPhysCSEs;
Evan Chengb7ff5a02010-12-15 22:16:21 +0000681 if (Commuted)
682 ++NumCommutes;
Evan Chengfe917ef2011-04-11 18:47:20 +0000683 Changed = true;
Evan Cheng19e44b42010-03-09 03:21:12 +0000684 } else {
Evan Cheng19e44b42010-03-09 03:21:12 +0000685 VNT.insert(MI, CurrVN++);
686 Exps.push_back(MI);
687 }
688 CSEPairs.clear();
Manman Ren1be131b2012-08-08 00:51:41 +0000689 ImplicitDefsToUpdate.clear();
Ahmed Bougacha54b7d332014-12-02 18:09:51 +0000690 ImplicitDefs.clear();
Evan Cheng4eab0082010-03-03 02:48:20 +0000691 }
692
Evan Cheng4b2ef562010-04-21 00:21:07 +0000693 return Changed;
694}
695
696/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
697/// dominator tree node if its a leaf or all of its children are done. Walk
698/// up the dominator tree to destroy ancestors which are now done.
699void
700MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
Nick Lewycky765c6992012-07-05 06:19:21 +0000701 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
Evan Cheng4b2ef562010-04-21 00:21:07 +0000702 if (OpenChildren[Node])
703 return;
704
705 // Pop scope.
706 ExitScope(Node->getBlock());
707
708 // Now traverse upwards to pop ancestors whose offsprings are all done.
Nick Lewycky765c6992012-07-05 06:19:21 +0000709 while (MachineDomTreeNode *Parent = Node->getIDom()) {
Evan Cheng4b2ef562010-04-21 00:21:07 +0000710 unsigned Left = --OpenChildren[Parent];
711 if (Left != 0)
712 break;
713 ExitScope(Parent->getBlock());
714 Node = Parent;
715 }
716}
717
718bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
719 SmallVector<MachineDomTreeNode*, 32> Scopes;
720 SmallVector<MachineDomTreeNode*, 8> WorkList;
Evan Cheng4b2ef562010-04-21 00:21:07 +0000721 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
722
Evan Chengb08377e2010-09-17 21:59:42 +0000723 CurrVN = 0;
724
Evan Cheng4b2ef562010-04-21 00:21:07 +0000725 // Perform a DFS walk to determine the order of visit.
726 WorkList.push_back(Node);
727 do {
728 Node = WorkList.pop_back_val();
729 Scopes.push_back(Node);
730 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000731 OpenChildren[Node] = Children.size();
732 for (MachineDomTreeNode *Child : Children)
Evan Cheng4b2ef562010-04-21 00:21:07 +0000733 WorkList.push_back(Child);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000734 } while (!WorkList.empty());
735
736 // Now perform CSE.
737 bool Changed = false;
Sanjay Patel3d07ec92016-01-06 00:45:42 +0000738 for (MachineDomTreeNode *Node : Scopes) {
Evan Cheng4b2ef562010-04-21 00:21:07 +0000739 MachineBasicBlock *MBB = Node->getBlock();
740 EnterScope(MBB);
David L. Jones0ff41b82019-05-27 06:00:00 +0000741 Changed |= ProcessBlock(MBB);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000742 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
Nick Lewycky765c6992012-07-05 06:19:21 +0000743 ExitScopeIfDone(Node, OpenChildren);
Evan Cheng4b2ef562010-04-21 00:21:07 +0000744 }
Evan Cheng4eab0082010-03-03 02:48:20 +0000745
746 return Changed;
747}
748
Evan Cheng036aa492010-03-02 02:38:24 +0000749bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000750 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000751 return false;
752
Eric Christopherfc6de422014-08-05 02:39:49 +0000753 TII = MF.getSubtarget().getInstrInfo();
754 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng4eab0082010-03-03 02:48:20 +0000755 MRI = &MF.getRegInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000756 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Evan Cheng19e44b42010-03-09 03:21:12 +0000757 DT = &getAnalysis<MachineDominatorTree>();
Tom Stellardf01af292015-05-09 00:56:07 +0000758 LookAheadLimit = TII->getMachineCSELookAheadLimit();
David L. Jones0ff41b82019-05-27 06:00:00 +0000759 return PerformCSE(DT->getRootNode());
Evan Cheng036aa492010-03-02 02:38:24 +0000760}