aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/Target/RISCV/RISCVPushPopOptimizer.cpp
blob: dc33ad1978ef4a57f0d68d4055ceb033cf071041 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// SPDX-License-Identifier: GPL-3.0-or-later

#include "RISCV.h"
#include "RISCVInstrInfo.h"
#include "rcc/CodeGen/InstructionDescriptor.h"
#include "rcc/CodeGen/LiveRegUnits.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineIRBuilder.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineOperand.h"
#include "rcc/CodeGen/RegisterMask.h"
#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/Target/RISCV/RISCVRegisters.h"
#include "rcc/Target/RISCV/RISCVTarget.h"

#include <cstddef>
#include <memory>
#include <optional>
#include <utility>

namespace rcc::riscv {
namespace {

struct PushPopOpcodes final {
  Opcode Pop;
  Opcode PopRet;
  Opcode PopRetZero;
};

[[nodiscard]] const MachinePassContract &pushPopContract() {
  static const MachinePassContract Contract = [] {
    MachinePassContract Value{
        .Name = "riscv-push-pop-opt",
        .Requires = {MachineFunctionProperty::NoPHIs, MachineFunctionProperty::NoVRegs,
                     MachineFunctionProperty::FrameFinalized,
                     MachineFunctionProperty::NoFrameIndices},
        .Sets = {},
        .Clears = {},
        .RequiredAnalyses = {},
        .VerificationStage = PipelineStage::PostRAFinalized,
    };
    Value.ThreadSafety = PassThreadSafety::ThreadSafe;
    Value.DeclaredChanges = {MachinePassChange::Instructions, MachinePassChange::Operands};
    return Value;
  }();
  return Contract;
}

[[nodiscard]] bool intersects(const LiveRegUnits &Left, const LiveRegUnits &Right) noexcept {
  for (const auto &[Unit, Lanes] : Left.entries())
    if (Right.intersects(Unit, Lanes))
      return true;
  return false;
}

[[nodiscard]] Expected<void> accumulateRegisterEffects(const MachineInstr &Instruction,
                                                       const TargetDescription &Target,
                                                       LiveRegUnits &Modified, LiveRegUnits &Used) {
  for (const MachineOperand &Operand : Instruction.operands()) {
    if (Operand.isDebugUse())
      continue;
    if (Operand.isRegister()) {
      const std::optional<Register> Reg = Operand.registerValue();
      if (!Reg || !Reg->isPhysical() || Reg->isNoRegister())
        continue;
      auto Units = physicalOperandUnits(Operand, Target);
      if (!Units)
        return std::unexpected(Units.error());
      for (const PhysicalUnitAccess &Access : *Units) {
        if (Operand.isDef())
          Modified.add(Access.Unit, Access.Lanes);
        if (Operand.isUse())
          Used.add(Access.Unit, Access.Lanes);
      }
      continue;
    }
    if (const auto *Mask = Operand.getIf<RegisterMaskOperand>();
        Mask != nullptr && Mask->Mask != nullptr) {
      if (auto Added = addRegisterMaskDefs(Modified, *Mask->Mask, Target); !Added)
        return std::unexpected(Added.error());
      continue;
    }
    if (const auto *Mask = Operand.getIf<LiveOutRegisterMaskOperand>();
        Mask != nullptr && Mask->Mask != nullptr) {
      if (auto Added = addRegisterMaskUses(Used, *Mask->Mask, Target); !Added)
        return std::unexpected(Added.error());
    }
  }
  return {};
}

[[nodiscard]] MachineInstr *previousNonDebug(MachineInstr &Instruction) noexcept {
  MachineInstr *Previous = Instruction.previous();
  while (Previous != nullptr && Previous->isDebugInstr())
    Previous = Previous->previous();
  return Previous;
}

[[nodiscard]] MachineInstr *firstTerminator(MachineBasicBlock &Block,
                                            const TargetDescription &Target) noexcept {
  for (MachineInstr *Instruction = Block.firstInstruction(); Instruction != nullptr;
       Instruction = Instruction->next()) {
    const InstructionDescriptor *Descriptor = Target.instructionDescriptor(Instruction->opcode());
    if (Descriptor != nullptr && Descriptor->Flags.has(InstructionFlag::Terminator))
      return Instruction;
  }
  return nullptr;
}

[[nodiscard]] Expected<bool> removeZeroReturnAssignment(MachineInstr &Pop,
                                                        const TargetDescription &Target,
                                                        PhysicalRegister ReturnRegister,
                                                        PhysicalRegister ZeroRegister) {
  const PhysicalRegisterDesc *ReturnDescription =
      Target.registers().physicalRegister(ReturnRegister);
  if (ReturnDescription == nullptr)
    return makeUnexpected(ErrorCode::VerificationError,
                          "RISC-V return register has no register-unit description");
  const LiveRegUnits ReturnUnits = physicalRegisterCoverage(*ReturnDescription);
  LiveRegUnits Modified;
  LiveRegUnits Used;
  for (MachineInstr *Instruction = previousNonDebug(Pop); Instruction != nullptr;
       Instruction = previousNonDebug(*Instruction)) {
    if (const std::optional<MachineCopyOperands> Copy = instrInfo().getCopyOperands(*Instruction)) {
      const std::optional<Register> Destination = Copy->Destination->registerValue();
      const std::optional<Register> Source = Copy->Source->registerValue();
      if (Destination && Source && Destination->physicalRegister() == ReturnRegister &&
          Source->physicalRegister() == ZeroRegister) {
        if (auto Removed = Instruction->eraseFromParent(); !Removed)
          return std::unexpected(Removed.error());
        return true;
      }
    }
    if (auto Accumulated = accumulateRegisterEffects(*Instruction, Target, Modified, Used);
        !Accumulated) {
      return std::unexpected(Accumulated.error());
    }
    if (intersects(Modified, ReturnUnits) || intersects(Used, ReturnUnits))
      return false;
  }
  return false;
}

[[nodiscard]] Expected<MachineInstr *> buildPopReturn(MachineInstr &Pop, MachineInstr &Return,
                                                      bool ReturnZero,
                                                      const PushPopOpcodes &Opcodes,
                                                      MachineFunction &Function,
                                                      const TargetDescription &Target) {
  const InstructionDescriptor *PopDescriptor = Target.instructionDescriptor(Pop.opcode());
  if (PopDescriptor == nullptr || PopDescriptor->Operands.size() != 2U)
    return makeUnexpected(ErrorCode::VerificationError,
                          "RISC-V CM_POP has an invalid instruction descriptor");
  MachineIRBuilder Builder(Function, Target);
  if (auto Point = Builder.setInsertPointBefore(Return); !Point)
    return std::unexpected(Point.error());
  auto Pending = Builder.buildInstr(ReturnZero ? Opcodes.PopRetZero : Opcodes.PopRet);
  if (!Pending)
    return std::unexpected(Pending.error());
  for (std::size_t Index = 0; Index < PopDescriptor->Operands.size(); ++Index) {
    const MachineOperand *Operand = Pop.operandAt(Index);
    if (Operand == nullptr)
      return makeUnexpected(ErrorCode::VerificationError,
                            "RISC-V CM_POP is missing an explicit operand");
    if (auto Added = Pending->addOperand(Operand->cloneDetached()); !Added)
      return std::unexpected(Added.error());
  }
  const std::size_t FirstDynamicImplicit = PopDescriptor->Operands.size() +
                                           PopDescriptor->ImplicitDefs.size() +
                                           PopDescriptor->ImplicitUses.size();
  for (std::size_t Index = FirstDynamicImplicit; Index < Pop.operandCount(); ++Index) {
    const MachineOperand *Operand = Pop.operandAt(Index);
    if (Operand == nullptr || !Operand->isImplicit()) {
      return makeUnexpected(ErrorCode::VerificationError,
                            "RISC-V CM_POP has a malformed dynamic implicit operand");
    }
    if (auto Added = Pending->addImplicitOperand(Operand->cloneDetached()); !Added)
      return std::unexpected(Added.error());
  }
  if (auto Flags = Pending->setFlags({MachineInstrFlag::FrameDestroy}); !Flags)
    return std::unexpected(Flags.error());
  if (Return.debugLocation()) {
    if (auto Location = Pending->setDebugLocation(*Return.debugLocation()); !Location)
      return std::unexpected(Location.error());
  }
  return Pending->build();
}

class RISCVPushPopOptimizationPass final : public MachineFunctionPass {
public:
  explicit RISCVPushPopOptimizationPass(const RISCVSubtarget &Subtarget) noexcept
      : Subtarget(&Subtarget) {}

  [[nodiscard]] const MachinePassContract &contract() const noexcept override {
    return pushPopContract();
  }

  [[nodiscard]] Expected<MachinePassResult> run(MachineFunction &Function,
                                                const TargetDescription &Target,
                                                MachineFunctionAnalysisManager &) override {
    MachinePassResult Result;
    if (!Subtarget->features().has(RISCVExtension::Zcmp)) {
      Result.Preserved = PreservedAnalyses::all();
      return Result;
    }

    const InstructionDescriptor *Pop = Target.instructions().descriptor("CM_POP");
    const InstructionDescriptor *PopRet = Target.instructions().descriptor("CM_POPRET");
    const InstructionDescriptor *PopRetZero = Target.instructions().descriptor("CM_POPRETZ");
    if (Pop == nullptr || PopRet == nullptr || PopRetZero == nullptr) {
      return makeUnexpected(ErrorCode::Unsupported,
                            "RISC-V Zcmp push/pop instructions are not registered");
    }
    auto ReturnRegister = physicalRegister(PhysicalRegisterID::X10);
    if (!ReturnRegister)
      return std::unexpected(ReturnRegister.error());
    auto ZeroRegister = physicalRegister(PhysicalRegisterID::X0);
    if (!ZeroRegister)
      return std::unexpected(ZeroRegister.error());
    const PushPopOpcodes Opcodes{Pop->InstructionOpcode, PopRet->InstructionOpcode,
                                 PopRetZero->InstructionOpcode};

    for (MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr;
         Block = Block->next()) {
      MachineInstr *Return = firstTerminator(*Block, Target);
      if (Return == nullptr ||
          Return->opcode() != instructionOpcode(InstructionOpcode::PseudoRET)) {
        continue;
      }
      MachineInstr *PopInstruction = previousNonDebug(*Return);
      if (PopInstruction == nullptr || PopInstruction->opcode() != Opcodes.Pop ||
          !PopInstruction->flags().has(MachineInstrFlag::FrameDestroy)) {
        continue;
      }
      auto ReturnZero =
          removeZeroReturnAssignment(*PopInstruction, Target, *ReturnRegister, *ZeroRegister);
      if (!ReturnZero)
        return std::unexpected(ReturnZero.error());
      auto NewReturn =
          buildPopReturn(*PopInstruction, *Return, *ReturnZero, Opcodes, Function, Target);
      if (!NewReturn)
        return std::unexpected(NewReturn.error());
      if (auto Removed = PopInstruction->eraseFromParent(); !Removed)
        return std::unexpected(Removed.error());
      if (auto Removed = Return->eraseFromParent(); !Removed)
        return std::unexpected(Removed.error());
      Result.Changes.add(MachinePassChange::Instructions);
      Result.Changes.add(MachinePassChange::Operands);
    }
    Result.Changed = !Result.Changes.empty();
    Result.Preserved = Result.Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
    return Result;
  }

private:
  const RISCVSubtarget *Subtarget;
};

} // namespace

std::unique_ptr<MachineFunctionPass>
createPushPopOptimizationPass(const RISCVSubtarget &Subtarget) {
  return std::make_unique<RISCVPushPopOptimizationPass>(Subtarget);
}

} // namespace rcc::riscv