1//===- R600MergeVectorRegisters.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/// \file
10/// This pass merges inputs of swizzeable instructions into vector sharing
11/// common data and/or have enough undef subreg using swizzle abilities.
12///
13/// For instance let's consider the following pseudo code :
14/// %5 = REG_SEQ %1, sub0, %2, sub1, %3, sub2, undef, sub3
15/// ...
16/// %7 = REG_SEQ %1, sub0, %3, sub1, undef, sub2, %4, sub3
17/// (swizzable Inst) %7, SwizzleMask : sub0, sub1, sub2, sub3
18///
19/// is turned into :
20/// %5 = REG_SEQ %1, sub0, %2, sub1, %3, sub2, undef, sub3
21/// ...
22/// %7 = INSERT_SUBREG %4, sub3
23/// (swizzable Inst) %7, SwizzleMask : sub0, sub2, sub1, sub3
24///
25/// This allow regalloc to reduce register pressure for vector registers and
26/// to reduce MOV count.
27//===----------------------------------------------------------------------===//
28
29#include "MCTargetDesc/R600MCTargetDesc.h"
30#include "R600.h"
31#include "R600Defines.h"
32#include "R600Subtarget.h"
33#include "llvm/CodeGen/MachineDominators.h"
34#include "llvm/CodeGen/MachineLoopInfo.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "vec-merger"
39
40static bool isImplicitlyDef(MachineRegisterInfo &MRI, Register Reg) {
41 if (Reg.isPhysical())
42 return false;
43 const MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
44 return MI && MI->isImplicitDef();
45}
46
47namespace {
48
49class RegSeqInfo {
50public:
51 MachineInstr *Instr;
52 DenseMap<Register, unsigned> RegToChan;
53 std::vector<Register> UndefReg;
54
55 RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {
56 assert(MI->getOpcode() == R600::REG_SEQUENCE);
57 for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {
58 MachineOperand &MO = Instr->getOperand(i);
59 unsigned Chan = Instr->getOperand(i: i + 1).getImm();
60 if (isImplicitlyDef(MRI, Reg: MO.getReg()))
61 UndefReg.emplace_back(args&: Chan);
62 else
63 RegToChan[MO.getReg()] = Chan;
64 }
65 }
66
67 RegSeqInfo() = default;
68
69 bool operator==(const RegSeqInfo &RSI) const {
70 return RSI.Instr == Instr;
71 }
72};
73
74class R600VectorRegMerger : public MachineFunctionPass {
75private:
76 using InstructionSetMap = DenseMap<unsigned, std::vector<MachineInstr *>>;
77
78 MachineRegisterInfo *MRI;
79 const R600InstrInfo *TII = nullptr;
80 DenseMap<MachineInstr *, RegSeqInfo> PreviousRegSeq;
81 InstructionSetMap PreviousRegSeqByReg;
82 InstructionSetMap PreviousRegSeqByUndefCount;
83
84 bool canSwizzle(const MachineInstr &MI) const;
85 bool areAllUsesSwizzeable(Register Reg) const;
86 void SwizzleInput(MachineInstr &,
87 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const;
88 bool tryMergeVector(const RegSeqInfo *Untouched, RegSeqInfo *ToMerge,
89 std::vector<std::pair<unsigned, unsigned>> &Remap) const;
90 bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
91 std::vector<std::pair<unsigned, unsigned>> &RemapChan);
92 bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
93 std::vector<std::pair<unsigned, unsigned>> &RemapChan);
94 MachineInstr *RebuildVector(RegSeqInfo *MI, const RegSeqInfo *BaseVec,
95 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const;
96 void RemoveMI(MachineInstr *);
97 void trackRSI(const RegSeqInfo &RSI);
98
99public:
100 static char ID;
101
102 R600VectorRegMerger() : MachineFunctionPass(ID) {}
103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.setPreservesCFG();
106 AU.addRequired<MachineDominatorTreeWrapperPass>();
107 AU.addPreserved<MachineDominatorTreeWrapperPass>();
108 AU.addRequired<MachineLoopInfoWrapperPass>();
109 AU.addPreserved<MachineLoopInfoWrapperPass>();
110 MachineFunctionPass::getAnalysisUsage(AU);
111 }
112
113 MachineFunctionProperties getRequiredProperties() const override {
114 return MachineFunctionProperties().setIsSSA();
115 }
116
117 StringRef getPassName() const override {
118 return "R600 Vector Registers Merge Pass";
119 }
120
121 bool runOnMachineFunction(MachineFunction &Fn) override;
122};
123
124} // end anonymous namespace
125
126INITIALIZE_PASS_BEGIN(R600VectorRegMerger, DEBUG_TYPE,
127 "R600 Vector Reg Merger", false, false)
128INITIALIZE_PASS_END(R600VectorRegMerger, DEBUG_TYPE,
129 "R600 Vector Reg Merger", false, false)
130
131char R600VectorRegMerger::ID = 0;
132
133char &llvm::R600VectorRegMergerID = R600VectorRegMerger::ID;
134
135bool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)
136 const {
137 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
138 return true;
139 switch (MI.getOpcode()) {
140 case R600::R600_ExportSwz:
141 case R600::EG_ExportSwz:
142 return true;
143 default:
144 return false;
145 }
146}
147
148bool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,
149 RegSeqInfo *ToMerge, std::vector< std::pair<unsigned, unsigned>> &Remap)
150 const {
151 unsigned CurrentUndexIdx = 0;
152 for (auto &It : ToMerge->RegToChan) {
153 auto PosInUntouched = Untouched->RegToChan.find(Val: It.first);
154 if (PosInUntouched != Untouched->RegToChan.end()) {
155 Remap.emplace_back(args&: It.second, args: (*PosInUntouched).second);
156 continue;
157 }
158 if (CurrentUndexIdx >= Untouched->UndefReg.size())
159 return false;
160 Remap.emplace_back(args&: It.second, args: Untouched->UndefReg[CurrentUndexIdx++]);
161 }
162
163 return true;
164}
165
166static
167unsigned getReassignedChan(
168 const std::vector<std::pair<unsigned, unsigned>> &RemapChan,
169 unsigned Chan) {
170 for (const auto &J : RemapChan) {
171 if (J.first == Chan)
172 return J.second;
173 }
174 llvm_unreachable("Chan wasn't reassigned");
175}
176
177MachineInstr *R600VectorRegMerger::RebuildVector(
178 RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,
179 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
180 Register Reg = RSI->Instr->getOperand(i: 0).getReg();
181 MachineBasicBlock::iterator Pos = RSI->Instr;
182 MachineBasicBlock &MBB = *Pos->getParent();
183 const DebugLoc &DL = Pos->getDebugLoc();
184
185 Register SrcVec = BaseRSI->Instr->getOperand(i: 0).getReg();
186 DenseMap<Register, unsigned> UpdatedRegToChan = BaseRSI->RegToChan;
187 std::vector<Register> UpdatedUndef = BaseRSI->UndefReg;
188 for (const auto &It : RSI->RegToChan) {
189 Register DstReg = MRI->createVirtualRegister(RegClass: &R600::R600_Reg128RegClass);
190 unsigned SubReg = It.first;
191 unsigned Swizzle = It.second;
192 unsigned Chan = getReassignedChan(RemapChan, Chan: Swizzle);
193
194 MachineInstr *Tmp = BuildMI(BB&: MBB, I: Pos, MIMD: DL, MCID: TII->get(Opcode: R600::INSERT_SUBREG),
195 DestReg: DstReg)
196 .addReg(RegNo: SrcVec)
197 .addReg(RegNo: SubReg)
198 .addImm(Val: Chan);
199 UpdatedRegToChan[SubReg] = Chan;
200 std::vector<Register>::iterator ChanPos = llvm::find(Range&: UpdatedUndef, Val: Chan);
201 if (ChanPos != UpdatedUndef.end())
202 UpdatedUndef.erase(position: ChanPos);
203 assert(!is_contained(UpdatedUndef, Chan) &&
204 "UpdatedUndef shouldn't contain Chan more than once!");
205 LLVM_DEBUG(dbgs() << " ->"; Tmp->dump(););
206 (void)Tmp;
207 SrcVec = DstReg;
208 }
209 MachineInstr *NewMI =
210 BuildMI(BB&: MBB, I: Pos, MIMD: DL, MCID: TII->get(Opcode: R600::COPY), DestReg: Reg).addReg(RegNo: SrcVec);
211 LLVM_DEBUG(dbgs() << " ->"; NewMI->dump(););
212
213 LLVM_DEBUG(dbgs() << " Updating Swizzle:\n");
214 for (MachineRegisterInfo::use_instr_iterator It = MRI->use_instr_begin(RegNo: Reg),
215 E = MRI->use_instr_end(); It != E; ++It) {
216 LLVM_DEBUG(dbgs() << " "; (*It).dump(); dbgs() << " ->");
217 SwizzleInput(*It, RemapChan);
218 LLVM_DEBUG((*It).dump());
219 }
220 RSI->Instr->eraseFromParent();
221
222 // Update RSI
223 RSI->Instr = NewMI;
224 RSI->RegToChan = std::move(UpdatedRegToChan);
225 RSI->UndefReg = std::move(UpdatedUndef);
226
227 return NewMI;
228}
229
230void R600VectorRegMerger::RemoveMI(MachineInstr *MI) {
231 for (auto &It : PreviousRegSeqByReg) {
232 std::vector<MachineInstr *> &MIs = It.second;
233 MIs.erase(first: llvm::find(Range&: MIs, Val: MI), last: MIs.end());
234 }
235 for (auto &It : PreviousRegSeqByUndefCount) {
236 std::vector<MachineInstr *> &MIs = It.second;
237 MIs.erase(first: llvm::find(Range&: MIs, Val: MI), last: MIs.end());
238 }
239}
240
241void R600VectorRegMerger::SwizzleInput(MachineInstr &MI,
242 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
243 unsigned Offset;
244 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
245 Offset = 2;
246 else
247 Offset = 3;
248 for (unsigned i = 0; i < 4; i++) {
249 unsigned Swizzle = MI.getOperand(i: i + Offset).getImm() + 1;
250 for (const auto &J : RemapChan) {
251 if (J.first == Swizzle) {
252 MI.getOperand(i: i + Offset).setImm(J.second - 1);
253 break;
254 }
255 }
256 }
257}
258
259bool R600VectorRegMerger::areAllUsesSwizzeable(Register Reg) const {
260 return llvm::all_of(Range: MRI->use_instructions(Reg),
261 P: [&](const MachineInstr &MI) { return canSwizzle(MI); });
262}
263
264bool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,
265 RegSeqInfo &CompatibleRSI,
266 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
267 for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),
268 MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {
269 if (!MOp->isReg())
270 continue;
271 auto &Insts = PreviousRegSeqByReg[MOp->getReg()];
272 if (Insts.empty())
273 continue;
274 for (MachineInstr *MI : Insts) {
275 CompatibleRSI = PreviousRegSeq[MI];
276 if (RSI == CompatibleRSI)
277 continue;
278 if (tryMergeVector(Untouched: &CompatibleRSI, ToMerge: &RSI, Remap&: RemapChan))
279 return true;
280 }
281 }
282 return false;
283}
284
285bool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,
286 RegSeqInfo &CompatibleRSI,
287 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
288 unsigned NeededUndefs = 4 - RSI.UndefReg.size();
289 std::vector<MachineInstr *> &MIs =
290 PreviousRegSeqByUndefCount[NeededUndefs];
291 if (MIs.empty())
292 return false;
293 CompatibleRSI = PreviousRegSeq[MIs.back()];
294 tryMergeVector(Untouched: &CompatibleRSI, ToMerge: &RSI, Remap&: RemapChan);
295 return true;
296}
297
298void R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {
299 for (DenseMap<Register, unsigned>::const_iterator
300 It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {
301 PreviousRegSeqByReg[(*It).first].push_back(x: RSI.Instr);
302 }
303 PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(x: RSI.Instr);
304 PreviousRegSeq[RSI.Instr] = RSI;
305}
306
307bool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {
308 if (skipFunction(F: Fn.getFunction()))
309 return false;
310
311 const R600Subtarget &ST = Fn.getSubtarget<R600Subtarget>();
312 TII = ST.getInstrInfo();
313 MRI = &Fn.getRegInfo();
314
315 for (MachineBasicBlock &MB : Fn) {
316 PreviousRegSeq.clear();
317 PreviousRegSeqByReg.clear();
318 PreviousRegSeqByUndefCount.clear();
319
320 for (MachineBasicBlock::iterator MII = MB.begin(), MIIE = MB.end();
321 MII != MIIE; ++MII) {
322 MachineInstr &MI = *MII;
323 if (MI.getOpcode() != R600::REG_SEQUENCE) {
324 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST) {
325 Register Reg = MI.getOperand(i: 1).getReg();
326 for (MachineInstr &DefMI : MRI->def_instructions(Reg))
327 RemoveMI(MI: &DefMI);
328 }
329 continue;
330 }
331
332 RegSeqInfo RSI(*MRI, &MI);
333
334 // All uses of MI are swizzeable ?
335 Register Reg = MI.getOperand(i: 0).getReg();
336 if (!areAllUsesSwizzeable(Reg))
337 continue;
338
339 LLVM_DEBUG({
340 dbgs() << "Trying to optimize ";
341 MI.dump();
342 });
343
344 RegSeqInfo CandidateRSI;
345 std::vector<std::pair<unsigned, unsigned>> RemapChan;
346 LLVM_DEBUG(dbgs() << "Using common slots...\n";);
347 if (tryMergeUsingCommonSlot(RSI, CompatibleRSI&: CandidateRSI, RemapChan)) {
348 // Remove CandidateRSI mapping
349 RemoveMI(MI: CandidateRSI.Instr);
350 MII = RebuildVector(RSI: &RSI, BaseRSI: &CandidateRSI, RemapChan);
351 trackRSI(RSI);
352 continue;
353 }
354 LLVM_DEBUG(dbgs() << "Using free slots...\n";);
355 RemapChan.clear();
356 if (tryMergeUsingFreeSlot(RSI, CompatibleRSI&: CandidateRSI, RemapChan)) {
357 RemoveMI(MI: CandidateRSI.Instr);
358 MII = RebuildVector(RSI: &RSI, BaseRSI: &CandidateRSI, RemapChan);
359 trackRSI(RSI);
360 continue;
361 }
362 //Failed to merge
363 trackRSI(RSI);
364 }
365 }
366 return false;
367}
368
369llvm::FunctionPass *llvm::createR600VectorRegMerger() {
370 return new R600VectorRegMerger();
371}
372