@@ -45,10 +45,30 @@ char RISCVPushPopOpt::ID = 0;
45
45
INITIALIZE_PASS (RISCVPushPopOpt, " riscv-push-pop-opt" , RISCV_PUSH_POP_OPT_NAME,
46
46
false , false )
47
47
48
+ template <typename IterT>
49
+ static IterT nextNoDebugNoCFIInst(const IterT It, const IterT End) {
50
+ assert (It != End);
51
+ return std::find_if_not (std::next (It), End, [](const auto &Inst) {
52
+ return Inst.isDebugInstr () || Inst.isCFIInstruction () ||
53
+ Inst.isPseudoProbe ();
54
+ });
55
+ }
56
+
57
+ static void eraseCFIInst (const MachineBasicBlock::iterator Begin,
58
+ const MachineBasicBlock::iterator End) {
59
+ assert (Begin != End);
60
+ std::vector<std::reference_wrapper<llvm::MachineInstr>> CFIInstrs;
61
+ std::copy_if (std::next (Begin), End, std::back_inserter (CFIInstrs),
62
+ [](const auto &Inst) { return Inst.isCFIInstruction (); });
63
+
64
+ for (auto Inst : CFIInstrs)
65
+ Inst.get ().eraseFromParent ();
66
+ }
67
+
48
68
// Check if POP instruction was inserted into the MBB and return iterator to it.
49
69
static MachineBasicBlock::iterator containsPop (MachineBasicBlock &MBB) {
50
70
for (MachineBasicBlock::iterator MBBI = MBB.begin (); MBBI != MBB.end ();
51
- MBBI = next_nodbg (MBBI, MBB.end ()))
71
+ MBBI = nextNoDebugNoCFIInst (MBBI, MBB.end ()))
52
72
if (MBBI->getOpcode () == RISCV::CM_POP)
53
73
return MBBI;
54
74
@@ -76,6 +96,10 @@ bool RISCVPushPopOpt::usePopRet(MachineBasicBlock::iterator &MBBI,
76
96
for (unsigned i = FirstNonDeclaredOp; i < MBBI->getNumOperands (); ++i)
77
97
PopRetBuilder.add (MBBI->getOperand (i));
78
98
99
+ // Remove CFI instructions, they are not needed for cm.popret and cm.popretz
100
+ // anyway
101
+ eraseCFIInst (MBBI, NextI);
102
+
79
103
MBBI->eraseFromParent ();
80
104
NextI->eraseFromParent ();
81
105
return true ;
@@ -92,8 +116,8 @@ bool RISCVPushPopOpt::adjustRetVal(MachineBasicBlock::iterator &MBBI) {
92
116
// Since POP instruction is in Epilogue no normal instructions will follow
93
117
// after it. Therefore search only previous ones to find the return value.
94
118
for (MachineBasicBlock::reverse_iterator I =
95
- next_nodbg (MBBI.getReverse (), RE);
96
- I != RE; I = next_nodbg (I, RE)) {
119
+ nextNoDebugNoCFIInst (MBBI.getReverse (), RE);
120
+ I != RE; I = nextNoDebugNoCFIInst (I, RE)) {
97
121
MachineInstr &MI = *I;
98
122
if (auto OperandPair = TII->isCopyInstrImpl (MI)) {
99
123
Register DestReg = OperandPair->Destination ->getReg ();
@@ -138,7 +162,7 @@ bool RISCVPushPopOpt::runOnMachineFunction(MachineFunction &Fn) {
138
162
bool Modified = false ;
139
163
for (auto &MBB : Fn) {
140
164
MachineBasicBlock::iterator MBBI = containsPop (MBB);
141
- MachineBasicBlock::iterator NextI = next_nodbg (MBBI, MBB.end ());
165
+ MachineBasicBlock::iterator NextI = nextNoDebugNoCFIInst (MBBI, MBB.end ());
142
166
if (MBBI != MBB.end () && NextI != MBB.end () &&
143
167
NextI->getOpcode () == RISCV::PseudoRET)
144
168
Modified |= usePopRet (MBBI, NextI, adjustRetVal (MBBI));
0 commit comments