1//===----- X86AvoidTrailingCall.cpp - Insert int3 after trailing calls ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The Windows x64 unwinder decodes the instruction stream during unwinding.
10// The unwinder decodes forward from the current PC to detect epilogue code
11// patterns.
12//
13// First, this means that there must be an instruction after every
14// call instruction for the unwinder to decode. LLVM must maintain the invariant
15// that the last instruction of a function or funclet is not a call, or the
16// unwinder may decode into the next function. Similarly, a call may not
17// immediately precede an epilogue code pattern. As of this writing, the
18// SEH_Epilogue pseudo instruction takes care of that.
19//
20// Second, all non-tail call jump targets must be within the *half-open*
21// interval of the bounds of the function. The unwinder distinguishes between
22// internal jump instructions and tail calls in an epilogue sequence by checking
23// the jump target against the function bounds from the .pdata section. This
24// means that the last regular MBB of an LLVM function must not be empty if
25// there are regular jumps targeting it.
26//
27// This pass upholds these invariants by ensuring that blocks at the end of a
28// function or funclet are a) not empty and b) do not end in a CALL instruction.
29//
30// Unwinder implementation for reference:
31// https://github.com/dotnet/coreclr/blob/a9f3fc16483eecfc47fb79c362811d870be02249/src/unwinder/amd64/unwinder_amd64.cpp#L1015
32//
33//===----------------------------------------------------------------------===//
34
35#include "X86.h"
36#include "X86InstrInfo.h"
37#include "X86Subtarget.h"
38#include "llvm/CodeGen/MachineFunctionPass.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/IR/Analysis.h"
41
42#define AVOIDCALL_DESC "X86 avoid trailing call pass"
43#define AVOIDCALL_NAME "x86-avoid-trailing-call"
44
45#define DEBUG_TYPE AVOIDCALL_NAME
46
47using namespace llvm;
48
49namespace {
50class X86AvoidTrailingCallLegacyPass : public MachineFunctionPass {
51public:
52 X86AvoidTrailingCallLegacyPass() : MachineFunctionPass(ID) {}
53
54 bool runOnMachineFunction(MachineFunction &MF) override;
55
56 static char ID;
57
58private:
59 StringRef getPassName() const override { return AVOIDCALL_DESC; }
60};
61} // end anonymous namespace
62
63char X86AvoidTrailingCallLegacyPass::ID = 0;
64
65FunctionPass *llvm::createX86AvoidTrailingCallLegacyPass() {
66 return new X86AvoidTrailingCallLegacyPass();
67}
68
69INITIALIZE_PASS(X86AvoidTrailingCallLegacyPass, AVOIDCALL_NAME, AVOIDCALL_DESC,
70 false, false)
71
72// A real instruction is a non-meta, non-pseudo instruction. Some pseudos
73// expand to nothing, and some expand to code. This logic conservatively assumes
74// they might expand to nothing.
75static bool isCallOrRealInstruction(MachineInstr &MI) {
76 return MI.isCall() || (!MI.isPseudo() && !MI.isMetaInstruction());
77}
78
79// Return true if this is a call instruction, but not a tail call.
80static bool isCallInstruction(const MachineInstr &MI) {
81 return MI.isCall() && !MI.isReturn();
82}
83
84bool UpdatedOnX86AvoidTrailingCallPass(MachineFunction &MF) {
85 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
86 const X86InstrInfo &TII = *STI.getInstrInfo();
87 assert(STI.isTargetWin64() && "pass only runs on Win64");
88
89 // We don't need to worry about any of the invariants described above if there
90 // is no unwind info (CFI).
91 if (!MF.hasWinCFI())
92 return false;
93
94 // FIXME: Perhaps this pass should also replace SEH_Epilogue by inserting nops
95 // before epilogues.
96
97 bool Changed = false;
98 for (MachineBasicBlock &MBB : MF) {
99 // Look for basic blocks that precede funclet entries or are at the end of
100 // the function.
101 MachineBasicBlock *NextMBB = MBB.getNextNode();
102 if (NextMBB && !NextMBB->isEHFuncletEntry())
103 continue;
104
105 // Find the last real instruction in this block.
106 auto LastRealInstr = llvm::find_if(Range: reverse(C&: MBB), P: isCallOrRealInstruction);
107
108 // If the block is empty or the last real instruction is a call instruction,
109 // insert an int3. If there is a call instruction, insert the int3 between
110 // the call and any labels or other meta instructions. If the block is
111 // empty, insert at block end.
112 bool IsEmpty = LastRealInstr == MBB.rend();
113 bool IsCall = !IsEmpty && isCallInstruction(MI: *LastRealInstr);
114 if (IsEmpty || IsCall) {
115 LLVM_DEBUG({
116 if (IsCall) {
117 dbgs() << "inserting int3 after trailing call instruction:\n";
118 LastRealInstr->dump();
119 dbgs() << '\n';
120 } else {
121 dbgs() << "inserting int3 in trailing empty MBB:\n";
122 MBB.dump();
123 }
124 });
125
126 MachineBasicBlock::iterator MBBI = MBB.end();
127 DebugLoc DL;
128 if (IsCall) {
129 MBBI = std::next(x: LastRealInstr.getReverse());
130 DL = LastRealInstr->getDebugLoc();
131 }
132 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::INT3));
133 Changed = true;
134 }
135 }
136
137 return Changed;
138}
139
140bool X86AvoidTrailingCallLegacyPass::runOnMachineFunction(MachineFunction &MF) {
141 return UpdatedOnX86AvoidTrailingCallPass(MF);
142}
143
144PreservedAnalyses
145X86AvoidTrailingCallPass::run(MachineFunction &MF,
146 MachineFunctionAnalysisManager &MFAM) {
147 bool Changed = UpdatedOnX86AvoidTrailingCallPass(MF);
148 if (!Changed)
149 return PreservedAnalyses::all();
150
151 return getMachineFunctionPassPreservedAnalyses().preserveSet<CFGAnalyses>();
152}
153