xref: /freebsd/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCPreEmitPeephole.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===--------- PPCPreEmitPeephole.cpp - Late peephole optimizations -------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // A pre-emit peephole for catching opportunities introduced by late passes such
100b57cec5SDimitry Andric // as MachineBlockPlacement.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "PPC.h"
150b57cec5SDimitry Andric #include "PPCInstrInfo.h"
160b57cec5SDimitry Andric #include "PPCSubtarget.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
24*81ad6265SDimitry Andric #include "llvm/CodeGen/RegisterScavenging.h"
25e8d8bef9SDimitry Andric #include "llvm/MC/MCContext.h"
260b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
270b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric using namespace llvm;
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric #define DEBUG_TYPE "ppc-pre-emit-peephole"
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric STATISTIC(NumRRConvertedInPreEmit,
340b57cec5SDimitry Andric           "Number of r+r instructions converted to r+i in pre-emit peephole");
350b57cec5SDimitry Andric STATISTIC(NumRemovedInPreEmit,
360b57cec5SDimitry Andric           "Number of instructions deleted in pre-emit peephole");
370b57cec5SDimitry Andric STATISTIC(NumberOfSelfCopies,
380b57cec5SDimitry Andric           "Number of self copy instructions eliminated");
39480093f4SDimitry Andric STATISTIC(NumFrameOffFoldInPreEmit,
40480093f4SDimitry Andric           "Number of folding frame offset by using r+r in pre-emit peephole");
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric static cl::opt<bool>
43e8d8bef9SDimitry Andric EnablePCRelLinkerOpt("ppc-pcrel-linker-opt", cl::Hidden, cl::init(true),
44e8d8bef9SDimitry Andric                      cl::desc("enable PC Relative linker optimization"));
45e8d8bef9SDimitry Andric 
46e8d8bef9SDimitry Andric static cl::opt<bool>
470b57cec5SDimitry Andric RunPreEmitPeephole("ppc-late-peephole", cl::Hidden, cl::init(true),
480b57cec5SDimitry Andric                    cl::desc("Run pre-emit peephole optimizations."));
490b57cec5SDimitry Andric 
50*81ad6265SDimitry Andric static cl::opt<uint64_t>
51*81ad6265SDimitry Andric DSCRValue("ppc-set-dscr", cl::Hidden,
52*81ad6265SDimitry Andric           cl::desc("Set the Data Stream Control Register."));
53*81ad6265SDimitry Andric 
540b57cec5SDimitry Andric namespace {
55e8d8bef9SDimitry Andric 
56e8d8bef9SDimitry Andric static bool hasPCRelativeForm(MachineInstr &Use) {
57e8d8bef9SDimitry Andric   switch (Use.getOpcode()) {
58e8d8bef9SDimitry Andric   default:
59e8d8bef9SDimitry Andric     return false;
60e8d8bef9SDimitry Andric   case PPC::LBZ:
61e8d8bef9SDimitry Andric   case PPC::LBZ8:
62e8d8bef9SDimitry Andric   case PPC::LHA:
63e8d8bef9SDimitry Andric   case PPC::LHA8:
64e8d8bef9SDimitry Andric   case PPC::LHZ:
65e8d8bef9SDimitry Andric   case PPC::LHZ8:
66e8d8bef9SDimitry Andric   case PPC::LWZ:
67e8d8bef9SDimitry Andric   case PPC::LWZ8:
68e8d8bef9SDimitry Andric   case PPC::STB:
69e8d8bef9SDimitry Andric   case PPC::STB8:
70e8d8bef9SDimitry Andric   case PPC::STH:
71e8d8bef9SDimitry Andric   case PPC::STH8:
72e8d8bef9SDimitry Andric   case PPC::STW:
73e8d8bef9SDimitry Andric   case PPC::STW8:
74e8d8bef9SDimitry Andric   case PPC::LD:
75e8d8bef9SDimitry Andric   case PPC::STD:
76e8d8bef9SDimitry Andric   case PPC::LWA:
77e8d8bef9SDimitry Andric   case PPC::LXSD:
78e8d8bef9SDimitry Andric   case PPC::LXSSP:
79e8d8bef9SDimitry Andric   case PPC::LXV:
80e8d8bef9SDimitry Andric   case PPC::STXSD:
81e8d8bef9SDimitry Andric   case PPC::STXSSP:
82e8d8bef9SDimitry Andric   case PPC::STXV:
83e8d8bef9SDimitry Andric   case PPC::LFD:
84e8d8bef9SDimitry Andric   case PPC::LFS:
85e8d8bef9SDimitry Andric   case PPC::STFD:
86e8d8bef9SDimitry Andric   case PPC::STFS:
87e8d8bef9SDimitry Andric   case PPC::DFLOADf32:
88e8d8bef9SDimitry Andric   case PPC::DFLOADf64:
89e8d8bef9SDimitry Andric   case PPC::DFSTOREf32:
90e8d8bef9SDimitry Andric   case PPC::DFSTOREf64:
91e8d8bef9SDimitry Andric     return true;
92e8d8bef9SDimitry Andric   }
93e8d8bef9SDimitry Andric }
94e8d8bef9SDimitry Andric 
950b57cec5SDimitry Andric   class PPCPreEmitPeephole : public MachineFunctionPass {
960b57cec5SDimitry Andric   public:
970b57cec5SDimitry Andric     static char ID;
980b57cec5SDimitry Andric     PPCPreEmitPeephole() : MachineFunctionPass(ID) {
990b57cec5SDimitry Andric       initializePPCPreEmitPeepholePass(*PassRegistry::getPassRegistry());
1000b57cec5SDimitry Andric     }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
1030b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
1040b57cec5SDimitry Andric     }
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
1070b57cec5SDimitry Andric       return MachineFunctionProperties().set(
1080b57cec5SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
1090b57cec5SDimitry Andric     }
1100b57cec5SDimitry Andric 
1118bcb0991SDimitry Andric     // This function removes any redundant load immediates. It has two level
1128bcb0991SDimitry Andric     // loops - The outer loop finds the load immediates BBI that could be used
1138bcb0991SDimitry Andric     // to replace following redundancy. The inner loop scans instructions that
1148bcb0991SDimitry Andric     // after BBI to find redundancy and update kill/dead flags accordingly. If
1158bcb0991SDimitry Andric     // AfterBBI is the same as BBI, it is redundant, otherwise any instructions
1168bcb0991SDimitry Andric     // that modify the def register of BBI would break the scanning.
1178bcb0991SDimitry Andric     // DeadOrKillToUnset is a pointer to the previous operand that had the
1188bcb0991SDimitry Andric     // kill/dead flag set. It keeps track of the def register of BBI, the use
1198bcb0991SDimitry Andric     // registers of AfterBBIs and the def registers of AfterBBIs.
1208bcb0991SDimitry Andric     bool removeRedundantLIs(MachineBasicBlock &MBB,
1218bcb0991SDimitry Andric                             const TargetRegisterInfo *TRI) {
1228bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Remove redundant load immediates from MBB:\n";
1238bcb0991SDimitry Andric                  MBB.dump(); dbgs() << "\n");
1248bcb0991SDimitry Andric 
1258bcb0991SDimitry Andric       DenseSet<MachineInstr *> InstrsToErase;
1268bcb0991SDimitry Andric       for (auto BBI = MBB.instr_begin(); BBI != MBB.instr_end(); ++BBI) {
1278bcb0991SDimitry Andric         // Skip load immediate that is marked to be erased later because it
1288bcb0991SDimitry Andric         // cannot be used to replace any other instructions.
129e8d8bef9SDimitry Andric         if (InstrsToErase.contains(&*BBI))
1308bcb0991SDimitry Andric           continue;
1318bcb0991SDimitry Andric         // Skip non-load immediate.
1328bcb0991SDimitry Andric         unsigned Opc = BBI->getOpcode();
1338bcb0991SDimitry Andric         if (Opc != PPC::LI && Opc != PPC::LI8 && Opc != PPC::LIS &&
1348bcb0991SDimitry Andric             Opc != PPC::LIS8)
1358bcb0991SDimitry Andric           continue;
1368bcb0991SDimitry Andric         // Skip load immediate, where the operand is a relocation (e.g., $r3 =
1378bcb0991SDimitry Andric         // LI target-flags(ppc-lo) %const.0).
1388bcb0991SDimitry Andric         if (!BBI->getOperand(1).isImm())
1398bcb0991SDimitry Andric           continue;
1408bcb0991SDimitry Andric         assert(BBI->getOperand(0).isReg() &&
1418bcb0991SDimitry Andric                "Expected a register for the first operand");
1428bcb0991SDimitry Andric 
1438bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << "Scanning after load immediate: "; BBI->dump(););
1448bcb0991SDimitry Andric 
1458bcb0991SDimitry Andric         Register Reg = BBI->getOperand(0).getReg();
1468bcb0991SDimitry Andric         int64_t Imm = BBI->getOperand(1).getImm();
1478bcb0991SDimitry Andric         MachineOperand *DeadOrKillToUnset = nullptr;
1488bcb0991SDimitry Andric         if (BBI->getOperand(0).isDead()) {
1498bcb0991SDimitry Andric           DeadOrKillToUnset = &BBI->getOperand(0);
1508bcb0991SDimitry Andric           LLVM_DEBUG(dbgs() << " Kill flag of " << *DeadOrKillToUnset
1518bcb0991SDimitry Andric                             << " from load immediate " << *BBI
1528bcb0991SDimitry Andric                             << " is a unsetting candidate\n");
1538bcb0991SDimitry Andric         }
1548bcb0991SDimitry Andric         // This loop scans instructions after BBI to see if there is any
1558bcb0991SDimitry Andric         // redundant load immediate.
1568bcb0991SDimitry Andric         for (auto AfterBBI = std::next(BBI); AfterBBI != MBB.instr_end();
1578bcb0991SDimitry Andric              ++AfterBBI) {
1588bcb0991SDimitry Andric           // Track the operand that kill Reg. We would unset the kill flag of
1598bcb0991SDimitry Andric           // the operand if there is a following redundant load immediate.
1608bcb0991SDimitry Andric           int KillIdx = AfterBBI->findRegisterUseOperandIdx(Reg, true, TRI);
1615ffd83dbSDimitry Andric 
1625ffd83dbSDimitry Andric           // We can't just clear implicit kills, so if we encounter one, stop
1635ffd83dbSDimitry Andric           // looking further.
1645ffd83dbSDimitry Andric           if (KillIdx != -1 && AfterBBI->getOperand(KillIdx).isImplicit()) {
1655ffd83dbSDimitry Andric             LLVM_DEBUG(dbgs()
1665ffd83dbSDimitry Andric                        << "Encountered an implicit kill, cannot proceed: ");
1675ffd83dbSDimitry Andric             LLVM_DEBUG(AfterBBI->dump());
1685ffd83dbSDimitry Andric             break;
1695ffd83dbSDimitry Andric           }
1705ffd83dbSDimitry Andric 
1718bcb0991SDimitry Andric           if (KillIdx != -1) {
1728bcb0991SDimitry Andric             assert(!DeadOrKillToUnset && "Shouldn't kill same register twice");
1738bcb0991SDimitry Andric             DeadOrKillToUnset = &AfterBBI->getOperand(KillIdx);
1748bcb0991SDimitry Andric             LLVM_DEBUG(dbgs()
1758bcb0991SDimitry Andric                        << " Kill flag of " << *DeadOrKillToUnset << " from "
1768bcb0991SDimitry Andric                        << *AfterBBI << " is a unsetting candidate\n");
1778bcb0991SDimitry Andric           }
1788bcb0991SDimitry Andric 
1798bcb0991SDimitry Andric           if (!AfterBBI->modifiesRegister(Reg, TRI))
1808bcb0991SDimitry Andric             continue;
1818bcb0991SDimitry Andric           // Finish scanning because Reg is overwritten by a non-load
1828bcb0991SDimitry Andric           // instruction.
1838bcb0991SDimitry Andric           if (AfterBBI->getOpcode() != Opc)
1848bcb0991SDimitry Andric             break;
1858bcb0991SDimitry Andric           assert(AfterBBI->getOperand(0).isReg() &&
1868bcb0991SDimitry Andric                  "Expected a register for the first operand");
1878bcb0991SDimitry Andric           // Finish scanning because Reg is overwritten by a relocation or a
1888bcb0991SDimitry Andric           // different value.
1898bcb0991SDimitry Andric           if (!AfterBBI->getOperand(1).isImm() ||
1908bcb0991SDimitry Andric               AfterBBI->getOperand(1).getImm() != Imm)
1918bcb0991SDimitry Andric             break;
1928bcb0991SDimitry Andric 
1938bcb0991SDimitry Andric           // It loads same immediate value to the same Reg, which is redundant.
1948bcb0991SDimitry Andric           // We would unset kill flag in previous Reg usage to extend live range
1958bcb0991SDimitry Andric           // of Reg first, then remove the redundancy.
1968bcb0991SDimitry Andric           if (DeadOrKillToUnset) {
1978bcb0991SDimitry Andric             LLVM_DEBUG(dbgs()
1988bcb0991SDimitry Andric                        << " Unset dead/kill flag of " << *DeadOrKillToUnset
1998bcb0991SDimitry Andric                        << " from " << *DeadOrKillToUnset->getParent());
2008bcb0991SDimitry Andric             if (DeadOrKillToUnset->isDef())
2018bcb0991SDimitry Andric               DeadOrKillToUnset->setIsDead(false);
2028bcb0991SDimitry Andric             else
2038bcb0991SDimitry Andric               DeadOrKillToUnset->setIsKill(false);
2048bcb0991SDimitry Andric           }
2058bcb0991SDimitry Andric           DeadOrKillToUnset =
2068bcb0991SDimitry Andric               AfterBBI->findRegisterDefOperand(Reg, true, true, TRI);
2078bcb0991SDimitry Andric           if (DeadOrKillToUnset)
2088bcb0991SDimitry Andric             LLVM_DEBUG(dbgs()
2098bcb0991SDimitry Andric                        << " Dead flag of " << *DeadOrKillToUnset << " from "
2108bcb0991SDimitry Andric                        << *AfterBBI << " is a unsetting candidate\n");
2118bcb0991SDimitry Andric           InstrsToErase.insert(&*AfterBBI);
2128bcb0991SDimitry Andric           LLVM_DEBUG(dbgs() << " Remove redundant load immediate: ";
2138bcb0991SDimitry Andric                      AfterBBI->dump());
2148bcb0991SDimitry Andric         }
2158bcb0991SDimitry Andric       }
2168bcb0991SDimitry Andric 
2178bcb0991SDimitry Andric       for (MachineInstr *MI : InstrsToErase) {
2188bcb0991SDimitry Andric         MI->eraseFromParent();
2198bcb0991SDimitry Andric       }
2208bcb0991SDimitry Andric       NumRemovedInPreEmit += InstrsToErase.size();
2218bcb0991SDimitry Andric       return !InstrsToErase.empty();
2228bcb0991SDimitry Andric     }
2238bcb0991SDimitry Andric 
224e8d8bef9SDimitry Andric     // Check if this instruction is a PLDpc that is part of a GOT indirect
225e8d8bef9SDimitry Andric     // access.
226e8d8bef9SDimitry Andric     bool isGOTPLDpc(MachineInstr &Instr) {
227e8d8bef9SDimitry Andric       if (Instr.getOpcode() != PPC::PLDpc)
228e8d8bef9SDimitry Andric         return false;
229e8d8bef9SDimitry Andric 
230e8d8bef9SDimitry Andric       // The result must be a register.
231e8d8bef9SDimitry Andric       const MachineOperand &LoadedAddressReg = Instr.getOperand(0);
232e8d8bef9SDimitry Andric       if (!LoadedAddressReg.isReg())
233e8d8bef9SDimitry Andric         return false;
234e8d8bef9SDimitry Andric 
235e8d8bef9SDimitry Andric       // Make sure that this is a global symbol.
236e8d8bef9SDimitry Andric       const MachineOperand &SymbolOp = Instr.getOperand(1);
237e8d8bef9SDimitry Andric       if (!SymbolOp.isGlobal())
238e8d8bef9SDimitry Andric         return false;
239e8d8bef9SDimitry Andric 
240e8d8bef9SDimitry Andric       // Finally return true only if the GOT flag is present.
241e8d8bef9SDimitry Andric       return (SymbolOp.getTargetFlags() & PPCII::MO_GOT_FLAG);
242e8d8bef9SDimitry Andric     }
243e8d8bef9SDimitry Andric 
244e8d8bef9SDimitry Andric     bool addLinkerOpt(MachineBasicBlock &MBB, const TargetRegisterInfo *TRI) {
245e8d8bef9SDimitry Andric       MachineFunction *MF = MBB.getParent();
246e8d8bef9SDimitry Andric       // If the linker opt is disabled then just return.
247e8d8bef9SDimitry Andric       if (!EnablePCRelLinkerOpt)
248e8d8bef9SDimitry Andric         return false;
249e8d8bef9SDimitry Andric 
250e8d8bef9SDimitry Andric       // Add this linker opt only if we are using PC Relative memops.
251e8d8bef9SDimitry Andric       if (!MF->getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls())
252e8d8bef9SDimitry Andric         return false;
253e8d8bef9SDimitry Andric 
254e8d8bef9SDimitry Andric       // Struct to keep track of one def/use pair for a GOT indirect access.
255e8d8bef9SDimitry Andric       struct GOTDefUsePair {
256e8d8bef9SDimitry Andric         MachineBasicBlock::iterator DefInst;
257e8d8bef9SDimitry Andric         MachineBasicBlock::iterator UseInst;
258e8d8bef9SDimitry Andric         Register DefReg;
259e8d8bef9SDimitry Andric         Register UseReg;
260e8d8bef9SDimitry Andric         bool StillValid;
261e8d8bef9SDimitry Andric       };
262e8d8bef9SDimitry Andric       // Vector of def/ues pairs in this basic block.
263e8d8bef9SDimitry Andric       SmallVector<GOTDefUsePair, 4> CandPairs;
264e8d8bef9SDimitry Andric       SmallVector<GOTDefUsePair, 4> ValidPairs;
265e8d8bef9SDimitry Andric       bool MadeChange = false;
266e8d8bef9SDimitry Andric 
267e8d8bef9SDimitry Andric       // Run through all of the instructions in the basic block and try to
268e8d8bef9SDimitry Andric       // collect potential pairs of GOT indirect access instructions.
269e8d8bef9SDimitry Andric       for (auto BBI = MBB.instr_begin(); BBI != MBB.instr_end(); ++BBI) {
270e8d8bef9SDimitry Andric         // Look for the initial GOT indirect load.
271e8d8bef9SDimitry Andric         if (isGOTPLDpc(*BBI)) {
272e8d8bef9SDimitry Andric           GOTDefUsePair CurrentPair{BBI, MachineBasicBlock::iterator(),
273e8d8bef9SDimitry Andric                                     BBI->getOperand(0).getReg(),
274e8d8bef9SDimitry Andric                                     PPC::NoRegister, true};
275e8d8bef9SDimitry Andric           CandPairs.push_back(CurrentPair);
276e8d8bef9SDimitry Andric           continue;
277e8d8bef9SDimitry Andric         }
278e8d8bef9SDimitry Andric 
279e8d8bef9SDimitry Andric         // We haven't encountered any new PLD instructions, nothing to check.
280e8d8bef9SDimitry Andric         if (CandPairs.empty())
281e8d8bef9SDimitry Andric           continue;
282e8d8bef9SDimitry Andric 
283e8d8bef9SDimitry Andric         // Run through the candidate pairs and see if any of the registers
284e8d8bef9SDimitry Andric         // defined in the PLD instructions are used by this instruction.
285e8d8bef9SDimitry Andric         // Note: the size of CandPairs can change in the loop.
286e8d8bef9SDimitry Andric         for (unsigned Idx = 0; Idx < CandPairs.size(); Idx++) {
287e8d8bef9SDimitry Andric           GOTDefUsePair &Pair = CandPairs[Idx];
288e8d8bef9SDimitry Andric           // The instruction does not use or modify this PLD's def reg,
289e8d8bef9SDimitry Andric           // ignore it.
290e8d8bef9SDimitry Andric           if (!BBI->readsRegister(Pair.DefReg, TRI) &&
291e8d8bef9SDimitry Andric               !BBI->modifiesRegister(Pair.DefReg, TRI))
292e8d8bef9SDimitry Andric             continue;
293e8d8bef9SDimitry Andric 
294e8d8bef9SDimitry Andric           // The use needs to be used in the address compuation and not
295e8d8bef9SDimitry Andric           // as the register being stored for a store.
296e8d8bef9SDimitry Andric           const MachineOperand *UseOp =
297e8d8bef9SDimitry Andric               hasPCRelativeForm(*BBI) ? &BBI->getOperand(2) : nullptr;
298e8d8bef9SDimitry Andric 
299e8d8bef9SDimitry Andric           // Check for a valid use.
300e8d8bef9SDimitry Andric           if (UseOp && UseOp->isReg() && UseOp->getReg() == Pair.DefReg &&
301e8d8bef9SDimitry Andric               UseOp->isUse() && UseOp->isKill()) {
302e8d8bef9SDimitry Andric             Pair.UseInst = BBI;
303e8d8bef9SDimitry Andric             Pair.UseReg = BBI->getOperand(0).getReg();
304e8d8bef9SDimitry Andric             ValidPairs.push_back(Pair);
305e8d8bef9SDimitry Andric           }
306e8d8bef9SDimitry Andric           CandPairs.erase(CandPairs.begin() + Idx);
307e8d8bef9SDimitry Andric         }
308e8d8bef9SDimitry Andric       }
309e8d8bef9SDimitry Andric 
310e8d8bef9SDimitry Andric       // Go through all of the pairs and check for any more valid uses.
311e8d8bef9SDimitry Andric       for (auto Pair = ValidPairs.begin(); Pair != ValidPairs.end(); Pair++) {
312e8d8bef9SDimitry Andric         // We shouldn't be here if we don't have a valid pair.
313e8d8bef9SDimitry Andric         assert(Pair->UseInst.isValid() && Pair->StillValid &&
314e8d8bef9SDimitry Andric                "Kept an invalid def/use pair for GOT PCRel opt");
315e8d8bef9SDimitry Andric         // We have found a potential pair. Search through the instructions
316e8d8bef9SDimitry Andric         // between the def and the use to see if it is valid to mark this as a
317e8d8bef9SDimitry Andric         // linker opt.
318e8d8bef9SDimitry Andric         MachineBasicBlock::iterator BBI = Pair->DefInst;
319e8d8bef9SDimitry Andric         ++BBI;
320e8d8bef9SDimitry Andric         for (; BBI != Pair->UseInst; ++BBI) {
321e8d8bef9SDimitry Andric           if (BBI->readsRegister(Pair->UseReg, TRI) ||
322e8d8bef9SDimitry Andric               BBI->modifiesRegister(Pair->UseReg, TRI)) {
323e8d8bef9SDimitry Andric             Pair->StillValid = false;
324e8d8bef9SDimitry Andric             break;
325e8d8bef9SDimitry Andric           }
326e8d8bef9SDimitry Andric         }
327e8d8bef9SDimitry Andric 
328e8d8bef9SDimitry Andric         if (!Pair->StillValid)
329e8d8bef9SDimitry Andric           continue;
330e8d8bef9SDimitry Andric 
331e8d8bef9SDimitry Andric         // The load/store instruction that uses the address from the PLD will
332e8d8bef9SDimitry Andric         // either use a register (for a store) or define a register (for the
333e8d8bef9SDimitry Andric         // load). That register will be added as an implicit def to the PLD
334e8d8bef9SDimitry Andric         // and as an implicit use on the second memory op. This is a precaution
335e8d8bef9SDimitry Andric         // to prevent future passes from using that register between the two
336e8d8bef9SDimitry Andric         // instructions.
337e8d8bef9SDimitry Andric         MachineOperand ImplDef =
338e8d8bef9SDimitry Andric             MachineOperand::CreateReg(Pair->UseReg, true, true);
339e8d8bef9SDimitry Andric         MachineOperand ImplUse =
340e8d8bef9SDimitry Andric             MachineOperand::CreateReg(Pair->UseReg, false, true);
341e8d8bef9SDimitry Andric         Pair->DefInst->addOperand(ImplDef);
342e8d8bef9SDimitry Andric         Pair->UseInst->addOperand(ImplUse);
343e8d8bef9SDimitry Andric 
344e8d8bef9SDimitry Andric         // Create the symbol.
345e8d8bef9SDimitry Andric         MCContext &Context = MF->getContext();
346e8d8bef9SDimitry Andric         MCSymbol *Symbol = Context.createNamedTempSymbol("pcrel");
347e8d8bef9SDimitry Andric         MachineOperand PCRelLabel =
348e8d8bef9SDimitry Andric             MachineOperand::CreateMCSymbol(Symbol, PPCII::MO_PCREL_OPT_FLAG);
349e8d8bef9SDimitry Andric         Pair->DefInst->addOperand(*MF, PCRelLabel);
350e8d8bef9SDimitry Andric         Pair->UseInst->addOperand(*MF, PCRelLabel);
351e8d8bef9SDimitry Andric         MadeChange |= true;
352e8d8bef9SDimitry Andric       }
353e8d8bef9SDimitry Andric       return MadeChange;
354e8d8bef9SDimitry Andric     }
355e8d8bef9SDimitry Andric 
356e8d8bef9SDimitry Andric     // This function removes redundant pairs of accumulator prime/unprime
357e8d8bef9SDimitry Andric     // instructions. In some situations, it's possible the compiler inserts an
358e8d8bef9SDimitry Andric     // accumulator prime instruction followed by an unprime instruction (e.g.
359e8d8bef9SDimitry Andric     // when we store an accumulator after restoring it from a spill). If the
360e8d8bef9SDimitry Andric     // accumulator is not used between the two, they can be removed. This
361e8d8bef9SDimitry Andric     // function removes these redundant pairs from basic blocks.
362e8d8bef9SDimitry Andric     // The algorithm is quite straightforward - every time we encounter a prime
363e8d8bef9SDimitry Andric     // instruction, the primed register is added to a candidate set. Any use
364e8d8bef9SDimitry Andric     // other than a prime removes the candidate from the set and any de-prime
365e8d8bef9SDimitry Andric     // of a current candidate marks both the prime and de-prime for removal.
366e8d8bef9SDimitry Andric     // This way we ensure we only remove prime/de-prime *pairs* with no
367e8d8bef9SDimitry Andric     // intervening uses.
368e8d8bef9SDimitry Andric     bool removeAccPrimeUnprime(MachineBasicBlock &MBB) {
369e8d8bef9SDimitry Andric       DenseSet<MachineInstr *> InstrsToErase;
370e8d8bef9SDimitry Andric       // Initially, none of the acc registers are candidates.
371e8d8bef9SDimitry Andric       SmallVector<MachineInstr *, 8> Candidates(
372e8d8bef9SDimitry Andric           PPC::UACCRCRegClass.getNumRegs(), nullptr);
373e8d8bef9SDimitry Andric 
374e8d8bef9SDimitry Andric       for (MachineInstr &BBI : MBB.instrs()) {
375e8d8bef9SDimitry Andric         unsigned Opc = BBI.getOpcode();
376e8d8bef9SDimitry Andric         // If we are visiting a xxmtacc instruction, we add it and its operand
377e8d8bef9SDimitry Andric         // register to the candidate set.
378e8d8bef9SDimitry Andric         if (Opc == PPC::XXMTACC) {
379e8d8bef9SDimitry Andric           Register Acc = BBI.getOperand(0).getReg();
380e8d8bef9SDimitry Andric           assert(PPC::ACCRCRegClass.contains(Acc) &&
381e8d8bef9SDimitry Andric                  "Unexpected register for XXMTACC");
382e8d8bef9SDimitry Andric           Candidates[Acc - PPC::ACC0] = &BBI;
383e8d8bef9SDimitry Andric         }
384e8d8bef9SDimitry Andric         // If we are visiting a xxmfacc instruction and its operand register is
385e8d8bef9SDimitry Andric         // in the candidate set, we mark the two instructions for removal.
386e8d8bef9SDimitry Andric         else if (Opc == PPC::XXMFACC) {
387e8d8bef9SDimitry Andric           Register Acc = BBI.getOperand(0).getReg();
388e8d8bef9SDimitry Andric           assert(PPC::ACCRCRegClass.contains(Acc) &&
389e8d8bef9SDimitry Andric                  "Unexpected register for XXMFACC");
390e8d8bef9SDimitry Andric           if (!Candidates[Acc - PPC::ACC0])
391e8d8bef9SDimitry Andric             continue;
392e8d8bef9SDimitry Andric           InstrsToErase.insert(&BBI);
393e8d8bef9SDimitry Andric           InstrsToErase.insert(Candidates[Acc - PPC::ACC0]);
394e8d8bef9SDimitry Andric         }
395e8d8bef9SDimitry Andric         // If we are visiting an instruction using an accumulator register
396e8d8bef9SDimitry Andric         // as operand, we remove it from the candidate set.
397e8d8bef9SDimitry Andric         else {
398e8d8bef9SDimitry Andric           for (MachineOperand &Operand : BBI.operands()) {
399e8d8bef9SDimitry Andric             if (!Operand.isReg())
400e8d8bef9SDimitry Andric               continue;
401e8d8bef9SDimitry Andric             Register Reg = Operand.getReg();
402e8d8bef9SDimitry Andric             if (PPC::ACCRCRegClass.contains(Reg))
403e8d8bef9SDimitry Andric               Candidates[Reg - PPC::ACC0] = nullptr;
404e8d8bef9SDimitry Andric           }
405e8d8bef9SDimitry Andric         }
406e8d8bef9SDimitry Andric       }
407e8d8bef9SDimitry Andric 
408e8d8bef9SDimitry Andric       for (MachineInstr *MI : InstrsToErase)
409e8d8bef9SDimitry Andric         MI->eraseFromParent();
410e8d8bef9SDimitry Andric       NumRemovedInPreEmit += InstrsToErase.size();
411e8d8bef9SDimitry Andric       return !InstrsToErase.empty();
412e8d8bef9SDimitry Andric     }
413e8d8bef9SDimitry Andric 
4140b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override {
415*81ad6265SDimitry Andric       // If the user wants to set the DSCR using command-line options,
416*81ad6265SDimitry Andric       // load in the specified value at the start of main.
417*81ad6265SDimitry Andric       if (DSCRValue.getNumOccurrences() > 0 && MF.getName().equals("main") &&
418*81ad6265SDimitry Andric           MF.getFunction().hasExternalLinkage()) {
419*81ad6265SDimitry Andric         DSCRValue = (uint32_t)(DSCRValue & 0x01FFFFFF); // 25-bit DSCR mask
420*81ad6265SDimitry Andric         RegScavenger RS;
421*81ad6265SDimitry Andric         MachineBasicBlock &MBB = MF.front();
422*81ad6265SDimitry Andric         // Find an unused GPR according to register liveness
423*81ad6265SDimitry Andric         RS.enterBasicBlock(MBB);
424*81ad6265SDimitry Andric         unsigned InDSCR = RS.FindUnusedReg(&PPC::GPRCRegClass);
425*81ad6265SDimitry Andric         if (InDSCR) {
426*81ad6265SDimitry Andric           const PPCInstrInfo *TII =
427*81ad6265SDimitry Andric               MF.getSubtarget<PPCSubtarget>().getInstrInfo();
428*81ad6265SDimitry Andric           DebugLoc dl;
429*81ad6265SDimitry Andric           MachineBasicBlock::iterator IP = MBB.begin(); // Insert Point
430*81ad6265SDimitry Andric           // Copy the 32-bit DSCRValue integer into the GPR InDSCR using LIS and
431*81ad6265SDimitry Andric           // ORI, then move to DSCR. If the requested DSCR value is contained
432*81ad6265SDimitry Andric           // in a 16-bit signed number, we can emit a single `LI`, but the
433*81ad6265SDimitry Andric           // impact of saving one instruction in one function does not warrant
434*81ad6265SDimitry Andric           // any additional complexity in the logic here.
435*81ad6265SDimitry Andric           BuildMI(MBB, IP, dl, TII->get(PPC::LIS), InDSCR)
436*81ad6265SDimitry Andric               .addImm(DSCRValue >> 16);
437*81ad6265SDimitry Andric           BuildMI(MBB, IP, dl, TII->get(PPC::ORI), InDSCR)
438*81ad6265SDimitry Andric               .addReg(InDSCR)
439*81ad6265SDimitry Andric               .addImm(DSCRValue & 0xFFFF);
440*81ad6265SDimitry Andric           BuildMI(MBB, IP, dl, TII->get(PPC::MTUDSCR))
441*81ad6265SDimitry Andric               .addReg(InDSCR, RegState::Kill);
442*81ad6265SDimitry Andric         } else
443*81ad6265SDimitry Andric           errs() << "Warning: Ran out of registers - Unable to set DSCR as "
444*81ad6265SDimitry Andric                     "requested";
445*81ad6265SDimitry Andric       }
446*81ad6265SDimitry Andric 
447480093f4SDimitry Andric       if (skipFunction(MF.getFunction()) || !RunPreEmitPeephole) {
448480093f4SDimitry Andric         // Remove UNENCODED_NOP even when this pass is disabled.
449480093f4SDimitry Andric         // This needs to be done unconditionally so we don't emit zeros
450480093f4SDimitry Andric         // in the instruction stream.
451480093f4SDimitry Andric         SmallVector<MachineInstr *, 4> InstrsToErase;
452480093f4SDimitry Andric         for (MachineBasicBlock &MBB : MF)
453480093f4SDimitry Andric           for (MachineInstr &MI : MBB)
454480093f4SDimitry Andric             if (MI.getOpcode() == PPC::UNENCODED_NOP)
455480093f4SDimitry Andric               InstrsToErase.push_back(&MI);
456480093f4SDimitry Andric         for (MachineInstr *MI : InstrsToErase)
457480093f4SDimitry Andric           MI->eraseFromParent();
4580b57cec5SDimitry Andric         return false;
459480093f4SDimitry Andric       }
4600b57cec5SDimitry Andric       bool Changed = false;
4610b57cec5SDimitry Andric       const PPCInstrInfo *TII = MF.getSubtarget<PPCSubtarget>().getInstrInfo();
4620b57cec5SDimitry Andric       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4630b57cec5SDimitry Andric       SmallVector<MachineInstr *, 4> InstrsToErase;
4640b57cec5SDimitry Andric       for (MachineBasicBlock &MBB : MF) {
4658bcb0991SDimitry Andric         Changed |= removeRedundantLIs(MBB, TRI);
466e8d8bef9SDimitry Andric         Changed |= addLinkerOpt(MBB, TRI);
467e8d8bef9SDimitry Andric         Changed |= removeAccPrimeUnprime(MBB);
4680b57cec5SDimitry Andric         for (MachineInstr &MI : MBB) {
4690b57cec5SDimitry Andric           unsigned Opc = MI.getOpcode();
470480093f4SDimitry Andric           if (Opc == PPC::UNENCODED_NOP) {
471480093f4SDimitry Andric             InstrsToErase.push_back(&MI);
472480093f4SDimitry Andric             continue;
473480093f4SDimitry Andric           }
4740b57cec5SDimitry Andric           // Detect self copies - these can result from running AADB.
4750b57cec5SDimitry Andric           if (PPCInstrInfo::isSameClassPhysRegCopy(Opc)) {
4760b57cec5SDimitry Andric             const MCInstrDesc &MCID = TII->get(Opc);
4770b57cec5SDimitry Andric             if (MCID.getNumOperands() == 3 &&
4780b57cec5SDimitry Andric                 MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
4790b57cec5SDimitry Andric                 MI.getOperand(0).getReg() == MI.getOperand(2).getReg()) {
4800b57cec5SDimitry Andric               NumberOfSelfCopies++;
4810b57cec5SDimitry Andric               LLVM_DEBUG(dbgs() << "Deleting self-copy instruction: ");
4820b57cec5SDimitry Andric               LLVM_DEBUG(MI.dump());
4830b57cec5SDimitry Andric               InstrsToErase.push_back(&MI);
4840b57cec5SDimitry Andric               continue;
4850b57cec5SDimitry Andric             }
4860b57cec5SDimitry Andric             else if (MCID.getNumOperands() == 2 &&
4870b57cec5SDimitry Andric                      MI.getOperand(0).getReg() == MI.getOperand(1).getReg()) {
4880b57cec5SDimitry Andric               NumberOfSelfCopies++;
4890b57cec5SDimitry Andric               LLVM_DEBUG(dbgs() << "Deleting self-copy instruction: ");
4900b57cec5SDimitry Andric               LLVM_DEBUG(MI.dump());
4910b57cec5SDimitry Andric               InstrsToErase.push_back(&MI);
4920b57cec5SDimitry Andric               continue;
4930b57cec5SDimitry Andric             }
4940b57cec5SDimitry Andric           }
4950b57cec5SDimitry Andric           MachineInstr *DefMIToErase = nullptr;
4960b57cec5SDimitry Andric           if (TII->convertToImmediateForm(MI, &DefMIToErase)) {
4970b57cec5SDimitry Andric             Changed = true;
4980b57cec5SDimitry Andric             NumRRConvertedInPreEmit++;
4990b57cec5SDimitry Andric             LLVM_DEBUG(dbgs() << "Converted instruction to imm form: ");
5000b57cec5SDimitry Andric             LLVM_DEBUG(MI.dump());
5010b57cec5SDimitry Andric             if (DefMIToErase) {
5020b57cec5SDimitry Andric               InstrsToErase.push_back(DefMIToErase);
5030b57cec5SDimitry Andric             }
5040b57cec5SDimitry Andric           }
505480093f4SDimitry Andric           if (TII->foldFrameOffset(MI)) {
506480093f4SDimitry Andric             Changed = true;
507480093f4SDimitry Andric             NumFrameOffFoldInPreEmit++;
508480093f4SDimitry Andric             LLVM_DEBUG(dbgs() << "Frame offset folding by using index form: ");
509480093f4SDimitry Andric             LLVM_DEBUG(MI.dump());
510480093f4SDimitry Andric           }
5110b57cec5SDimitry Andric         }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric         // Eliminate conditional branch based on a constant CR bit by
5140b57cec5SDimitry Andric         // CRSET or CRUNSET. We eliminate the conditional branch or
5150b57cec5SDimitry Andric         // convert it into an unconditional branch. Also, if the CR bit
5160b57cec5SDimitry Andric         // is not used by other instructions, we eliminate CRSET as well.
5170b57cec5SDimitry Andric         auto I = MBB.getFirstInstrTerminator();
5180b57cec5SDimitry Andric         if (I == MBB.instr_end())
5190b57cec5SDimitry Andric           continue;
5200b57cec5SDimitry Andric         MachineInstr *Br = &*I;
5210b57cec5SDimitry Andric         if (Br->getOpcode() != PPC::BC && Br->getOpcode() != PPC::BCn)
5220b57cec5SDimitry Andric           continue;
5230b57cec5SDimitry Andric         MachineInstr *CRSetMI = nullptr;
5248bcb0991SDimitry Andric         Register CRBit = Br->getOperand(0).getReg();
5250b57cec5SDimitry Andric         unsigned CRReg = getCRFromCRBit(CRBit);
5260b57cec5SDimitry Andric         bool SeenUse = false;
5270b57cec5SDimitry Andric         MachineBasicBlock::reverse_iterator It = Br, Er = MBB.rend();
5280b57cec5SDimitry Andric         for (It++; It != Er; It++) {
5290b57cec5SDimitry Andric           if (It->modifiesRegister(CRBit, TRI)) {
5300b57cec5SDimitry Andric             if ((It->getOpcode() == PPC::CRUNSET ||
5310b57cec5SDimitry Andric                  It->getOpcode() == PPC::CRSET) &&
5320b57cec5SDimitry Andric                 It->getOperand(0).getReg() == CRBit)
5330b57cec5SDimitry Andric               CRSetMI = &*It;
5340b57cec5SDimitry Andric             break;
5350b57cec5SDimitry Andric           }
5360b57cec5SDimitry Andric           if (It->readsRegister(CRBit, TRI))
5370b57cec5SDimitry Andric             SeenUse = true;
5380b57cec5SDimitry Andric         }
5390b57cec5SDimitry Andric         if (!CRSetMI) continue;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric         unsigned CRSetOp = CRSetMI->getOpcode();
5420b57cec5SDimitry Andric         if ((Br->getOpcode() == PPC::BCn && CRSetOp == PPC::CRSET) ||
5430b57cec5SDimitry Andric             (Br->getOpcode() == PPC::BC  && CRSetOp == PPC::CRUNSET)) {
5440b57cec5SDimitry Andric           // Remove this branch since it cannot be taken.
5450b57cec5SDimitry Andric           InstrsToErase.push_back(Br);
5460b57cec5SDimitry Andric           MBB.removeSuccessor(Br->getOperand(1).getMBB());
5470b57cec5SDimitry Andric         }
5480b57cec5SDimitry Andric         else {
5490b57cec5SDimitry Andric           // This conditional branch is always taken. So, remove all branches
5500b57cec5SDimitry Andric           // and insert an unconditional branch to the destination of this.
5510b57cec5SDimitry Andric           MachineBasicBlock::iterator It = Br, Er = MBB.end();
5520b57cec5SDimitry Andric           for (; It != Er; It++) {
5530b57cec5SDimitry Andric             if (It->isDebugInstr()) continue;
5540b57cec5SDimitry Andric             assert(It->isTerminator() && "Non-terminator after a terminator");
5550b57cec5SDimitry Andric             InstrsToErase.push_back(&*It);
5560b57cec5SDimitry Andric           }
5570b57cec5SDimitry Andric           if (!MBB.isLayoutSuccessor(Br->getOperand(1).getMBB())) {
5580b57cec5SDimitry Andric             ArrayRef<MachineOperand> NoCond;
5590b57cec5SDimitry Andric             TII->insertBranch(MBB, Br->getOperand(1).getMBB(), nullptr,
5600b57cec5SDimitry Andric                               NoCond, Br->getDebugLoc());
5610b57cec5SDimitry Andric           }
5620b57cec5SDimitry Andric           for (auto &Succ : MBB.successors())
5630b57cec5SDimitry Andric             if (Succ != Br->getOperand(1).getMBB()) {
5640b57cec5SDimitry Andric               MBB.removeSuccessor(Succ);
5650b57cec5SDimitry Andric               break;
5660b57cec5SDimitry Andric             }
5670b57cec5SDimitry Andric         }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric         // If the CRBit is not used by another instruction, we can eliminate
5700b57cec5SDimitry Andric         // CRSET/CRUNSET instruction.
5710b57cec5SDimitry Andric         if (!SeenUse) {
5720b57cec5SDimitry Andric           // We need to check use of the CRBit in successors.
5730b57cec5SDimitry Andric           for (auto &SuccMBB : MBB.successors())
5740b57cec5SDimitry Andric             if (SuccMBB->isLiveIn(CRBit) || SuccMBB->isLiveIn(CRReg)) {
5750b57cec5SDimitry Andric               SeenUse = true;
5760b57cec5SDimitry Andric               break;
5770b57cec5SDimitry Andric             }
5780b57cec5SDimitry Andric           if (!SeenUse)
5790b57cec5SDimitry Andric             InstrsToErase.push_back(CRSetMI);
5800b57cec5SDimitry Andric         }
5810b57cec5SDimitry Andric       }
5820b57cec5SDimitry Andric       for (MachineInstr *MI : InstrsToErase) {
5830b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "PPC pre-emit peephole: erasing instruction: ");
5840b57cec5SDimitry Andric         LLVM_DEBUG(MI->dump());
5850b57cec5SDimitry Andric         MI->eraseFromParent();
5860b57cec5SDimitry Andric         NumRemovedInPreEmit++;
5870b57cec5SDimitry Andric       }
5880b57cec5SDimitry Andric       return Changed;
5890b57cec5SDimitry Andric     }
5900b57cec5SDimitry Andric   };
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric INITIALIZE_PASS(PPCPreEmitPeephole, DEBUG_TYPE, "PowerPC Pre-Emit Peephole",
5940b57cec5SDimitry Andric                 false, false)
5950b57cec5SDimitry Andric char PPCPreEmitPeephole::ID = 0;
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric FunctionPass *llvm::createPPCPreEmitPeepholePass() {
5980b57cec5SDimitry Andric   return new PPCPreEmitPeephole();
5990b57cec5SDimitry Andric }
600