LLVM 23.0.0git
HexagonRDFOpt.cpp
Go to the documentation of this file.
1//===- HexagonRDFOpt.cpp --------------------------------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "Hexagon.h"
11#include "HexagonInstrInfo.h"
12#include "HexagonSubtarget.h"
14#include "RDFCopy.h"
15#include "RDFDeadCode.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SetVector.h"
31#include "llvm/Pass.h"
34#include "llvm/Support/Debug.h"
37#include <cassert>
38#include <limits>
39
40using namespace llvm;
41using namespace rdf;
42
43static unsigned RDFCount = 0;
45
47 RDFLimit("hexagon-rdf-limit",
48 cl::init(std::numeric_limits<unsigned>::max()));
50 "hexagon-aggressive-rdf-copy",
51 cl::desc("Enable aggressive RDF copy propagation with super-register "
52 "support"),
53 cl::init(false), cl::Hidden);
54static cl::opt<bool> RDFDump("hexagon-rdf-dump", cl::Hidden);
55static cl::opt<bool> RDFTrackReserved("hexagon-rdf-track-reserved", cl::Hidden);
56
57namespace {
58
59 class HexagonRDFOpt : public MachineFunctionPass {
60 public:
61 HexagonRDFOpt() : MachineFunctionPass(ID) {}
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.addRequired<MachineDominatorTreeWrapperPass>();
65 AU.addRequired<MachineDominanceFrontierWrapperPass>();
66 AU.setPreservesAll();
68 }
69
70 StringRef getPassName() const override {
71 return "Hexagon RDF optimizations";
72 }
73
74 bool runOnMachineFunction(MachineFunction &MF) override;
75
76 MachineFunctionProperties getRequiredProperties() const override {
77 return MachineFunctionProperties().setNoVRegs();
78 }
79
80 static char ID;
81
82 private:
83 MachineDominatorTree *MDT;
84 MachineRegisterInfo *MRI;
85 };
86
87struct HexagonCP : public CopyPropagation {
88 HexagonCP(DataFlowGraph &G) : CopyPropagation(G) {}
89
90 bool interpretAsCopy(const MachineInstr *MI, EqualityMap &EM) override;
91};
92
93struct HexagonAggressiveCP : public AggressiveCopyPropagation {
94 HexagonAggressiveCP(DataFlowGraph &G) : AggressiveCopyPropagation(G) {}
95
96 bool interpretAsCopy(const MachineInstr *MI, EqualityMap &EM) override;
97};
98
99struct HexagonDCE : public DeadCodeElimination {
100 HexagonDCE(DataFlowGraph &G, MachineRegisterInfo &MRI)
101 : DeadCodeElimination(G, MRI) {}
102
103 bool rewrite(NodeAddr<InstrNode*> IA, SetVector<NodeId> &Remove);
104 void removeOperand(NodeAddr<InstrNode*> IA, unsigned OpNum);
105
106 bool run();
107};
108
109} // end anonymous namespace
110
111char HexagonRDFOpt::ID = 0;
112
113INITIALIZE_PASS_BEGIN(HexagonRDFOpt, "hexagon-rdf-opt",
114 "Hexagon RDF optimizations", false, false)
117INITIALIZE_PASS_END(HexagonRDFOpt, "hexagon-rdf-opt",
118 "Hexagon RDF optimizations", false, false)
119
120bool HexagonCP::interpretAsCopy(const MachineInstr *MI, EqualityMap &EM) {
121 auto mapRegs = [&EM] (RegisterRef DstR, RegisterRef SrcR) -> void {
122 EM.insert(std::make_pair(DstR, SrcR));
123 };
124
125 DataFlowGraph &DFG = getDFG();
126 unsigned Opc = MI->getOpcode();
127 switch (Opc) {
128 case Hexagon::A2_combinew: {
129 const MachineOperand &DstOp = MI->getOperand(0);
130 const MachineOperand &HiOp = MI->getOperand(1);
131 const MachineOperand &LoOp = MI->getOperand(2);
132 assert(DstOp.getSubReg() == 0 && "Unexpected subregister");
133 mapRegs(DFG.makeRegRef(DstOp.getReg(), Hexagon::isub_hi),
134 DFG.makeRegRef(HiOp.getReg(), HiOp.getSubReg()));
135 mapRegs(DFG.makeRegRef(DstOp.getReg(), Hexagon::isub_lo),
136 DFG.makeRegRef(LoOp.getReg(), LoOp.getSubReg()));
137 return true;
138 }
139 case Hexagon::A2_addi: {
140 const MachineOperand &A = MI->getOperand(2);
141 if (!A.isImm() || A.getImm() != 0)
142 return false;
143 [[fallthrough]];
144 }
145 case Hexagon::A2_tfr: {
146 const MachineOperand &DstOp = MI->getOperand(0);
147 const MachineOperand &SrcOp = MI->getOperand(1);
148 mapRegs(DFG.makeRegRef(DstOp.getReg(), DstOp.getSubReg()),
149 DFG.makeRegRef(SrcOp.getReg(), SrcOp.getSubReg()));
150 return true;
151 }
152 }
153
154 return CopyPropagation::interpretAsCopy(MI, EM);
155}
156
157bool HexagonAggressiveCP::interpretAsCopy(const MachineInstr *MI,
158 EqualityMap &EM) {
159 auto mapRegs = [&EM](RegisterRef DstR, RegisterRef SrcR) -> void {
160 EM.insert(std::make_pair(DstR, SrcR));
161 };
162
163 DataFlowGraph &DFG = getDFG();
164 const TargetRegisterInfo &TRI = DFG.getTRI();
165 unsigned Opc = MI->getOpcode();
166 switch (Opc) {
167 case Hexagon::A2_combinew: {
168 // Combine instruction is equivalent to double reg copy.
169 // Add double reg copy to map.
170 const MachineOperand &DstOp = MI->getOperand(0);
171 const MachineOperand &HiOp = MI->getOperand(1);
172 const MachineOperand &LoOp = MI->getOperand(2);
173 assert(DstOp.getSubReg() == 0 && "Unexpected subregister");
174 unsigned DoubleRegDest = TRI.getMatchingSuperReg(
175 LoOp.getReg(), Hexagon::isub_lo, &Hexagon::DoubleRegsRegClass);
176 if (DoubleRegDest != 0 &&
177 TRI.isSuperRegister(HiOp.getReg(), DoubleRegDest))
178 mapRegs(DFG.makeRegRef(DstOp), DFG.makeRegRef(DoubleRegDest, 0));
179 mapRegs(DFG.makeRegRef(DstOp.getReg(), Hexagon::isub_hi),
180 DFG.makeRegRef(HiOp.getReg(), HiOp.getSubReg()));
181 mapRegs(DFG.makeRegRef(DstOp.getReg(), Hexagon::isub_lo),
182 DFG.makeRegRef(LoOp.getReg(), LoOp.getSubReg()));
183 return true;
184 }
185 case Hexagon::A2_addi: {
186 const MachineOperand &A = MI->getOperand(2);
187 if (!A.isImm() || A.getImm() != 0)
188 return false;
189 [[fallthrough]];
190 }
191 case Hexagon::A2_tfr: {
192 const MachineOperand &DstOp = MI->getOperand(0);
193 const MachineOperand &SrcOp = MI->getOperand(1);
194 mapRegs(DFG.makeRegRef(DstOp.getReg(), DstOp.getSubReg()),
195 DFG.makeRegRef(SrcOp.getReg(), SrcOp.getSubReg()));
196 return true;
197 }
198 }
199
201}
202
203bool HexagonDCE::run() {
204 bool Collected = collect();
205 if (!Collected)
206 return false;
207
208 const SetVector<NodeId> &DeadNodes = getDeadNodes();
209 const SetVector<NodeId> &DeadInstrs = getDeadInstrs();
210
211 using RefToInstrMap = DenseMap<NodeId, NodeId>;
212
213 RefToInstrMap R2I;
214 SetVector<NodeId> PartlyDead;
215 DataFlowGraph &DFG = getDFG();
216
217 for (NodeAddr<BlockNode*> BA : DFG.getFunc().Addr->members(DFG)) {
218 for (auto TA : BA.Addr->members_if(DFG.IsCode<NodeAttrs::Stmt>, DFG)) {
219 NodeAddr<StmtNode*> SA = TA;
220 for (NodeAddr<RefNode*> RA : SA.Addr->members(DFG)) {
221 R2I.insert(std::make_pair(RA.Id, SA.Id));
222 if (DFG.IsDef(RA) && DeadNodes.count(RA.Id))
223 if (!DeadInstrs.count(SA.Id))
224 PartlyDead.insert(SA.Id);
225 }
226 }
227 }
228
229 // Nodes to remove.
230 SetVector<NodeId> Remove = DeadInstrs;
231
232 bool Changed = false;
233 for (NodeId N : PartlyDead) {
234 auto SA = DFG.addr<StmtNode*>(N);
235 if (trace())
236 dbgs() << "Partly dead: " << *SA.Addr->getCode();
237 Changed |= rewrite(SA, Remove);
238 }
239
240 return erase(Remove) || Changed;
241}
242
243void HexagonDCE::removeOperand(NodeAddr<InstrNode*> IA, unsigned OpNum) {
244 MachineInstr *MI = NodeAddr<StmtNode*>(IA).Addr->getCode();
245
246 auto getOpNum = [MI] (MachineOperand &Op) -> unsigned {
247 for (unsigned i = 0, n = MI->getNumOperands(); i != n; ++i)
248 if (&MI->getOperand(i) == &Op)
249 return i;
250 llvm_unreachable("Invalid operand");
251 };
252 DenseMap<NodeId,unsigned> OpMap;
253 DataFlowGraph &DFG = getDFG();
254 NodeList Refs = IA.Addr->members(DFG);
255 for (NodeAddr<RefNode*> RA : Refs)
256 OpMap.insert(std::make_pair(RA.Id, getOpNum(RA.Addr->getOp())));
257
258 MI->removeOperand(OpNum);
259
260 for (NodeAddr<RefNode*> RA : Refs) {
261 unsigned N = OpMap[RA.Id];
262 if (N < OpNum)
263 RA.Addr->setRegRef(&MI->getOperand(N), DFG);
264 else if (N > OpNum)
265 RA.Addr->setRegRef(&MI->getOperand(N-1), DFG);
266 }
267}
268
269bool HexagonDCE::rewrite(NodeAddr<InstrNode*> IA, SetVector<NodeId> &Remove) {
270 if (!getDFG().IsCode<NodeAttrs::Stmt>(IA))
271 return false;
272 DataFlowGraph &DFG = getDFG();
273 MachineInstr &MI = *NodeAddr<StmtNode*>(IA).Addr->getCode();
274 auto &HII = static_cast<const HexagonInstrInfo&>(DFG.getTII());
275 if (HII.getAddrMode(MI) != HexagonII::PostInc)
276 return false;
277 unsigned Opc = MI.getOpcode();
278 unsigned OpNum, NewOpc;
279 switch (Opc) {
280 case Hexagon::L2_loadri_pi:
281 NewOpc = Hexagon::L2_loadri_io;
282 OpNum = 1;
283 break;
284 case Hexagon::L2_loadrd_pi:
285 NewOpc = Hexagon::L2_loadrd_io;
286 OpNum = 1;
287 break;
288 case Hexagon::V6_vL32b_pi:
289 NewOpc = Hexagon::V6_vL32b_ai;
290 OpNum = 1;
291 break;
292 case Hexagon::S2_storeri_pi:
293 NewOpc = Hexagon::S2_storeri_io;
294 OpNum = 0;
295 break;
296 case Hexagon::S2_storerd_pi:
297 NewOpc = Hexagon::S2_storerd_io;
298 OpNum = 0;
299 break;
300 case Hexagon::V6_vS32b_pi:
301 NewOpc = Hexagon::V6_vS32b_ai;
302 OpNum = 0;
303 break;
304 default:
305 return false;
306 }
307 auto IsDead = [this] (NodeAddr<DefNode*> DA) -> bool {
308 return getDeadNodes().count(DA.Id);
309 };
310 NodeList Defs;
311 MachineOperand &Op = MI.getOperand(OpNum);
312 for (NodeAddr<DefNode*> DA : IA.Addr->members_if(DFG.IsDef, DFG)) {
313 if (&DA.Addr->getOp() != &Op)
314 continue;
315 Defs = DFG.getRelatedRefs(IA, DA);
316 if (!llvm::all_of(Defs, IsDead))
317 return false;
318 break;
319 }
320
321 // Mark all nodes in Defs for removal.
322 for (auto D : Defs)
323 Remove.insert(D.Id);
324
325 if (trace())
326 dbgs() << "Rewriting: " << MI;
327 MI.setDesc(HII.get(NewOpc));
328 MI.getOperand(OpNum+2).setImm(0);
329 removeOperand(IA, OpNum);
330 if (trace())
331 dbgs() << " to: " << MI;
332
333 return true;
334}
335
336bool HexagonRDFOpt::runOnMachineFunction(MachineFunction &MF) {
337 if (skipFunction(MF.getFunction()))
338 return false;
339
340 // Perform RDF optimizations only if number of basic blocks in the
341 // function is less than the limit
342 if (MF.size() > RDFFuncBlockLimit) {
343 if (RDFDump)
344 dbgs() << "Skipping " << getPassName() << ": too many basic blocks\n";
345 return false;
346 }
347
348 if (RDFLimit.getPosition()) {
349 if (RDFCount >= RDFLimit)
350 return false;
351 RDFCount++;
352 }
353
354 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
355 const auto &MDF = getAnalysis<MachineDominanceFrontierWrapperPass>().getMDF();
356 const auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
357 const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
358 MRI = &MF.getRegInfo();
359 bool Changed;
360
361 if (RDFDump)
362 MF.print(dbgs() << "Before " << getPassName() << "\n", nullptr);
363
364 DataFlowGraph G(MF, HII, HRI, *MDT, MDF);
365 // Dead phi nodes are necessary for copy propagation: we can add a use
366 // of a register in a block where it would need a phi node, but which
367 // was dead (and removed) during the graph build time.
368 DataFlowGraph::Config Cfg;
372 G.build(Cfg);
373
375 if (RDFDump)
376 dbgs() << "Starting aggressive copy propagation on: " << MF.getName()
377 << '\n'
378 << PrintNode<FuncNode *>(G.getFunc(), G) << '\n';
379 HexagonAggressiveCP CP(G);
380 CP.trace(RDFDump);
381 Changed = CP.run();
382 } else {
383 if (RDFDump)
384 dbgs() << "Starting copy propagation on: " << MF.getName() << '\n'
385 << PrintNode<FuncNode *>(G.getFunc(), G) << '\n';
386 HexagonCP CP(G);
387 CP.trace(RDFDump);
388 Changed = CP.run();
389 }
390
391 if (RDFDump)
392 dbgs() << "Starting dead code elimination on: " << MF.getName() << '\n'
393 << PrintNode<FuncNode*>(G.getFunc(), G) << '\n';
394 HexagonDCE DCE(G, *MRI);
395 DCE.trace(RDFDump);
396 Changed |= DCE.run();
397
398 if (Changed) {
399 if (RDFDump) {
400 dbgs() << "Starting liveness recomputation on: " << MF.getName() << '\n'
401 << PrintNode<FuncNode*>(G.getFunc(), G) << '\n';
402 }
403 Liveness LV(*MRI, G);
404 LV.trace(RDFDump);
405 LV.computeLiveIns();
406
407 // Set entry-block live-ins from the RDF LiveMap: calling-convention
408 // registers may not have direct uses and cannot be recovered by a
409 // backward walk.
410 MachineBasicBlock &EntryMBB = MF.front();
411 {
412 std::vector<MCRegister> Old;
413 for (const MachineBasicBlock::RegisterMaskPair &LI : EntryMBB.liveins())
414 Old.push_back(LI.PhysReg);
415 for (MCRegister R : Old)
416 EntryMBB.removeLiveIn(R);
417 for (RegisterRef R : LV.getLiveMap()[&EntryMBB].refs())
418 EntryMBB.addLiveIn({R.asMCReg(), R.Mask});
419 EntryMBB.sortUniqueLiveIns();
420 }
421
422 // The RDF-based live-in recomputation can leave stale (over-approximate)
423 // physical register live-ins on some blocks, which later confuses passes
424 // like IfConversion into inserting incorrect implicit-use operands. Run a
425 // conventional backward liveness recomputation to correct the live-in
426 // lists. Skip:
427 // - the entry block: handled above from the RDF LiveMap;
428 // - EH pads: exception pointer/selector are runtime-established.
430 for (MachineBasicBlock &B : MF)
431 if (!B.isEntryBlock() && !B.isEHPad())
432 Blocks.push_back(&B);
433 fullyRecomputeLiveIns(Blocks);
434
435 // Recompute kill flags against the updated live-in lists.
436 LV.resetKills();
437 }
438
439 if (RDFDump)
440 MF.print(dbgs() << "After " << getPassName() << "\n", nullptr);
441
442 return false;
443}
444
446 return new HexagonRDFOpt();
447}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
cl::opt< unsigned > RDFFuncBlockLimit
static cl::opt< bool > RDFTrackReserved("hexagon-rdf-track-reserved", cl::Hidden)
static cl::opt< bool > EnableAggressiveRDFCopy("hexagon-aggressive-rdf-copy", cl::desc("Enable aggressive RDF copy propagation with super-register " "support"), cl::init(false), cl::Hidden)
static cl::opt< unsigned > RDFLimit("hexagon-rdf-limit", cl::init(std::numeric_limits< unsigned >::max()))
static unsigned RDFCount
static cl::opt< bool > RDFDump("hexagon-rdf-dump", cl::Hidden)
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define G(x, y, z)
Definition MD5.cpp:55
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
bool IsDead
SI optimize exec mask operations pre RA
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Register getReg() const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
iterator_range< livein_iterator > liveins() const
LLVM_ABI void removeLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
void push_back(const T &Elt)
Register getReg() const
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
uint32_t NodeId
Definition RDFGraph.h:262
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:552
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
FunctionPass * createHexagonRDFOpt()
#define N
virtual bool interpretAsCopy(const MachineInstr *MI, EqualityMap &EM)
LLVM_ABI NodeList members(const DataFlowGraph &G) const
Definition RDFGraph.cpp:519
LLVM_ABI RegisterRef makeRegRef(unsigned Reg, unsigned Sub) const
Definition RDFGraph.cpp:987
static bool IsDef(const Node BA)
Definition RDFGraph.h:829
LLVM_ABI NodeList getRelatedRefs(Instr IA, Ref RA) const
const TargetInstrInfo & getTII() const
Definition RDFGraph.h:700
static bool IsCode(const Node BA)
Definition RDFGraph.h:825
const TargetRegisterInfo & getTRI() const
Definition RDFGraph.h:701
NodeAddr< T > addr(NodeId N) const
Definition RDFGraph.h:694