1 //===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===---------------------------------------------------------------------===//
10 // This pass analyzes vector computations and removes unnecessary
11 // doubleword swaps (xxswapd instructions). This pass is performed
12 // only for little-endian VSX code generation.
14 // For this specific case, loads and stores of v4i32, v4f32, v2i64,
15 // and v2f64 vectors are inefficient. These are implemented using
16 // the lxvd2x and stxvd2x instructions, which invert the order of
17 // doublewords in a vector register. Thus code generation inserts
18 // an xxswapd after each such load, and prior to each such store.
20 // The extra xxswapd instructions reduce performance. The purpose
21 // of this pass is to reduce the number of xxswapd instructions
22 // required for correctness.
24 // The primary insight is that much code that operates on vectors
25 // does not care about the relative order of elements in a register,
26 // so long as the correct memory order is preserved. If we have a
27 // computation where all input values are provided by lxvd2x/xxswapd,
28 // all outputs are stored using xxswapd/lxvd2x, and all intermediate
29 // computations are lane-insensitive (independent of element order),
30 // then all the xxswapd instructions associated with the loads and
31 // stores may be removed without changing observable semantics.
33 // This pass uses standard equivalence class infrastructure to create
34 // maximal webs of computations fitting the above description. Each
35 // such web is then optimized by removing its unnecessary xxswapd
38 // There are some lane-sensitive operations for which we can still
39 // permit the optimization, provided we modify those operations
40 // accordingly. Such operations are identified as using "special
41 // handling" within this module.
43 //===---------------------------------------------------------------------===//
46 #include "PPCInstrBuilder.h"
47 #include "PPCInstrInfo.h"
48 #include "PPCTargetMachine.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/EquivalenceClasses.h"
51 #include "llvm/CodeGen/MachineFunctionPass.h"
52 #include "llvm/CodeGen/MachineInstrBuilder.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/raw_ostream.h"
60 #define DEBUG_TYPE "ppc-vsx-swaps"
63 void initializePPCVSXSwapRemovalPass(PassRegistry
&);
68 // A PPCVSXSwapEntry is created for each machine instruction that
69 // is relevant to a vector computation.
70 struct PPCVSXSwapEntry
{
71 // Pointer to the instruction.
74 // Unique ID (position in the swap vector).
77 // Attributes of this node.
78 unsigned int IsLoad
: 1;
79 unsigned int IsStore
: 1;
80 unsigned int IsSwap
: 1;
81 unsigned int MentionsPhysVR
: 1;
82 unsigned int IsSwappable
: 1;
83 unsigned int MentionsPartialVR
: 1;
84 unsigned int SpecialHandling
: 3;
85 unsigned int WebRejected
: 1;
86 unsigned int WillRemove
: 1;
100 struct PPCVSXSwapRemoval
: public MachineFunctionPass
{
103 const PPCInstrInfo
*TII
;
105 MachineRegisterInfo
*MRI
;
107 // Swap entries are allocated in a vector for better performance.
108 std::vector
<PPCVSXSwapEntry
> SwapVector
;
110 // A mapping is maintained between machine instructions and
111 // their swap entries. The key is the address of the MI.
112 DenseMap
<MachineInstr
*, int> SwapMap
;
114 // Equivalence classes are used to gather webs of related computation.
115 // Swap entries are represented by their VSEId fields.
116 EquivalenceClasses
<int> *EC
;
118 PPCVSXSwapRemoval() : MachineFunctionPass(ID
) {
119 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
123 // Initialize data structures.
124 void initialize(MachineFunction
&MFParm
);
126 // Walk the machine instructions to gather vector usage information.
127 // Return true iff vector mentions are present.
128 bool gatherVectorInstructions();
130 // Add an entry to the swap vector and swap map.
131 int addSwapEntry(MachineInstr
*MI
, PPCVSXSwapEntry
&SwapEntry
);
133 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
134 // source register. VecIdx indicates the swap vector entry to
135 // mark as mentioning a physical register if the search leads
137 unsigned lookThruCopyLike(unsigned SrcReg
, unsigned VecIdx
);
139 // Generate equivalence classes for related computations (webs).
142 // Analyze webs and determine those that cannot be optimized.
143 void recordUnoptimizableWebs();
145 // Record which swap instructions can be safely removed.
146 void markSwapsForRemoval();
148 // Remove swaps and update other instructions requiring special
149 // handling. Return true iff any changes are made.
152 // Insert a swap instruction from SrcReg to DstReg at the given
154 void insertSwap(MachineInstr
*MI
, MachineBasicBlock::iterator InsertPoint
,
155 unsigned DstReg
, unsigned SrcReg
);
157 // Update instructions requiring special handling.
158 void handleSpecialSwappables(int EntryIdx
);
160 // Dump a description of the entries in the swap vector.
161 void dumpSwapVector();
163 // Return true iff the given register is in the given class.
164 bool isRegInClass(unsigned Reg
, const TargetRegisterClass
*RC
) {
165 if (TargetRegisterInfo::isVirtualRegister(Reg
))
166 return RC
->hasSubClassEq(MRI
->getRegClass(Reg
));
167 return RC
->contains(Reg
);
170 // Return true iff the given register is a full vector register.
171 bool isVecReg(unsigned Reg
) {
172 return (isRegInClass(Reg
, &PPC::VSRCRegClass
) ||
173 isRegInClass(Reg
, &PPC::VRRCRegClass
));
176 // Return true iff the given register is a partial vector register.
177 bool isScalarVecReg(unsigned Reg
) {
178 return (isRegInClass(Reg
, &PPC::VSFRCRegClass
) ||
179 isRegInClass(Reg
, &PPC::VSSRCRegClass
));
182 // Return true iff the given register mentions all or part of a
183 // vector register. Also sets Partial to true if the mention
184 // is for just the floating-point register overlap of the register.
185 bool isAnyVecReg(unsigned Reg
, bool &Partial
) {
186 if (isScalarVecReg(Reg
))
188 return isScalarVecReg(Reg
) || isVecReg(Reg
);
192 // Main entry point for this pass.
193 bool runOnMachineFunction(MachineFunction
&MF
) override
{
194 if (skipFunction(MF
.getFunction()))
197 // If we don't have VSX on the subtarget, don't do anything.
198 // Also, on Power 9 the load and store ops preserve element order and so
199 // the swaps are not required.
200 const PPCSubtarget
&STI
= MF
.getSubtarget
<PPCSubtarget
>();
201 if (!STI
.hasVSX() || !STI
.needsSwapsForVSXMemOps())
204 bool Changed
= false;
207 if (gatherVectorInstructions()) {
209 recordUnoptimizableWebs();
210 markSwapsForRemoval();
211 Changed
= removeSwaps();
214 // FIXME: See the allocation of EC in initialize().
220 // Initialize data structures for this pass. In particular, clear the
221 // swap vector and allocate the equivalence class mapping before
222 // processing each function.
223 void PPCVSXSwapRemoval::initialize(MachineFunction
&MFParm
) {
225 MRI
= &MF
->getRegInfo();
226 TII
= MF
->getSubtarget
<PPCSubtarget
>().getInstrInfo();
228 // An initial vector size of 256 appears to work well in practice.
229 // Small/medium functions with vector content tend not to incur a
230 // reallocation at this size. Three of the vector tests in
231 // projects/test-suite reallocate, which seems like a reasonable rate.
232 const int InitialVectorSize(256);
234 SwapVector
.reserve(InitialVectorSize
);
236 // FIXME: Currently we allocate EC each time because we don't have
237 // access to the set representation on which to call clear(). Should
238 // consider adding a clear() method to the EquivalenceClasses class.
239 EC
= new EquivalenceClasses
<int>;
242 // Create an entry in the swap vector for each instruction that mentions
243 // a full vector register, recording various characteristics of the
244 // instructions there.
245 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
246 bool RelevantFunction
= false;
248 for (MachineBasicBlock
&MBB
: *MF
) {
249 for (MachineInstr
&MI
: MBB
) {
251 if (MI
.isDebugValue())
254 bool RelevantInstr
= false;
255 bool Partial
= false;
257 for (const MachineOperand
&MO
: MI
.operands()) {
260 unsigned Reg
= MO
.getReg();
261 if (isAnyVecReg(Reg
, Partial
)) {
262 RelevantInstr
= true;
270 RelevantFunction
= true;
272 // Create a SwapEntry initialized to zeros, then fill in the
273 // instruction and ID fields before pushing it to the back
274 // of the swap vector.
275 PPCVSXSwapEntry SwapEntry
{};
276 int VecIdx
= addSwapEntry(&MI
, SwapEntry
);
278 switch(MI
.getOpcode()) {
280 // Unless noted otherwise, an instruction is considered
281 // safe for the optimization. There are a large number of
282 // such true-SIMD instructions (all vector math, logical,
283 // select, compare, etc.). However, if the instruction
284 // mentions a partial vector register and does not have
285 // special handling defined, it is not swappable.
287 SwapVector
[VecIdx
].MentionsPartialVR
= 1;
289 SwapVector
[VecIdx
].IsSwappable
= 1;
291 case PPC::XXPERMDI
: {
292 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
293 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
294 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
295 // for example. We have to look through chains of COPY and
296 // SUBREG_TO_REG to find the real source value for comparison.
297 // If the real source value is a physical register, then mark the
298 // XXPERMDI as mentioning a physical register.
299 int immed
= MI
.getOperand(3).getImm();
301 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
303 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
305 if (trueReg1
== trueReg2
)
306 SwapVector
[VecIdx
].IsSwap
= 1;
308 // We can still handle these if the two registers are not
309 // identical, by adjusting the form of the XXPERMDI.
310 SwapVector
[VecIdx
].IsSwappable
= 1;
311 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
313 // This is a doubleword splat if it is of the form
314 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
315 // must look through chains of copy-likes to find the source
316 // register. We turn off the marking for mention of a physical
317 // register, because splatting it is safe; the optimization
318 // will not swap the value in the physical register. Whether
319 // or not the two input registers are identical, we can handle
320 // these by adjusting the form of the XXPERMDI.
321 } else if (immed
== 0 || immed
== 3) {
323 SwapVector
[VecIdx
].IsSwappable
= 1;
324 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
326 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
328 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
330 if (trueReg1
== trueReg2
)
331 SwapVector
[VecIdx
].MentionsPhysVR
= 0;
334 // We can still handle these by adjusting the form of the XXPERMDI.
335 SwapVector
[VecIdx
].IsSwappable
= 1;
336 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
341 // Non-permuting loads are currently unsafe. We can use special
342 // handling for this in the future. By not marking these as
343 // IsSwap, we ensure computations containing them will be rejected
345 SwapVector
[VecIdx
].IsLoad
= 1;
349 // Permuting loads are marked as both load and swap, and are
350 // safe for optimization.
351 SwapVector
[VecIdx
].IsLoad
= 1;
352 SwapVector
[VecIdx
].IsSwap
= 1;
358 // A load of a floating-point value into the high-order half of
359 // a vector register is safe, provided that we introduce a swap
360 // following the load, which will be done by the SUBREG_TO_REG
361 // support. So just mark these as safe.
362 SwapVector
[VecIdx
].IsLoad
= 1;
363 SwapVector
[VecIdx
].IsSwappable
= 1;
366 // Non-permuting stores are currently unsafe. We can use special
367 // handling for this in the future. By not marking these as
368 // IsSwap, we ensure computations containing them will be rejected
370 SwapVector
[VecIdx
].IsStore
= 1;
374 // Permuting stores are marked as both store and swap, and are
375 // safe for optimization.
376 SwapVector
[VecIdx
].IsStore
= 1;
377 SwapVector
[VecIdx
].IsSwap
= 1;
380 // These are fine provided they are moving between full vector
382 if (isVecReg(MI
.getOperand(0).getReg()) &&
383 isVecReg(MI
.getOperand(1).getReg()))
384 SwapVector
[VecIdx
].IsSwappable
= 1;
385 // If we have a copy from one scalar floating-point register
386 // to another, we can accept this even if it is a physical
387 // register. The only way this gets involved is if it feeds
388 // a SUBREG_TO_REG, which is handled by introducing a swap.
389 else if (isScalarVecReg(MI
.getOperand(0).getReg()) &&
390 isScalarVecReg(MI
.getOperand(1).getReg()))
391 SwapVector
[VecIdx
].IsSwappable
= 1;
393 case PPC::SUBREG_TO_REG
: {
394 // These are fine provided they are moving between full vector
395 // register classes. If they are moving from a scalar
396 // floating-point class to a vector class, we can handle those
397 // as well, provided we introduce a swap. It is generally the
398 // case that we will introduce fewer swaps than we remove, but
399 // (FIXME) a cost model could be used. However, introduced
400 // swaps could potentially be CSEd, so this is not trivial.
401 if (isVecReg(MI
.getOperand(0).getReg()) &&
402 isVecReg(MI
.getOperand(2).getReg()))
403 SwapVector
[VecIdx
].IsSwappable
= 1;
404 else if (isVecReg(MI
.getOperand(0).getReg()) &&
405 isScalarVecReg(MI
.getOperand(2).getReg())) {
406 SwapVector
[VecIdx
].IsSwappable
= 1;
407 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_COPYWIDEN
;
415 // Splats are lane-sensitive, but we can use special handling
416 // to adjust the source lane for the splat.
417 SwapVector
[VecIdx
].IsSwappable
= 1;
418 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_SPLAT
;
420 // The presence of the following lane-sensitive operations in a
421 // web will kill the optimization, at least for now. For these
422 // we do nothing, causing the optimization to fail.
423 // FIXME: Some of these could be permitted with special handling,
424 // and will be phased in as time permits.
425 // FIXME: There is no simple and maintainable way to express a set
426 // of opcodes having a common attribute in TableGen. Should this
427 // change, this is a prime candidate to use such a mechanism.
429 case PPC::EXTRACT_SUBREG
:
430 case PPC::INSERT_SUBREG
:
431 case PPC::COPY_TO_REGCLASS
:
442 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
443 // by adding special handling for narrowing copies as well as
444 // widening ones. However, I've experimented with this, and in
445 // practice we currently do not appear to use STXSDX fed by
446 // a narrowing copy from a full vector register. Since I can't
447 // generate any useful test cases, I've left this alone for now.
451 case PPC::VCIPHERLAST
:
471 case PPC::VNCIPHERLAST
:
496 case PPC::VSHASIGMAD
:
497 case PPC::VSHASIGMAW
:
518 // XXSLDWI could be replaced by a general permute with one of three
519 // permute control vectors (for shift values 1, 2, 3). However,
520 // VPERM has a more restrictive register class.
529 if (RelevantFunction
) {
530 DEBUG(dbgs() << "Swap vector when first built\n\n");
531 DEBUG(dumpSwapVector());
534 return RelevantFunction
;
537 // Add an entry to the swap vector and swap map, and make a
538 // singleton equivalence class for the entry.
539 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr
*MI
,
540 PPCVSXSwapEntry
& SwapEntry
) {
541 SwapEntry
.VSEMI
= MI
;
542 SwapEntry
.VSEId
= SwapVector
.size();
543 SwapVector
.push_back(SwapEntry
);
544 EC
->insert(SwapEntry
.VSEId
);
545 SwapMap
[MI
] = SwapEntry
.VSEId
;
546 return SwapEntry
.VSEId
;
549 // This is used to find the "true" source register for an
550 // XXPERMDI instruction, since MachineCSE does not handle the
551 // "copy-like" operations (Copy and SubregToReg). Returns
552 // the original SrcReg unless it is the target of a copy-like
553 // operation, in which case we chain backwards through all
554 // such operations to the ultimate source register. If a
555 // physical register is encountered, we stop the search and
556 // flag the swap entry indicated by VecIdx (the original
557 // XXPERMDI) as mentioning a physical register.
558 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg
,
560 MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
561 if (!MI
->isCopyLike())
566 CopySrcReg
= MI
->getOperand(1).getReg();
568 assert(MI
->isSubregToReg() && "bad opcode for lookThruCopyLike");
569 CopySrcReg
= MI
->getOperand(2).getReg();
572 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg
)) {
573 if (!isScalarVecReg(CopySrcReg
))
574 SwapVector
[VecIdx
].MentionsPhysVR
= 1;
578 return lookThruCopyLike(CopySrcReg
, VecIdx
);
581 // Generate equivalence classes for related computations (webs) by
582 // def-use relationships of virtual registers. Mention of a physical
583 // register terminates the generation of equivalence classes as this
584 // indicates a use of a parameter, definition of a return value, use
585 // of a value returned from a call, or definition of a parameter to a
586 // call. Computations with physical register mentions are flagged
587 // as such so their containing webs will not be optimized.
588 void PPCVSXSwapRemoval::formWebs() {
590 DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
592 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
594 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
596 DEBUG(dbgs() << "\n" << SwapVector
[EntryIdx
].VSEId
<< " ");
599 // It's sufficient to walk vector uses and join them to their unique
600 // definitions. In addition, check full vector register operands
601 // for physical regs. We exclude partial-vector register operands
602 // because we can handle them if copied to a full vector.
603 for (const MachineOperand
&MO
: MI
->operands()) {
607 unsigned Reg
= MO
.getReg();
608 if (!isVecReg(Reg
) && !isScalarVecReg(Reg
))
611 if (!TargetRegisterInfo::isVirtualRegister(Reg
)) {
612 if (!(MI
->isCopy() && isScalarVecReg(Reg
)))
613 SwapVector
[EntryIdx
].MentionsPhysVR
= 1;
620 MachineInstr
* DefMI
= MRI
->getVRegDef(Reg
);
621 assert(SwapMap
.find(DefMI
) != SwapMap
.end() &&
622 "Inconsistency: def of vector reg not found in swap map!");
623 int DefIdx
= SwapMap
[DefMI
];
624 (void)EC
->unionSets(SwapVector
[DefIdx
].VSEId
,
625 SwapVector
[EntryIdx
].VSEId
);
627 DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector
[DefIdx
].VSEId
,
628 SwapVector
[EntryIdx
].VSEId
));
629 DEBUG(dbgs() << " Def: ");
630 DEBUG(DefMI
->dump());
635 // Walk the swap vector entries looking for conditions that prevent their
636 // containing computations from being optimized. When such conditions are
637 // found, mark the representative of the computation's equivalence class
639 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
641 DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
643 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
644 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
646 // If representative is already rejected, don't waste further time.
647 if (SwapVector
[Repr
].WebRejected
)
650 // Reject webs containing mentions of physical or partial registers, or
651 // containing operations that we don't know how to handle in a lane-
653 if (SwapVector
[EntryIdx
].MentionsPhysVR
||
654 SwapVector
[EntryIdx
].MentionsPartialVR
||
655 !(SwapVector
[EntryIdx
].IsSwappable
|| SwapVector
[EntryIdx
].IsSwap
)) {
657 SwapVector
[Repr
].WebRejected
= 1;
660 format("Web %d rejected for physreg, partial reg, or not "
661 "swap[pable]\n", Repr
));
662 DEBUG(dbgs() << " in " << EntryIdx
<< ": ");
663 DEBUG(SwapVector
[EntryIdx
].VSEMI
->dump());
664 DEBUG(dbgs() << "\n");
667 // Reject webs than contain swapping loads that feed something other
668 // than a swap instruction.
669 else if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
670 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
671 unsigned DefReg
= MI
->getOperand(0).getReg();
673 // We skip debug instructions in the analysis. (Note that debug
674 // location information is still maintained by this optimization
675 // because it remains on the LXVD2X and STXVD2X instructions after
676 // the XXPERMDIs are removed.)
677 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
678 int UseIdx
= SwapMap
[&UseMI
];
680 if (!SwapVector
[UseIdx
].IsSwap
|| SwapVector
[UseIdx
].IsLoad
||
681 SwapVector
[UseIdx
].IsStore
) {
683 SwapVector
[Repr
].WebRejected
= 1;
686 format("Web %d rejected for load not feeding swap\n", Repr
));
687 DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
689 DEBUG(dbgs() << " use " << UseIdx
<< ": ");
691 DEBUG(dbgs() << "\n");
695 // Reject webs that contain swapping stores that are fed by something
696 // other than a swap instruction.
697 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
698 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
699 unsigned UseReg
= MI
->getOperand(0).getReg();
700 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
701 unsigned DefReg
= DefMI
->getOperand(0).getReg();
702 int DefIdx
= SwapMap
[DefMI
];
704 if (!SwapVector
[DefIdx
].IsSwap
|| SwapVector
[DefIdx
].IsLoad
||
705 SwapVector
[DefIdx
].IsStore
) {
707 SwapVector
[Repr
].WebRejected
= 1;
710 format("Web %d rejected for store not fed by swap\n", Repr
));
711 DEBUG(dbgs() << " def " << DefIdx
<< ": ");
712 DEBUG(DefMI
->dump());
713 DEBUG(dbgs() << " use " << EntryIdx
<< ": ");
715 DEBUG(dbgs() << "\n");
718 // Ensure all uses of the register defined by DefMI feed store
720 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
721 int UseIdx
= SwapMap
[&UseMI
];
723 if (SwapVector
[UseIdx
].VSEMI
->getOpcode() != MI
->getOpcode()) {
724 SwapVector
[Repr
].WebRejected
= 1;
727 format("Web %d rejected for swap not feeding only stores\n",
729 DEBUG(dbgs() << " def " << " : ");
730 DEBUG(DefMI
->dump());
731 DEBUG(dbgs() << " use " << UseIdx
<< ": ");
732 DEBUG(SwapVector
[UseIdx
].VSEMI
->dump());
733 DEBUG(dbgs() << "\n");
739 DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
740 DEBUG(dumpSwapVector());
743 // Walk the swap vector entries looking for swaps fed by permuting loads
744 // and swaps that feed permuting stores. If the containing computation
745 // has not been marked rejected, mark each such swap for removal.
746 // (Removal is delayed in case optimization has disturbed the pattern,
747 // such that multiple loads feed the same swap, etc.)
748 void PPCVSXSwapRemoval::markSwapsForRemoval() {
750 DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
752 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
754 if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
755 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
757 if (!SwapVector
[Repr
].WebRejected
) {
758 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
759 unsigned DefReg
= MI
->getOperand(0).getReg();
761 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
762 int UseIdx
= SwapMap
[&UseMI
];
763 SwapVector
[UseIdx
].WillRemove
= 1;
765 DEBUG(dbgs() << "Marking swap fed by load for removal: ");
770 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
771 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
773 if (!SwapVector
[Repr
].WebRejected
) {
774 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
775 unsigned UseReg
= MI
->getOperand(0).getReg();
776 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
777 int DefIdx
= SwapMap
[DefMI
];
778 SwapVector
[DefIdx
].WillRemove
= 1;
780 DEBUG(dbgs() << "Marking swap feeding store for removal: ");
781 DEBUG(DefMI
->dump());
784 } else if (SwapVector
[EntryIdx
].IsSwappable
&&
785 SwapVector
[EntryIdx
].SpecialHandling
!= 0) {
786 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
788 if (!SwapVector
[Repr
].WebRejected
)
789 handleSpecialSwappables(EntryIdx
);
794 // Create an xxswapd instruction and insert it prior to the given point.
795 // MI is used to determine basic block and debug loc information.
796 // FIXME: When inserting a swap, we should check whether SrcReg is
797 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
798 // then instead we should generate a copy from Reg to DstReg.
799 void PPCVSXSwapRemoval::insertSwap(MachineInstr
*MI
,
800 MachineBasicBlock::iterator InsertPoint
,
801 unsigned DstReg
, unsigned SrcReg
) {
802 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
803 TII
->get(PPC::XXPERMDI
), DstReg
)
809 // The identified swap entry requires special handling to allow its
810 // containing computation to be optimized. Perform that handling
812 // FIXME: Additional opportunities will be phased in with subsequent
814 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx
) {
815 switch (SwapVector
[EntryIdx
].SpecialHandling
) {
818 llvm_unreachable("Unexpected special handling type");
820 // For splats based on an index into a vector, add N/2 modulo N
821 // to the index, where N is the number of vector elements.
822 case SHValues::SH_SPLAT
: {
823 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
826 DEBUG(dbgs() << "Changing splat: ");
829 switch (MI
->getOpcode()) {
831 llvm_unreachable("Unexpected splat opcode");
832 case PPC::VSPLTB
: NElts
= 16; break;
833 case PPC::VSPLTH
: NElts
= 8; break;
835 case PPC::XXSPLTW
: NElts
= 4; break;
839 if (MI
->getOpcode() == PPC::XXSPLTW
)
840 EltNo
= MI
->getOperand(2).getImm();
842 EltNo
= MI
->getOperand(1).getImm();
844 EltNo
= (EltNo
+ NElts
/ 2) % NElts
;
845 if (MI
->getOpcode() == PPC::XXSPLTW
)
846 MI
->getOperand(2).setImm(EltNo
);
848 MI
->getOperand(1).setImm(EltNo
);
850 DEBUG(dbgs() << " Into: ");
855 // For an XXPERMDI that isn't handled otherwise, we need to
856 // reverse the order of the operands. If the selector operand
857 // has a value of 0 or 3, we need to change it to 3 or 0,
858 // respectively. Otherwise we should leave it alone. (This
859 // is equivalent to reversing the two bits of the selector
860 // operand and complementing the result.)
861 case SHValues::SH_XXPERMDI
: {
862 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
864 DEBUG(dbgs() << "Changing XXPERMDI: ");
867 unsigned Selector
= MI
->getOperand(3).getImm();
868 if (Selector
== 0 || Selector
== 3)
869 Selector
= 3 - Selector
;
870 MI
->getOperand(3).setImm(Selector
);
872 unsigned Reg1
= MI
->getOperand(1).getReg();
873 unsigned Reg2
= MI
->getOperand(2).getReg();
874 MI
->getOperand(1).setReg(Reg2
);
875 MI
->getOperand(2).setReg(Reg1
);
877 DEBUG(dbgs() << " Into: ");
882 // For a copy from a scalar floating-point register to a vector
883 // register, removing swaps will leave the copied value in the
884 // wrong lane. Insert a swap following the copy to fix this.
885 case SHValues::SH_COPYWIDEN
: {
886 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
888 DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
891 unsigned DstReg
= MI
->getOperand(0).getReg();
892 const TargetRegisterClass
*DstRC
= MRI
->getRegClass(DstReg
);
893 unsigned NewVReg
= MRI
->createVirtualRegister(DstRC
);
895 MI
->getOperand(0).setReg(NewVReg
);
896 DEBUG(dbgs() << " Into: ");
899 auto InsertPoint
= ++MachineBasicBlock::iterator(MI
);
901 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
902 // is copying to a VRRC, we need to be careful to avoid a register
903 // assignment problem. In this case we must copy from VRRC to VSRC
904 // prior to the swap, and from VSRC to VRRC following the swap.
905 // Coalescing will usually remove all this mess.
906 if (DstRC
== &PPC::VRRCRegClass
) {
907 unsigned VSRCTmp1
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
908 unsigned VSRCTmp2
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
910 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
911 TII
->get(PPC::COPY
), VSRCTmp1
)
913 DEBUG(std::prev(InsertPoint
)->dump());
915 insertSwap(MI
, InsertPoint
, VSRCTmp2
, VSRCTmp1
);
916 DEBUG(std::prev(InsertPoint
)->dump());
918 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
919 TII
->get(PPC::COPY
), DstReg
)
921 DEBUG(std::prev(InsertPoint
)->dump());
924 insertSwap(MI
, InsertPoint
, DstReg
, NewVReg
);
925 DEBUG(std::prev(InsertPoint
)->dump());
932 // Walk the swap vector and replace each entry marked for removal with
934 bool PPCVSXSwapRemoval::removeSwaps() {
936 DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
938 bool Changed
= false;
940 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
941 if (SwapVector
[EntryIdx
].WillRemove
) {
943 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
944 MachineBasicBlock
*MBB
= MI
->getParent();
945 BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(TargetOpcode::COPY
),
946 MI
->getOperand(0).getReg())
947 .add(MI
->getOperand(1));
949 DEBUG(dbgs() << format("Replaced %d with copy: ",
950 SwapVector
[EntryIdx
].VSEId
));
953 MI
->eraseFromParent();
960 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
961 // For debug purposes, dump the contents of the swap vector.
962 LLVM_DUMP_METHOD
void PPCVSXSwapRemoval::dumpSwapVector() {
964 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
966 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
967 int ID
= SwapVector
[EntryIdx
].VSEId
;
969 dbgs() << format("%6d", ID
);
970 dbgs() << format("%6d", EC
->getLeaderValue(ID
));
971 dbgs() << format(" %bb.%3d", MI
->getParent()->getNumber());
972 dbgs() << format(" %14s ", TII
->getName(MI
->getOpcode()).str().c_str());
974 if (SwapVector
[EntryIdx
].IsLoad
)
976 if (SwapVector
[EntryIdx
].IsStore
)
978 if (SwapVector
[EntryIdx
].IsSwap
)
980 if (SwapVector
[EntryIdx
].MentionsPhysVR
)
981 dbgs() << "physreg ";
982 if (SwapVector
[EntryIdx
].MentionsPartialVR
)
983 dbgs() << "partialreg ";
985 if (SwapVector
[EntryIdx
].IsSwappable
) {
986 dbgs() << "swappable ";
987 switch(SwapVector
[EntryIdx
].SpecialHandling
) {
989 dbgs() << "special:**unknown**";
994 dbgs() << "special:extract ";
997 dbgs() << "special:insert ";
1000 dbgs() << "special:load ";
1003 dbgs() << "special:store ";
1006 dbgs() << "special:splat ";
1009 dbgs() << "special:xxpermdi ";
1012 dbgs() << "special:copywiden ";
1017 if (SwapVector
[EntryIdx
].WebRejected
)
1018 dbgs() << "rejected ";
1019 if (SwapVector
[EntryIdx
].WillRemove
)
1020 dbgs() << "remove ";
1024 // For no-asserts builds.
1033 } // end default namespace
1035 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1036 "PowerPC VSX Swap Removal", false, false)
1037 INITIALIZE_PASS_END(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1038 "PowerPC VSX Swap Removal", false, false)
1040 char PPCVSXSwapRemoval::ID
= 0;
1042 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }