aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/CodeGen/GlobalISel/RegBankSelect.cpp
blob: 3b7932b18a283ddc9dbecd01682bc1e2fbd8ae0e (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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/CodeGen/GlobalISel/RegBankSelect.h"

#include "rcc/CodeGen/GenericOpcodes.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineIRBuilder.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineRegisterInfo.h"
#include "rcc/CodeGen/TargetDescription.h"

#include <cstdint>
#include <optional>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>

namespace rcc {
namespace {

[[nodiscard]] const MachinePassContract &bankSelectContract() {
  static const MachinePassContract Contract{
      .Name = "regbankselect",
      .Requires = {MachineFunctionProperty::Legalized},
      .Sets = {MachineFunctionProperty::RegBankSelected},
      .Clears = {},
      .RequiredAnalyses = {},
      .VerificationStage = PipelineStage::RegBankSelected,
  };
  return Contract;
}

void combineFingerprint(std::uint64_t &State, std::uint64_t Value) noexcept {
  State ^= Value + 0x9e3779b97f4a7c15ULL + (State << 6U) + (State >> 2U);
}

[[nodiscard]] std::uint64_t
registerConfigurationFingerprint(const MachineRegisterInfo &RegInfo) noexcept {
  std::uint64_t Result = 0xcbf29ce484222325ULL;
  for (const VirtualRegisterInfo &Info : RegInfo.virtualRegisters()) {
    combineFingerprint(Result, Info.IsTombstone ? 1U : 0U);
    combineFingerprint(Result, Info.Bank ? Info.Bank->value() : 0U);
    combineFingerprint(Result, Info.RegClass ? Info.RegClass->value() : 0U);
  }
  return Result;
}

[[nodiscard]] std::vector<MachineInstr *> layoutInstructions(MachineFunction &Function) {
  std::vector<MachineInstr *> Result;
  for (MachineBasicBlock *Block = Function.firstBlock(); Block != nullptr; Block = Block->next())
    for (MachineInstr *Instruction = Block->firstInstruction(); Instruction != nullptr;
         Instruction = Instruction->next())
      Result.push_back(Instruction);
  return Result;
}

[[nodiscard]] Expected<void> restoreRegisterConfiguration(
    MachineRegisterInfo &RegInfo,
    const std::vector<std::pair<Register, std::pair<std::optional<RegisterBankID>,
                                                    std::optional<RegisterClassID>>>> &Snapshot) {
  for (const auto &[Reg, Configuration] : Snapshot) {
    auto ClearBank = RegInfo.clearRegisterBank(Reg);
    if (!ClearBank)
      return std::unexpected(ClearBank.error());
    if (Configuration.first) {
      auto SetBank = RegInfo.setRegisterBank(Reg, *Configuration.first);
      if (!SetBank)
        return std::unexpected(SetBank.error());
    }
    auto ClearClass = RegInfo.clearRegisterClass(Reg);
    if (!ClearClass)
      return std::unexpected(ClearClass.error());
    if (Configuration.second) {
      auto SetClass = RegInfo.setRegisterClass(Reg, *Configuration.second);
      if (!SetClass)
        return std::unexpected(SetClass.error());
    }
  }
  return {};
}

[[nodiscard]] Error passFailure(std::string Message,
                                ErrorCode Code = ErrorCode::VerificationError) {
  return Error(Code, std::move(Message));
}

struct PlannedRegisterBank final {
  Register Reg;
  RegisterBankID Bank;
  bool IsConstrained = false;
};

struct MappingMutation final {
  MachineOperand *Operand = nullptr;
  Register Original;
  Register Fresh;
  MachineInstr *Copy = nullptr;
};

[[nodiscard]] Expected<MachineInstr *> buildBankCopy(MachineFunction &Function,
                                                     const TargetDescription &Target,
                                                     MachineInstr &Instruction, bool InsertBefore,
                                                     Register Destination, Register Source) {
  MachineIRBuilder Builder(Function, Target);
  auto Point = InsertBefore ? Builder.setInsertPointBefore(Instruction)
                            : Builder.setInsertPointAfter(Instruction);
  if (!Point)
    return std::unexpected(Point.error());
  auto Pending = Builder.buildInstr(opcode(GenericOpcode::COPY));
  if (!Pending)
    return std::unexpected(Pending.error());
  auto DestinationOperand = Pending->addDef(Destination);
  if (!DestinationOperand)
    return std::unexpected(DestinationOperand.error());
  auto SourceOperand = Pending->addUse(Source);
  if (!SourceOperand)
    return std::unexpected(SourceOperand.error());
  if (Instruction.debugLocation()) {
    auto Debug = Pending->setDebugLocation(*Instruction.debugLocation());
    if (!Debug)
      return std::unexpected(Debug.error());
  }
  return Pending->build();
}

[[nodiscard]] Expected<void> repairMappedOperand(MachineFunction &Function,
                                                 const TargetDescription &Target,
                                                 MachineInstr &Instruction, MachineOperand &Operand,
                                                 RegisterBankID RequiredBank,
                                                 std::vector<MappingMutation> &Mutations) {
  const Register *Original = Operand.getIf<Register>();
  if (Original == nullptr || !Original->isVirtual() || Operand.isDef() == Operand.isUse()) {
    return makeUnexpected(ErrorCode::VerificationError,
                          "register-bank repair requires a virtual def or use operand");
  }
  const Register OriginalReg = *Original;
  auto OriginalInfo = Function.registerInfo().virtualRegisterInfo(OriginalReg);
  if (!OriginalInfo)
    return std::unexpected(OriginalInfo.error());
  if (!OriginalInfo->get().Type) {
    return makeUnexpected(ErrorCode::VerificationError,
                          "register-bank repair requires a virtual-register type");
  }
  if (Operand.subReg().value() != 0) {
    return makeUnexpected(ErrorCode::Unsupported,
                          "register-bank repair does not support subregister operands");
  }

  auto Fresh = Function.registerInfo().createVirtualRegister(*OriginalInfo->get().Type);
  if (!Fresh)
    return std::unexpected(Fresh.error());
  auto SetBank = Function.registerInfo().setRegisterBank(*Fresh, RequiredBank);
  if (!SetBank) {
    auto Erased = Function.registerInfo().eraseVirtualRegister(*Fresh);
    (void)Erased;
    return std::unexpected(SetBank.error());
  }

  auto Copy = Operand.isDef()
                  ? buildBankCopy(Function, Target, Instruction, false, OriginalReg, *Fresh)
                  : buildBankCopy(Function, Target, Instruction, true, *Fresh, OriginalReg);
  if (!Copy) {
    auto Erased = Function.registerInfo().eraseVirtualRegister(*Fresh);
    (void)Erased;
    return std::unexpected(Copy.error());
  }
  auto Replaced = Operand.setRegister(*Fresh);
  if (!Replaced) {
    if ((*Copy)->parent() != nullptr) {
      auto Removed = (*Copy)->parent()->removeInstruction(**Copy);
      (void)Removed;
    }
    auto Erased = Function.registerInfo().eraseVirtualRegister(*Fresh);
    (void)Erased;
    return std::unexpected(Replaced.error());
  }
  Mutations.push_back(MappingMutation{
      .Operand = &Operand, .Original = OriginalReg, .Fresh = *Fresh, .Copy = *Copy});
  return {};
}

[[nodiscard]] Expected<void> rollbackMappingMutations(MachineRegisterInfo &RegInfo,
                                                      std::vector<MappingMutation> &Mutations) {
  for (auto Iterator = Mutations.rbegin(); Iterator != Mutations.rend(); ++Iterator) {
    auto Restored = Iterator->Operand->setRegister(Iterator->Original);
    if (!Restored)
      return std::unexpected(Restored.error());
    if (Iterator->Copy != nullptr && Iterator->Copy->parent() != nullptr) {
      auto Removed = Iterator->Copy->parent()->removeInstruction(*Iterator->Copy);
      if (!Removed)
        return std::unexpected(Removed.error());
    }
    auto Erased = RegInfo.eraseVirtualRegister(Iterator->Fresh);
    if (!Erased)
      return std::unexpected(Erased.error());
  }
  Mutations.clear();
  return {};
}

[[nodiscard]] Expected<void>
applyInstructionMappings(MachineFunction &Function, const TargetDescription &Target,
                         const RegisterBankInfo &Info,
                         std::unordered_set<Register> &ConstrainedRegisters,
                         std::vector<MappingMutation> &Mutations, MachinePassResult &Result) {
  MachineRegisterInfo &RegInfo = Function.registerInfo();
  const std::vector<MachineInstr *> Instructions = layoutInstructions(Function);
  for (MachineInstr *Instruction : Instructions) {
    auto Mapping = Info.getInstructionMapping(*Instruction, Function, Target);
    if (!Mapping)
      return std::unexpected(Mapping.error());
    if (Mapping->empty())
      continue;
    if (Mapping->size() != Instruction->operandCount()) {
      return makeUnexpected(ErrorCode::InternalError,
                            "target register-bank mapping has the wrong operand count");
    }
    for (std::size_t Index = 0; Index < Mapping->size(); ++Index) {
      if (!(*Mapping)[Index])
        continue;
      const RegisterBankID RequiredBank = *Mapping->at(Index);
      if (Target.registers().registerBank(RequiredBank) == nullptr) {
        return makeUnexpected(ErrorCode::InternalError,
                              "target instruction mapping names an unknown register bank");
      }
      MachineOperand *Operand = Instruction->operandAt(Index);
      const Register *Reg = Operand == nullptr ? nullptr : Operand->getIf<Register>();
      if (Reg == nullptr || !Reg->isVirtual()) {
        return makeUnexpected(ErrorCode::VerificationError,
                              "target register-bank mapping requires a virtual-register operand");
      }
      auto RegisterInfo = RegInfo.virtualRegisterInfo(*Reg);
      if (!RegisterInfo)
        return std::unexpected(RegisterInfo.error());
      if (!RegisterInfo->get().Bank) {
        auto SetBank = RegInfo.setRegisterBank(*Reg, RequiredBank);
        if (!SetBank)
          return std::unexpected(SetBank.error());
        ConstrainedRegisters.insert(*Reg);
        Result.Changed = true;
        Result.Changes.add(MachinePassChange::Registers);
        continue;
      }
      if (*RegisterInfo->get().Bank == RequiredBank) {
        ConstrainedRegisters.insert(*Reg);
        continue;
      }
      if (!ConstrainedRegisters.contains(*Reg) && !RegisterInfo->get().RegClass) {
        auto SetBank = RegInfo.setRegisterBank(*Reg, RequiredBank);
        if (!SetBank)
          return std::unexpected(SetBank.error());
        ConstrainedRegisters.insert(*Reg);
        Result.Changed = true;
        Result.Changes.add(MachinePassChange::Registers);
        continue;
      }
      auto Repaired =
          repairMappedOperand(Function, Target, *Instruction, *Operand, RequiredBank, Mutations);
      if (!Repaired)
        return std::unexpected(Repaired.error());
      ConstrainedRegisters.insert(Mutations.back().Fresh);
      Result.Changed = true;
      Result.Changes.add(MachinePassChange::Instructions);
      Result.Changes.add(MachinePassChange::Operands);
      Result.Changes.add(MachinePassChange::Registers);
    }
  }
  return {};
}

} // namespace

const MachinePassContract &RegBankSelect::contract() const noexcept {
  return bankSelectContract();
}

Expected<MachinePassResult> RegBankSelect::run(MachineFunction &Function,
                                               const TargetDescription &Target,
                                               MachineFunctionAnalysisManager &) {
  if (Function.properties().has(MachineFunctionProperty::FailedISel))
    return MachinePassResult{
        .Changed = false,
        .Changes = {},
        .Preserved = PreservedAnalyses::all(),
    };
  if (Info == nullptr)
    return std::unexpected(passFailure("register-bank select has no target behavior interface",
                                       ErrorCode::InvalidArgument));
  MachinePassResult Result;
  MachineRegisterInfo &RegInfo = Function.registerInfo();
  const std::uint64_t RegisterConfigurationBefore = registerConfigurationFingerprint(RegInfo);
  using RegisterConfiguration =
      std::pair<std::optional<RegisterBankID>, std::optional<RegisterClassID>>;
  std::vector<std::pair<Register, RegisterConfiguration>> Snapshot;
  std::vector<PlannedRegisterBank> PlannedBanks;
  std::unordered_set<Register> ConstrainedRegisters;
  for (std::size_t Index = 0; Index < RegInfo.virtualRegisters().size(); ++Index) {
    auto Reg = Register::makeVirtual(Index);
    if (!Reg)
      return std::unexpected(Reg.error());
    const VirtualRegisterInfo &StoredInfo = RegInfo.virtualRegisters()[Index];
    if (StoredInfo.IsTombstone)
      continue;
    Snapshot.emplace_back(*Reg, RegisterConfiguration{StoredInfo.Bank, StoredInfo.RegClass});
    auto InfoResult = RegInfo.virtualRegisterInfo(*Reg);
    if (!InfoResult)
      return std::unexpected(InfoResult.error());
    const VirtualRegisterInfo &InfoValue = InfoResult->get();
    const MachineInstr *Context = nullptr;
    for (const MachineOperand &Operand : RegInfo.regOperands(*Reg)) {
      Context = Operand.parent();
      if (Context != nullptr)
        break;
    }
    auto Bank = Info->selectBank(Function, *Reg, InfoValue, Context, Target);
    if (!Bank)
      return std::unexpected(Bank.error());
    if (Target.registers().registerBank(Bank->Bank) == nullptr)
      return std::unexpected(passFailure("target register-bank selector returned an unknown bank"));
    if (InfoValue.Bank && *InfoValue.Bank != Bank->Bank)
      return std::unexpected(
          passFailure("target register-bank selector conflicts with an existing bank"));
    if (InfoValue.RegClass && !Target.registers().bankCoversClass(Bank->Bank, *InfoValue.RegClass))
      return std::unexpected(
          passFailure("existing register class is not covered by selected bank"));
    PlannedBanks.push_back(PlannedRegisterBank{.Reg = *Reg,
                                               .Bank = Bank->Bank,
                                               .IsConstrained = Bank->IsConstrained ||
                                                                InfoValue.RegClass.has_value()});
  }

  for (MachineInstr *Instruction : layoutInstructions(Function)) {
    auto Validation = Info->validateInstruction(*Instruction, Function, Target);
    if (!Validation)
      return std::unexpected(
          withErrorContext(Validation.error(), "register-bank mapping precondition failed: "));
  }

  for (const PlannedRegisterBank &Plan : PlannedBanks) {
    const auto InfoResult = RegInfo.virtualRegisterInfo(Plan.Reg);
    if (!InfoResult)
      return std::unexpected(InfoResult.error());
    if (!InfoResult->get().Bank) {
      auto SetBank = RegInfo.setRegisterBank(Plan.Reg, Plan.Bank);
      if (!SetBank)
        return std::unexpected(SetBank.error());
      Result.Changed = true;
      Result.Changes.add(MachinePassChange::Registers);
    }
    if (Plan.IsConstrained)
      ConstrainedRegisters.insert(Plan.Reg);
  }

  std::vector<MappingMutation> MappingMutations;
  const auto Restore = [&]() -> Expected<void> {
    auto MappingRestore = rollbackMappingMutations(RegInfo, MappingMutations);
    if (!MappingRestore)
      return std::unexpected(MappingRestore.error());
    return restoreRegisterConfiguration(RegInfo, Snapshot);
  };
  auto Mapped = applyInstructionMappings(Function, Target, *Info, ConstrainedRegisters,
                                         MappingMutations, Result);
  if (!Mapped) {
    auto Restored = Restore();
    if (!Restored)
      return std::unexpected(withErrorContext(Restored.error(), "register-bank rollback failed: "));
    return std::unexpected(withErrorContext(Mapped.error(), "register-bank mapping failed: "));
  }
  for (MachineInstr *Instruction : layoutInstructions(Function)) {
    auto Validation = Target.validateInstruction(*Instruction, Function.registerInfo());
    if (!Validation) {
      auto Restored = Restore();
      if (!Restored)
        return std::unexpected(
            withErrorContext(Restored.error(), "register-bank rollback failed: "));
      return std::unexpected(withErrorContext(
          Validation.error(), "register-bank selection produced invalid MachineIR: "));
    }
  }
  auto RegisterValidation = Target.validateRegisterInfo(RegInfo);
  if (!RegisterValidation) {
    auto Restored = Restore();
    if (!Restored)
      return std::unexpected(withErrorContext(Restored.error(), "register-bank rollback failed: "));
    return std::unexpected(withErrorContext(
        RegisterValidation.error(), "register-bank selection produced invalid registers: "));
  }

  if (registerConfigurationFingerprint(RegInfo) != RegisterConfigurationBefore) {
    Result.Changed = true;
    Result.Changes.add(MachinePassChange::Registers);
  }

  Result.Preserved = Result.Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
  return Result;
}

} // namespace rcc