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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
|
// SPDX-License-Identifier: GPL-3.0-or-later
#include "RISCV.h"
#include "rcc/CodeGen/GenericOpcodes.h"
#include "rcc/CodeGen/MachineBasicBlock.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineFunctionRecords.h"
#include "rcc/CodeGen/MachineIRBuilder.h"
#include "rcc/CodeGen/MachineInstr.h"
#include "rcc/CodeGen/MachineOperand.h"
#include "rcc/CodeGen/MachineRegisterInfo.h"
#include "rcc/CodeGen/TargetDescription.h"
#include "rcc/Target/RISCV/RISCVInstructions.h"
#include "rcc/Target/RISCV/RISCVRegisters.h"
#include "rcc/Target/RISCV/RISCVTarget.h"
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace rcc::riscv {
namespace {
constexpr std::uint32_t PCRelativeHighFlag = 2;
constexpr std::uint32_t PCRelativeLowFlag = 4;
constexpr std::uint32_t CopyF32Flag = 8;
constexpr std::uint32_t CopyF64Flag = 16;
[[nodiscard]] std::optional<RegisterBankID>
registerBank(Register Reg, const MachineFunction &Function, const TargetDescription &Target) {
if (Reg.isVirtual()) {
auto Info = Function.registerInfo().virtualRegisterInfo(Reg);
return Info ? Info->get().Bank : std::nullopt;
}
const std::optional<PhysicalRegister> Physical = Reg.physicalRegister();
if (!Physical)
return std::nullopt;
for (const RegisterBankDesc &Bank : Target.registers().registerBanks()) {
if (Target.registers().bankContainsRegister(Bank.ID, *Physical))
return Bank.ID;
}
return std::nullopt;
}
[[nodiscard]] std::optional<LowLevelType> registerType(Register Reg,
const MachineFunction &Function) {
if (!Reg.isVirtual())
return std::nullopt;
auto Info = Function.registerInfo().virtualRegisterInfo(Reg);
return Info ? Info->get().Type : std::nullopt;
}
[[nodiscard]] Expected<void> copyLocation(const MachineInstr &Source, MachineInstr &Destination) {
if (Source.sourceLocation())
Destination.setSourceLocation(*Source.sourceLocation());
if (Source.debugLocation()) {
auto Debug = Destination.setDebugLocation(*Source.debugLocation());
if (!Debug)
return std::unexpected(Debug.error());
}
if (Source.origin())
Destination.setOrigin(*Source.origin());
return {};
}
[[nodiscard]] Expected<void> copyCommonDecoration(const MachineInstr &Source,
MachineInstr &Destination, bool CopyPreSymbol,
bool CopyPostSymbol, bool CopyDebugNumber) {
auto Location = copyLocation(Source, Destination);
if (!Location)
return std::unexpected(Location.error());
Destination.setFlags(Source.flags());
if (CopyDebugNumber && Source.debugInstrNumber() != 0) {
auto Number = Destination.setDebugInstrNumber(Source.debugInstrNumber());
if (!Number)
return std::unexpected(Number.error());
}
if (CopyPreSymbol) {
if (const auto Symbol = Source.preInstrSymbol()) {
auto Set = Destination.setPreInstrSymbol(std::string(*Symbol));
if (!Set)
return std::unexpected(Set.error());
}
}
if (CopyPostSymbol) {
if (const auto Symbol = Source.postInstrSymbol()) {
auto Set = Destination.setPostInstrSymbol(std::string(*Symbol));
if (!Set)
return std::unexpected(Set.error());
}
}
if (Source.heapAllocMarker()) {
auto Set = Destination.setHeapAllocMarker(*Source.heapAllocMarker());
if (!Set)
return std::unexpected(Set.error());
}
if (Source.pcSections()) {
auto Set = Destination.setPCSections(*Source.pcSections());
if (!Set)
return std::unexpected(Set.error());
}
if (Source.mmra()) {
auto Set = Destination.setMMRA(*Source.mmra());
if (!Set)
return std::unexpected(Set.error());
}
if (Source.cfiType()) {
auto Set = Destination.setCFIType(*Source.cfiType());
if (!Set)
return std::unexpected(Set.error());
}
if (const auto Symbol = Source.deactivationSymbol()) {
auto Set = Destination.setDeactivationSymbol(std::string(*Symbol));
if (!Set)
return std::unexpected(Set.error());
}
return {};
}
[[nodiscard]] Expected<void> removeOldInstruction(MachineInstr &Instruction) {
MachineBasicBlock *Block = Instruction.parent();
if (Block == nullptr)
return makeUnexpected(ErrorCode::InvalidArgument, "pseudo instruction is not linked");
return Block->removeInstruction(Instruction);
}
[[nodiscard]] Expected<std::pair<Register, Register>>
copyRegisters(const MachineInstr &Instruction) {
const MachineOperand *DestinationOperand = Instruction.operandAt(0);
const MachineOperand *SourceOperand = Instruction.operandAt(1);
const Register *Destination =
DestinationOperand == nullptr ? nullptr : DestinationOperand->getIf<Register>();
const Register *Source = SourceOperand == nullptr ? nullptr : SourceOperand->getIf<Register>();
if (Destination == nullptr || Source == nullptr)
return makeUnexpected(ErrorCode::VerificationError,
"post-RA copy pseudo requires two register operands");
return std::pair{*Destination, *Source};
}
[[nodiscard]] Expected<bool> prepareCopy(MachineInstr &Instruction, MachineFunction &Function,
const TargetDescription &Target) {
if (Instruction.opcode() != opcode(GenericOpcode::COPY))
return false;
auto Registers = copyRegisters(Instruction);
if (!Registers)
return std::unexpected(Registers.error());
const auto DestinationBank = registerBank(Registers->first, Function, Target);
const auto SourceBank = registerBank(Registers->second, Function, Target);
if (!DestinationBank || !SourceBank)
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V copy preparation requires constrained register banks");
if (*DestinationBank == *SourceBank)
return false;
const auto DestinationType = registerType(Registers->first, Function);
const auto SourceType = registerType(Registers->second, Function);
const std::optional<LowLevelType> Type = DestinationType ? DestinationType : SourceType;
if (!Type || Type->isVector() || (Type->scalarBitWidth() != 32 && Type->scalarBitWidth() != 64)) {
return makeUnexpected(ErrorCode::Unsupported,
"RISC-V cross-bank COPY requires a scalar 32-bit or 64-bit type");
}
if (DestinationType && SourceType &&
DestinationType->scalarBitWidth() != SourceType->scalarBitWidth()) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V cross-bank COPY has mismatched value widths");
}
const std::uint32_t Flag = Type->scalarBitWidth() == 32 ? CopyF32Flag : CopyF64Flag;
MachineOperand *DestinationOperand = Instruction.operandAt(0);
MachineOperand *SourceOperand = Instruction.operandAt(1);
const bool Changed =
DestinationOperand->targetFlags() != Flag || SourceOperand->targetFlags() != Flag;
DestinationOperand->setTargetFlags(Flag);
SourceOperand->setTargetFlags(Flag);
return Changed;
}
[[nodiscard]] Expected<bool> expandCopy(MachineInstr &Instruction, MachineFunction &Function,
const TargetDescription &Target) {
auto Registers = copyRegisters(Instruction);
if (!Registers)
return std::unexpected(Registers.error());
const Register Destination = Registers->first;
const Register Source = Registers->second;
if (!Destination.isPhysical() || !Source.isPhysical()) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V post-RA COPY retains a virtual register");
}
if (Destination == Source) {
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
const auto DestinationBank = registerBank(Destination, Function, Target);
const auto SourceBank = registerBank(Source, Function, Target);
if (!DestinationBank || !SourceBank)
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V post-RA COPY references an unknown register bank");
const RegisterBankID GPR =
RegisterBankID::fromValue(static_cast<std::uint32_t>(RegisterBank::GPR));
const RegisterBankID FPR =
RegisterBankID::fromValue(static_cast<std::uint32_t>(RegisterBank::FPR));
InstructionOpcode Selected = InstructionOpcode::Invalid;
bool DuplicateSource = false;
bool AddZeroImmediate = false;
if (*DestinationBank == GPR && *SourceBank == GPR) {
Selected = InstructionOpcode::ADDI;
AddZeroImmediate = true;
} else if (*DestinationBank == FPR && *SourceBank == FPR) {
Selected = InstructionOpcode::FSGNJ_D;
DuplicateSource = true;
} else {
const std::uint32_t DestinationFlags = Instruction.operandAt(0)->targetFlags();
const std::uint32_t SourceFlags = Instruction.operandAt(1)->targetFlags();
if (DestinationFlags != SourceFlags ||
(DestinationFlags != CopyF32Flag && DestinationFlags != CopyF64Flag)) {
return makeUnexpected(ErrorCode::PseudoExpansionFailed,
"RISC-V cross-bank COPY has no prepared transfer width");
}
if (*DestinationBank == GPR && *SourceBank == FPR) {
Selected =
DestinationFlags == CopyF32Flag ? InstructionOpcode::FMV_X_W : InstructionOpcode::FMV_X_D;
} else if (*DestinationBank == FPR && *SourceBank == GPR) {
Selected =
DestinationFlags == CopyF32Flag ? InstructionOpcode::FMV_W_X : InstructionOpcode::FMV_D_X;
}
}
if (Selected == InstructionOpcode::Invalid)
return makeUnexpected(ErrorCode::Unsupported, "RISC-V COPY crosses unsupported banks");
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
auto Pending = Builder.buildInstr(instructionOpcode(Selected));
if (!Pending)
return std::unexpected(Pending.error());
auto Def = Pending->addDef(Destination);
if (!Def)
return std::unexpected(Def.error());
auto Use = Pending->addUse(Source);
if (!Use)
return std::unexpected(Use.error());
if (DuplicateSource) {
auto SecondUse = Pending->addUse(Source);
if (!SecondUse)
return std::unexpected(SecondUse.error());
}
if (AddZeroImmediate) {
auto Immediate = Pending->addImmediate(0);
if (!Immediate)
return std::unexpected(Immediate.error());
}
auto Replacement = Pending->build();
if (!Replacement)
return std::unexpected(Replacement.error());
auto Decoration = copyCommonDecoration(Instruction, **Replacement, true, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
[[nodiscard]] Expected<bool> expandSubregisterCopy(MachineInstr &Instruction,
MachineFunction &Function,
const TargetDescription &Target) {
const Opcode Value = Instruction.opcode();
if (Value == opcode(GenericOpcode::EXTRACT_SUBREG) ||
Value == opcode(GenericOpcode::SUBREG_TO_REG)) {
const MachineOperand *Index = Instruction.operandAt(2);
const auto *Immediate = Index == nullptr ? nullptr : Index->getIf<std::int64_t>();
if (Immediate == nullptr || *Immediate != 0)
return makeUnexpected(ErrorCode::Unsupported,
"RV64GC does not support nonzero subregister indices");
} else if (Value == opcode(GenericOpcode::COPY_LANEMASK)) {
const MachineOperand *MaskOperand = Instruction.operandAt(2);
const auto *Mask = MaskOperand == nullptr ? nullptr : MaskOperand->getIf<LaneMaskOperand>();
if (Mask == nullptr || Mask->Mask.empty())
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V lane copy requires a nonempty lane mask");
} else {
return false;
}
return expandCopy(Instruction, Function, Target);
}
[[nodiscard]] Expected<void> addDirectTarget(MachineInstrBuilder &Builder,
const MachineOperand &Callee) {
if (const auto *Global = Callee.getIf<GlobalSymbolOperand>())
return Builder.addGlobalSymbol(Global->Name, Global->Offset, PCRelativeHighFlag);
if (const auto *External = Callee.getIf<ExternalSymbolOperand>())
return Builder.addExternalSymbol(External->Name, External->Offset, PCRelativeHighFlag);
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V direct call pseudo has no symbol target");
}
[[nodiscard]] bool isRegister(const MachineOperand &Operand, PhysicalRegister Reg) noexcept {
const Register *Value = Operand.getIf<Register>();
return Value != nullptr && Value->physicalRegister() == Reg;
}
[[nodiscard]] Expected<void> copyExtraImplicitOperands(
const MachineInstr &Source, std::size_t FirstImplicit, MachineInstrBuilder &Destination,
std::optional<PhysicalRegister> ExplicitDef, std::optional<PhysicalRegister> ExplicitUse) {
for (std::size_t Index = FirstImplicit; Index < Source.operandCount(); ++Index) {
const MachineOperand *Operand = Source.operandAt(Index);
if (Operand == nullptr || !Operand->isImplicit())
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V call pseudo has malformed implicit operands");
if ((ExplicitDef && Operand->isDef() && isRegister(*Operand, *ExplicitDef)) ||
(ExplicitUse && Operand->isUse() && isRegister(*Operand, *ExplicitUse))) {
continue;
}
auto Added = Destination.addImplicitOperand(Operand->cloneDetached());
if (!Added)
return std::unexpected(Added.error());
}
return {};
}
[[nodiscard]] Expected<bool> expandFFLAGSAccess(MachineInstr &Instruction,
MachineFunction &Function,
const TargetDescription &Target, bool IsRead) {
const MachineOperand *ValueOperand = Instruction.operandAt(0);
const Register *Value = ValueOperand == nullptr ? nullptr : ValueOperand->getIf<Register>();
if (Value == nullptr || !Value->isPhysical()) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V FFLAGS pseudo retains a nonphysical value register");
}
auto Zero = physicalRegister(PhysicalRegisterID::X0);
if (!Zero)
return std::unexpected(Zero.error());
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
auto Pending = Builder.buildInstr(
instructionOpcode(IsRead ? InstructionOpcode::CSRRS : InstructionOpcode::CSRRW));
if (!Pending)
return std::unexpected(Pending.error());
Expected<void> Added = IsRead ? Pending->addOperand(ValueOperand->cloneDetached())
: Pending->addDef(Register::fromPhysical(*Zero));
if (!Added)
return std::unexpected(Added.error());
Added = Pending->addImmediate(1);
if (!Added)
return std::unexpected(Added.error());
Added = IsRead ? Pending->addUse(Register::fromPhysical(*Zero))
: Pending->addOperand(ValueOperand->cloneDetached());
if (!Added)
return std::unexpected(Added.error());
auto Implicit = copyExtraImplicitOperands(Instruction, 1, *Pending, std::nullopt, std::nullopt);
if (!Implicit)
return std::unexpected(Implicit.error());
auto Replacement = Pending->build();
if (!Replacement)
return std::unexpected(Replacement.error());
auto Decoration = copyCommonDecoration(Instruction, **Replacement, true, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
[[nodiscard]] Expected<bool> expandCall(MachineInstr &Instruction, MachineFunction &Function,
const TargetDescription &Target, bool IsTail) {
MachineBasicBlock *Block = Instruction.parent();
const MachineOperand *Callee = Instruction.operandAt(0);
const MachineOperand *Mask = Instruction.operandAt(1);
if (Block == nullptr || Callee == nullptr || Mask == nullptr ||
Mask->kind() != MachineOperand::Kind::RegisterMask) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V call pseudo has malformed explicit operands");
}
auto Zero = physicalRegister(PhysicalRegisterID::X0);
auto Link = physicalRegister(PhysicalRegisterID::X1);
auto Scratch = physicalRegister(PhysicalRegisterID::X6);
if (!Zero || !Link || !Scratch)
return makeUnexpected(ErrorCode::InternalError, "RISC-V call registers are unavailable");
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
Register Base;
std::optional<std::string> Anchor;
const bool Direct = Callee->kind() == MachineOperand::Kind::GlobalSymbol ||
Callee->kind() == MachineOperand::Kind::ExternalSymbol;
if (Direct) {
const PhysicalRegister HighRegister = IsTail ? *Scratch : *Link;
Base = Register::fromPhysical(HighRegister);
Anchor = Instruction.preInstrSymbol()
? std::optional<std::string>{std::string(*Instruction.preInstrSymbol())}
: std::optional<std::string>{".Lrcc_call_" +
std::to_string(Function.stableID().value()) + "_" +
std::to_string(Instruction.stableID().value())};
auto HighPending = Builder.buildInstr(instructionOpcode(InstructionOpcode::AUIPC));
if (!HighPending)
return std::unexpected(HighPending.error());
auto HighDef = HighPending->addDef(Base);
if (!HighDef)
return std::unexpected(HighDef.error());
auto HighTarget = addDirectTarget(*HighPending, *Callee);
if (!HighTarget)
return std::unexpected(HighTarget.error());
auto High = HighPending->build();
if (!High)
return std::unexpected(High.error());
auto Symbol = (*High)->setPreInstrSymbol(*Anchor);
if (!Symbol)
return std::unexpected(Symbol.error());
auto Decoration = copyLocation(Instruction, **High);
if (!Decoration)
return std::unexpected(Decoration.error());
} else {
const Register *CalleeRegister = Callee->getIf<Register>();
if (CalleeRegister == nullptr || !CalleeRegister->isPhysical())
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V indirect call retains a virtual callee register");
Base = *CalleeRegister;
}
const InstructionOpcode LowOpcode =
IsTail ? InstructionOpcode::JALR_TAIL : InstructionOpcode::JALR_CALL;
auto LowPending = Builder.buildInstr(instructionOpcode(LowOpcode));
if (!LowPending)
return std::unexpected(LowPending.error());
const PhysicalRegister DestinationRegister = IsTail ? *Zero : *Link;
auto LowDef = LowPending->addDef(Register::fromPhysical(DestinationRegister));
if (!LowDef)
return std::unexpected(LowDef.error());
auto LowBase = LowPending->addUse(Base);
if (!LowBase)
return std::unexpected(LowBase.error());
Expected<void> LowOffset =
Anchor ? LowPending->addMCSymbol(*Anchor, 0, PCRelativeLowFlag) : LowPending->addImmediate(0);
if (!LowOffset)
return std::unexpected(LowOffset.error());
auto LowMask = LowPending->addOperand(Mask->cloneDetached());
if (!LowMask)
return std::unexpected(LowMask.error());
auto Implicit = copyExtraImplicitOperands(
Instruction, 2, *LowPending, IsTail ? std::nullopt : std::optional<PhysicalRegister>{*Link},
std::nullopt);
if (!Implicit)
return std::unexpected(Implicit.error());
auto Low = LowPending->build();
if (!Low)
return std::unexpected(Low.error());
auto Decoration = copyCommonDecoration(Instruction, **Low, !Direct, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Records =
Function.records().replaceInstructionReference(Instruction.stableID(), (*Low)->stableID());
if (!Records)
return std::unexpected(Records.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
[[nodiscard]] Expected<bool> expandReturn(MachineInstr &Instruction, MachineFunction &Function,
const TargetDescription &Target) {
auto Zero = physicalRegister(PhysicalRegisterID::X0);
auto Link = physicalRegister(PhysicalRegisterID::X1);
if (!Zero || !Link)
return makeUnexpected(ErrorCode::InternalError, "RISC-V return registers are unavailable");
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
auto Pending = Builder.buildInstr(instructionOpcode(InstructionOpcode::JALR_RET));
if (!Pending)
return std::unexpected(Pending.error());
auto Def = Pending->addDef(Register::fromPhysical(*Zero));
if (!Def)
return std::unexpected(Def.error());
auto Use = Pending->addUse(Register::fromPhysical(*Link));
if (!Use)
return std::unexpected(Use.error());
auto Immediate = Pending->addImmediate(0);
if (!Immediate)
return std::unexpected(Immediate.error());
auto Implicit = copyExtraImplicitOperands(Instruction, 0, *Pending, std::nullopt, *Link);
if (!Implicit)
return std::unexpected(Implicit.error());
auto Replacement = Pending->build();
if (!Replacement)
return std::unexpected(Replacement.error());
auto Decoration = copyCommonDecoration(Instruction, **Replacement, true, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
[[nodiscard]] Expected<bool> expandBranch(MachineInstr &Instruction, MachineFunction &Function,
const TargetDescription &Target) {
const MachineOperand *TargetOperand = Instruction.operandAt(0);
const BasicBlockOperand *TargetBlock =
TargetOperand == nullptr ? nullptr : TargetOperand->getIf<BasicBlockOperand>();
if (TargetBlock == nullptr || TargetBlock->Block == nullptr) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V PseudoBR has no basic-block target");
}
auto Zero = physicalRegister(PhysicalRegisterID::X0);
if (!Zero)
return std::unexpected(Zero.error());
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
auto Pending = Builder.buildInstr(instructionOpcode(InstructionOpcode::JAL));
if (!Pending)
return std::unexpected(Pending.error());
auto Def = Pending->addDef(Register::fromPhysical(*Zero));
if (!Def)
return std::unexpected(Def.error());
auto Destination = Pending->addBasicBlock(*TargetBlock->Block);
if (!Destination)
return std::unexpected(Destination.error());
auto Replacement = Pending->build();
if (!Replacement)
return std::unexpected(Replacement.error());
auto Decoration = copyCommonDecoration(Instruction, **Replacement, true, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
[[nodiscard]] Expected<bool> expandIndirectBranch(MachineInstr &Instruction,
MachineFunction &Function,
const TargetDescription &Target) {
const MachineOperand *Address = Instruction.operandAt(0);
const MachineOperand *Offset = Instruction.operandAt(1);
if (Address == nullptr || Address->getIf<Register>() == nullptr || Offset == nullptr ||
Offset->getIf<std::int64_t>() == nullptr) {
return makeUnexpected(ErrorCode::VerificationError,
"RISC-V PseudoBRIND has malformed operands");
}
auto Zero = physicalRegister(PhysicalRegisterID::X0);
if (!Zero)
return std::unexpected(Zero.error());
MachineIRBuilder Builder(Function, Target);
auto Point = Builder.setInsertPointBefore(Instruction);
if (!Point)
return std::unexpected(Point.error());
auto Pending = Builder.buildInstr(instructionOpcode(InstructionOpcode::JALR));
if (!Pending)
return std::unexpected(Pending.error());
auto Added = Pending->addDef(Register::fromPhysical(*Zero));
if (!Added)
return std::unexpected(Added.error());
Added = Pending->addOperand(Address->cloneDetached());
if (!Added)
return std::unexpected(Added.error());
Added = Pending->addOperand(Offset->cloneDetached());
if (!Added)
return std::unexpected(Added.error());
auto Implicit = copyExtraImplicitOperands(Instruction, 2, *Pending, std::nullopt, std::nullopt);
if (!Implicit)
return std::unexpected(Implicit.error());
auto Replacement = Pending->build();
if (!Replacement)
return std::unexpected(Replacement.error());
auto Decoration = copyCommonDecoration(Instruction, **Replacement, true, true, true);
if (!Decoration)
return std::unexpected(Decoration.error());
auto Removed = removeOldInstruction(Instruction);
if (!Removed)
return std::unexpected(Removed.error());
return true;
}
class RISCVPseudoExpansionInfo final : public TargetPseudoExpansionInfo {
public:
[[nodiscard]] Expected<bool> preparePostRAPseudo(MachineInstr &Instruction,
MachineFunction &Function,
const TargetDescription &Target) const override {
return prepareCopy(Instruction, Function, Target);
}
[[nodiscard]] Expected<bool> expandPseudo(MachineInstr &Instruction,
MachinePseudoExpansionPhase Phase,
MachineFunction &Function,
const TargetDescription &Target) const override {
if (Phase != MachinePseudoExpansionPhase::PostRA)
return false;
if (Instruction.opcode() == opcode(GenericOpcode::COPY))
return expandCopy(Instruction, Function, Target);
auto Subregister = expandSubregisterCopy(Instruction, Function, Target);
if (!Subregister || *Subregister)
return Subregister;
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::PseudoCALL))
return expandCall(Instruction, Function, Target, false);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::PseudoTAIL))
return expandCall(Instruction, Function, Target, true);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::PseudoRET))
return expandReturn(Instruction, Function, Target);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::PseudoBR))
return expandBranch(Instruction, Function, Target);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::PseudoBRIND))
return expandIndirectBranch(Instruction, Function, Target);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::ReadFFLAGS))
return expandFFLAGSAccess(Instruction, Function, Target, true);
if (Instruction.opcode() == instructionOpcode(InstructionOpcode::WriteFFLAGS))
return expandFFLAGSAccess(Instruction, Function, Target, false);
return false;
}
};
} // namespace
const TargetPseudoExpansionInfo &pseudoExpansionInfo() noexcept {
static const RISCVPseudoExpansionInfo Value;
return Value;
}
} // namespace rcc::riscv
|