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 //===---------------------------------------------------------------------===//
45 #include "PPCInstrInfo.h"
47 #include "PPCInstrBuilder.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 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
202 bool Changed = false;
205 if (gatherVectorInstructions()) {
207 recordUnoptimizableWebs();
208 markSwapsForRemoval();
209 Changed = removeSwaps();
212 // FIXME: See the allocation of EC in initialize().
218 // Initialize data structures for this pass. In particular, clear the
219 // swap vector and allocate the equivalence class mapping before
220 // processing each function.
221 void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) {
223 MRI = &MF->getRegInfo();
224 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
226 // An initial vector size of 256 appears to work well in practice.
227 // Small/medium functions with vector content tend not to incur a
228 // reallocation at this size. Three of the vector tests in
229 // projects/test-suite reallocate, which seems like a reasonable rate.
230 const int InitialVectorSize(256);
232 SwapVector.reserve(InitialVectorSize);
234 // FIXME: Currently we allocate EC each time because we don't have
235 // access to the set representation on which to call clear(). Should
236 // consider adding a clear() method to the EquivalenceClasses class.
237 EC = new EquivalenceClasses<int>;
240 // Create an entry in the swap vector for each instruction that mentions
241 // a full vector register, recording various characteristics of the
242 // instructions there.
243 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
244 bool RelevantFunction = false;
246 for (MachineBasicBlock &MBB : *MF) {
247 for (MachineInstr &MI : MBB) {
249 if (MI.isDebugValue())
252 bool RelevantInstr = false;
253 bool Partial = false;
255 for (const MachineOperand &MO : MI.operands()) {
258 unsigned Reg = MO.getReg();
259 if (isAnyVecReg(Reg, Partial)) {
260 RelevantInstr = true;
268 RelevantFunction = true;
270 // Create a SwapEntry initialized to zeros, then fill in the
271 // instruction and ID fields before pushing it to the back
272 // of the swap vector.
273 PPCVSXSwapEntry SwapEntry{};
274 int VecIdx = addSwapEntry(&MI, SwapEntry);
276 switch(MI.getOpcode()) {
278 // Unless noted otherwise, an instruction is considered
279 // safe for the optimization. There are a large number of
280 // such true-SIMD instructions (all vector math, logical,
281 // select, compare, etc.). However, if the instruction
282 // mentions a partial vector register and does not have
283 // special handling defined, it is not swappable.
285 SwapVector[VecIdx].MentionsPartialVR = 1;
287 SwapVector[VecIdx].IsSwappable = 1;
289 case PPC::XXPERMDI: {
290 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
291 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
292 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
293 // for example. We have to look through chains of COPY and
294 // SUBREG_TO_REG to find the real source value for comparison.
295 // If the real source value is a physical register, then mark the
296 // XXPERMDI as mentioning a physical register.
297 int immed = MI.getOperand(3).getImm();
299 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
301 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
303 if (trueReg1 == trueReg2)
304 SwapVector[VecIdx].IsSwap = 1;
306 // We can still handle these if the two registers are not
307 // identical, by adjusting the form of the XXPERMDI.
308 SwapVector[VecIdx].IsSwappable = 1;
309 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
311 // This is a doubleword splat if it is of the form
312 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
313 // must look through chains of copy-likes to find the source
314 // register. We turn off the marking for mention of a physical
315 // register, because splatting it is safe; the optimization
316 // will not swap the value in the physical register. Whether
317 // or not the two input registers are identical, we can handle
318 // these by adjusting the form of the XXPERMDI.
319 } else if (immed == 0 || immed == 3) {
321 SwapVector[VecIdx].IsSwappable = 1;
322 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
324 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
326 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
328 if (trueReg1 == trueReg2)
329 SwapVector[VecIdx].MentionsPhysVR = 0;
332 // We can still handle these by adjusting the form of the XXPERMDI.
333 SwapVector[VecIdx].IsSwappable = 1;
334 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
339 // Non-permuting loads are currently unsafe. We can use special
340 // handling for this in the future. By not marking these as
341 // IsSwap, we ensure computations containing them will be rejected
343 SwapVector[VecIdx].IsLoad = 1;
347 // Permuting loads are marked as both load and swap, and are
348 // safe for optimization.
349 SwapVector[VecIdx].IsLoad = 1;
350 SwapVector[VecIdx].IsSwap = 1;
354 // A load of a floating-point value into the high-order half of
355 // a vector register is safe, provided that we introduce a swap
356 // following the load, which will be done by the SUBREG_TO_REG
357 // support. So just mark these as safe.
358 SwapVector[VecIdx].IsLoad = 1;
359 SwapVector[VecIdx].IsSwappable = 1;
362 // Non-permuting stores are currently unsafe. We can use special
363 // handling for this in the future. By not marking these as
364 // IsSwap, we ensure computations containing them will be rejected
366 SwapVector[VecIdx].IsStore = 1;
370 // Permuting stores are marked as both store and swap, and are
371 // safe for optimization.
372 SwapVector[VecIdx].IsStore = 1;
373 SwapVector[VecIdx].IsSwap = 1;
376 // These are fine provided they are moving between full vector
378 if (isVecReg(MI.getOperand(0).getReg()) &&
379 isVecReg(MI.getOperand(1).getReg()))
380 SwapVector[VecIdx].IsSwappable = 1;
381 // If we have a copy from one scalar floating-point register
382 // to another, we can accept this even if it is a physical
383 // register. The only way this gets involved is if it feeds
384 // a SUBREG_TO_REG, which is handled by introducing a swap.
385 else if (isScalarVecReg(MI.getOperand(0).getReg()) &&
386 isScalarVecReg(MI.getOperand(1).getReg()))
387 SwapVector[VecIdx].IsSwappable = 1;
389 case PPC::SUBREG_TO_REG: {
390 // These are fine provided they are moving between full vector
391 // register classes. If they are moving from a scalar
392 // floating-point class to a vector class, we can handle those
393 // as well, provided we introduce a swap. It is generally the
394 // case that we will introduce fewer swaps than we remove, but
395 // (FIXME) a cost model could be used. However, introduced
396 // swaps could potentially be CSEd, so this is not trivial.
397 if (isVecReg(MI.getOperand(0).getReg()) &&
398 isVecReg(MI.getOperand(2).getReg()))
399 SwapVector[VecIdx].IsSwappable = 1;
400 else if (isVecReg(MI.getOperand(0).getReg()) &&
401 isScalarVecReg(MI.getOperand(2).getReg())) {
402 SwapVector[VecIdx].IsSwappable = 1;
403 SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN;
411 // Splats are lane-sensitive, but we can use special handling
412 // to adjust the source lane for the splat.
413 SwapVector[VecIdx].IsSwappable = 1;
414 SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT;
416 // The presence of the following lane-sensitive operations in a
417 // web will kill the optimization, at least for now. For these
418 // we do nothing, causing the optimization to fail.
419 // FIXME: Some of these could be permitted with special handling,
420 // and will be phased in as time permits.
421 // FIXME: There is no simple and maintainable way to express a set
422 // of opcodes having a common attribute in TableGen. Should this
423 // change, this is a prime candidate to use such a mechanism.
425 case PPC::EXTRACT_SUBREG:
426 case PPC::INSERT_SUBREG:
427 case PPC::COPY_TO_REGCLASS:
438 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
439 // by adding special handling for narrowing copies as well as
440 // widening ones. However, I've experimented with this, and in
441 // practice we currently do not appear to use STXSDX fed by
442 // a narrowing copy from a full vector register. Since I can't
443 // generate any useful test cases, I've left this alone for now.
447 case PPC::VCIPHERLAST:
467 case PPC::VNCIPHERLAST:
492 case PPC::VSHASIGMAD:
493 case PPC::VSHASIGMAW:
514 // XXSLDWI could be replaced by a general permute with one of three
515 // permute control vectors (for shift values 1, 2, 3). However,
516 // VPERM has a more restrictive register class.
523 if (RelevantFunction) {
524 DEBUG(dbgs() << "Swap vector when first built\n\n");
528 return RelevantFunction;
531 // Add an entry to the swap vector and swap map, and make a
532 // singleton equivalence class for the entry.
533 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
534 PPCVSXSwapEntry& SwapEntry) {
535 SwapEntry.VSEMI = MI;
536 SwapEntry.VSEId = SwapVector.size();
537 SwapVector.push_back(SwapEntry);
538 EC->insert(SwapEntry.VSEId);
539 SwapMap[MI] = SwapEntry.VSEId;
540 return SwapEntry.VSEId;
543 // This is used to find the "true" source register for an
544 // XXPERMDI instruction, since MachineCSE does not handle the
545 // "copy-like" operations (Copy and SubregToReg). Returns
546 // the original SrcReg unless it is the target of a copy-like
547 // operation, in which case we chain backwards through all
548 // such operations to the ultimate source register. If a
549 // physical register is encountered, we stop the search and
550 // flag the swap entry indicated by VecIdx (the original
551 // XXPERMDI) as mentioning a physical register.
552 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
554 MachineInstr *MI = MRI->getVRegDef(SrcReg);
555 if (!MI->isCopyLike())
560 CopySrcReg = MI->getOperand(1).getReg();
562 assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
563 CopySrcReg = MI->getOperand(2).getReg();
566 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg)) {
567 if (!isScalarVecReg(CopySrcReg))
568 SwapVector[VecIdx].MentionsPhysVR = 1;
572 return lookThruCopyLike(CopySrcReg, VecIdx);
575 // Generate equivalence classes for related computations (webs) by
576 // def-use relationships of virtual registers. Mention of a physical
577 // register terminates the generation of equivalence classes as this
578 // indicates a use of a parameter, definition of a return value, use
579 // of a value returned from a call, or definition of a parameter to a
580 // call. Computations with physical register mentions are flagged
581 // as such so their containing webs will not be optimized.
582 void PPCVSXSwapRemoval::formWebs() {
584 DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
586 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
588 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
590 DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
593 // It's sufficient to walk vector uses and join them to their unique
594 // definitions. In addition, check full vector register operands
595 // for physical regs. We exclude partial-vector register operands
596 // because we can handle them if copied to a full vector.
597 for (const MachineOperand &MO : MI->operands()) {
601 unsigned Reg = MO.getReg();
602 if (!isVecReg(Reg) && !isScalarVecReg(Reg))
605 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
606 if (!(MI->isCopy() && isScalarVecReg(Reg)))
607 SwapVector[EntryIdx].MentionsPhysVR = 1;
614 MachineInstr* DefMI = MRI->getVRegDef(Reg);
615 assert(SwapMap.find(DefMI) != SwapMap.end() &&
616 "Inconsistency: def of vector reg not found in swap map!");
617 int DefIdx = SwapMap[DefMI];
618 (void)EC->unionSets(SwapVector[DefIdx].VSEId,
619 SwapVector[EntryIdx].VSEId);
621 DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector[DefIdx].VSEId,
622 SwapVector[EntryIdx].VSEId));
623 DEBUG(dbgs() << " Def: ");
624 DEBUG(DefMI->dump());
629 // Walk the swap vector entries looking for conditions that prevent their
630 // containing computations from being optimized. When such conditions are
631 // found, mark the representative of the computation's equivalence class
633 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
635 DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
637 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
638 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
640 // If representative is already rejected, don't waste further time.
641 if (SwapVector[Repr].WebRejected)
644 // Reject webs containing mentions of physical or partial registers, or
645 // containing operations that we don't know how to handle in a lane-
647 if (SwapVector[EntryIdx].MentionsPhysVR ||
648 SwapVector[EntryIdx].MentionsPartialVR ||
649 !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
651 SwapVector[Repr].WebRejected = 1;
654 format("Web %d rejected for physreg, partial reg, or not "
655 "swap[pable]\n", Repr));
656 DEBUG(dbgs() << " in " << EntryIdx << ": ");
657 DEBUG(SwapVector[EntryIdx].VSEMI->dump());
658 DEBUG(dbgs() << "\n");
661 // Reject webs than contain swapping loads that feed something other
662 // than a swap instruction.
663 else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
664 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
665 unsigned DefReg = MI->getOperand(0).getReg();
667 // We skip debug instructions in the analysis. (Note that debug
668 // location information is still maintained by this optimization
669 // because it remains on the LXVD2X and STXVD2X instructions after
670 // the XXPERMDIs are removed.)
671 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
672 int UseIdx = SwapMap[&UseMI];
674 if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
675 SwapVector[UseIdx].IsStore) {
677 SwapVector[Repr].WebRejected = 1;
680 format("Web %d rejected for load not feeding swap\n", Repr));
681 DEBUG(dbgs() << " def " << EntryIdx << ": ");
683 DEBUG(dbgs() << " use " << UseIdx << ": ");
685 DEBUG(dbgs() << "\n");
689 // Reject webs that contain swapping stores that are fed by something
690 // other than a swap instruction.
691 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
692 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
693 unsigned UseReg = MI->getOperand(0).getReg();
694 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
695 unsigned DefReg = DefMI->getOperand(0).getReg();
696 int DefIdx = SwapMap[DefMI];
698 if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
699 SwapVector[DefIdx].IsStore) {
701 SwapVector[Repr].WebRejected = 1;
704 format("Web %d rejected for store not fed by swap\n", Repr));
705 DEBUG(dbgs() << " def " << DefIdx << ": ");
706 DEBUG(DefMI->dump());
707 DEBUG(dbgs() << " use " << EntryIdx << ": ");
709 DEBUG(dbgs() << "\n");
712 // Ensure all uses of the register defined by DefMI feed store
714 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
715 int UseIdx = SwapMap[&UseMI];
717 if (SwapVector[UseIdx].VSEMI->getOpcode() != MI->getOpcode()) {
718 SwapVector[Repr].WebRejected = 1;
721 format("Web %d rejected for swap not feeding only stores\n",
723 DEBUG(dbgs() << " def " << " : ");
724 DEBUG(DefMI->dump());
725 DEBUG(dbgs() << " use " << UseIdx << ": ");
726 DEBUG(SwapVector[UseIdx].VSEMI->dump());
727 DEBUG(dbgs() << "\n");
733 DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
737 // Walk the swap vector entries looking for swaps fed by permuting loads
738 // and swaps that feed permuting stores. If the containing computation
739 // has not been marked rejected, mark each such swap for removal.
740 // (Removal is delayed in case optimization has disturbed the pattern,
741 // such that multiple loads feed the same swap, etc.)
742 void PPCVSXSwapRemoval::markSwapsForRemoval() {
744 DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
746 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
748 if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
749 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
751 if (!SwapVector[Repr].WebRejected) {
752 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
753 unsigned DefReg = MI->getOperand(0).getReg();
755 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
756 int UseIdx = SwapMap[&UseMI];
757 SwapVector[UseIdx].WillRemove = 1;
759 DEBUG(dbgs() << "Marking swap fed by load for removal: ");
764 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
765 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
767 if (!SwapVector[Repr].WebRejected) {
768 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
769 unsigned UseReg = MI->getOperand(0).getReg();
770 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
771 int DefIdx = SwapMap[DefMI];
772 SwapVector[DefIdx].WillRemove = 1;
774 DEBUG(dbgs() << "Marking swap feeding store for removal: ");
775 DEBUG(DefMI->dump());
778 } else if (SwapVector[EntryIdx].IsSwappable &&
779 SwapVector[EntryIdx].SpecialHandling != 0) {
780 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
782 if (!SwapVector[Repr].WebRejected)
783 handleSpecialSwappables(EntryIdx);
788 // Create an xxswapd instruction and insert it prior to the given point.
789 // MI is used to determine basic block and debug loc information.
790 // FIXME: When inserting a swap, we should check whether SrcReg is
791 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
792 // then instead we should generate a copy from Reg to DstReg.
793 void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
794 MachineBasicBlock::iterator InsertPoint,
795 unsigned DstReg, unsigned SrcReg) {
796 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
797 TII->get(PPC::XXPERMDI), DstReg)
803 // The identified swap entry requires special handling to allow its
804 // containing computation to be optimized. Perform that handling
806 // FIXME: Additional opportunities will be phased in with subsequent
808 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
809 switch (SwapVector[EntryIdx].SpecialHandling) {
812 llvm_unreachable("Unexpected special handling type");
814 // For splats based on an index into a vector, add N/2 modulo N
815 // to the index, where N is the number of vector elements.
816 case SHValues::SH_SPLAT: {
817 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
820 DEBUG(dbgs() << "Changing splat: ");
823 switch (MI->getOpcode()) {
825 llvm_unreachable("Unexpected splat opcode");
826 case PPC::VSPLTB: NElts = 16; break;
827 case PPC::VSPLTH: NElts = 8; break;
829 case PPC::XXSPLTW: NElts = 4; break;
833 if (MI->getOpcode() == PPC::XXSPLTW)
834 EltNo = MI->getOperand(2).getImm();
836 EltNo = MI->getOperand(1).getImm();
838 EltNo = (EltNo + NElts / 2) % NElts;
839 if (MI->getOpcode() == PPC::XXSPLTW)
840 MI->getOperand(2).setImm(EltNo);
842 MI->getOperand(1).setImm(EltNo);
844 DEBUG(dbgs() << " Into: ");
849 // For an XXPERMDI that isn't handled otherwise, we need to
850 // reverse the order of the operands. If the selector operand
851 // has a value of 0 or 3, we need to change it to 3 or 0,
852 // respectively. Otherwise we should leave it alone. (This
853 // is equivalent to reversing the two bits of the selector
854 // operand and complementing the result.)
855 case SHValues::SH_XXPERMDI: {
856 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
858 DEBUG(dbgs() << "Changing XXPERMDI: ");
861 unsigned Selector = MI->getOperand(3).getImm();
862 if (Selector == 0 || Selector == 3)
863 Selector = 3 - Selector;
864 MI->getOperand(3).setImm(Selector);
866 unsigned Reg1 = MI->getOperand(1).getReg();
867 unsigned Reg2 = MI->getOperand(2).getReg();
868 MI->getOperand(1).setReg(Reg2);
869 MI->getOperand(2).setReg(Reg1);
871 DEBUG(dbgs() << " Into: ");
876 // For a copy from a scalar floating-point register to a vector
877 // register, removing swaps will leave the copied value in the
878 // wrong lane. Insert a swap following the copy to fix this.
879 case SHValues::SH_COPYWIDEN: {
880 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
882 DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
885 unsigned DstReg = MI->getOperand(0).getReg();
886 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
887 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
889 MI->getOperand(0).setReg(NewVReg);
890 DEBUG(dbgs() << " Into: ");
893 auto InsertPoint = ++MachineBasicBlock::iterator(MI);
895 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
896 // is copying to a VRRC, we need to be careful to avoid a register
897 // assignment problem. In this case we must copy from VRRC to VSRC
898 // prior to the swap, and from VSRC to VRRC following the swap.
899 // Coalescing will usually remove all this mess.
900 if (DstRC == &PPC::VRRCRegClass) {
901 unsigned VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
902 unsigned VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
904 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
905 TII->get(PPC::COPY), VSRCTmp1)
907 DEBUG(std::prev(InsertPoint)->dump());
909 insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
910 DEBUG(std::prev(InsertPoint)->dump());
912 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
913 TII->get(PPC::COPY), DstReg)
915 DEBUG(std::prev(InsertPoint)->dump());
918 insertSwap(MI, InsertPoint, DstReg, NewVReg);
919 DEBUG(std::prev(InsertPoint)->dump());
926 // Walk the swap vector and replace each entry marked for removal with
928 bool PPCVSXSwapRemoval::removeSwaps() {
930 DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
932 bool Changed = false;
934 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
935 if (SwapVector[EntryIdx].WillRemove) {
937 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
938 MachineBasicBlock *MBB = MI->getParent();
939 BuildMI(*MBB, MI, MI->getDebugLoc(),
940 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
941 .addOperand(MI->getOperand(1));
943 DEBUG(dbgs() << format("Replaced %d with copy: ",
944 SwapVector[EntryIdx].VSEId));
947 MI->eraseFromParent();
954 // For debug purposes, dump the contents of the swap vector.
955 void PPCVSXSwapRemoval::dumpSwapVector() {
957 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
959 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
960 int ID = SwapVector[EntryIdx].VSEId;
962 DEBUG(dbgs() << format("%6d", ID));
963 DEBUG(dbgs() << format("%6d", EC->getLeaderValue(ID)));
964 DEBUG(dbgs() << format(" BB#%3d", MI->getParent()->getNumber()));
965 DEBUG(dbgs() << format(" %14s ",
966 TII->getName(MI->getOpcode()).str().c_str()));
968 if (SwapVector[EntryIdx].IsLoad)
969 DEBUG(dbgs() << "load ");
970 if (SwapVector[EntryIdx].IsStore)
971 DEBUG(dbgs() << "store ");
972 if (SwapVector[EntryIdx].IsSwap)
973 DEBUG(dbgs() << "swap ");
974 if (SwapVector[EntryIdx].MentionsPhysVR)
975 DEBUG(dbgs() << "physreg ");
976 if (SwapVector[EntryIdx].MentionsPartialVR)
977 DEBUG(dbgs() << "partialreg ");
979 if (SwapVector[EntryIdx].IsSwappable) {
980 DEBUG(dbgs() << "swappable ");
981 switch(SwapVector[EntryIdx].SpecialHandling) {
983 DEBUG(dbgs() << "special:**unknown**");
988 DEBUG(dbgs() << "special:extract ");
991 DEBUG(dbgs() << "special:insert ");
994 DEBUG(dbgs() << "special:load ");
997 DEBUG(dbgs() << "special:store ");
1000 DEBUG(dbgs() << "special:splat ");
1003 DEBUG(dbgs() << "special:xxpermdi ");
1006 DEBUG(dbgs() << "special:copywiden ");
1011 if (SwapVector[EntryIdx].WebRejected)
1012 DEBUG(dbgs() << "rejected ");
1013 if (SwapVector[EntryIdx].WillRemove)
1014 DEBUG(dbgs() << "remove ");
1016 DEBUG(dbgs() << "\n");
1018 // For no-asserts builds.
1023 DEBUG(dbgs() << "\n");
1026 } // end default namespace
1028 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE,
1029 "PowerPC VSX Swap Removal", false, false)
1030 INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE,
1031 "PowerPC VSX Swap Removal", false, false)
1033 char PPCVSXSwapRemoval::ID = 0;
1035 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }