1*5ffd83dbSDimitry Andric //===-- X86SpeculativeExecutionSideEffectSuppression.cpp ------------------===//
2*5ffd83dbSDimitry Andric //
3*5ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*5ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*5ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*5ffd83dbSDimitry Andric //
7*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
8*5ffd83dbSDimitry Andric /// \file
9*5ffd83dbSDimitry Andric ///
10*5ffd83dbSDimitry Andric /// This file contains the X86 implementation of the speculative execution side
11*5ffd83dbSDimitry Andric /// effect suppression mitigation.
12*5ffd83dbSDimitry Andric ///
13*5ffd83dbSDimitry Andric /// This must be used with the -mlvi-cfi flag in order to mitigate indirect
14*5ffd83dbSDimitry Andric /// branches and returns.
15*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
16*5ffd83dbSDimitry Andric 
17*5ffd83dbSDimitry Andric #include "X86.h"
18*5ffd83dbSDimitry Andric #include "X86InstrInfo.h"
19*5ffd83dbSDimitry Andric #include "X86Subtarget.h"
20*5ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h"
21*5ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
22*5ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
23*5ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
24*5ffd83dbSDimitry Andric #include "llvm/Pass.h"
25*5ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
26*5ffd83dbSDimitry Andric using namespace llvm;
27*5ffd83dbSDimitry Andric 
28*5ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-seses"
29*5ffd83dbSDimitry Andric 
30*5ffd83dbSDimitry Andric STATISTIC(NumLFENCEsInserted, "Number of lfence instructions inserted");
31*5ffd83dbSDimitry Andric 
32*5ffd83dbSDimitry Andric static cl::opt<bool> EnableSpeculativeExecutionSideEffectSuppression(
33*5ffd83dbSDimitry Andric     "x86-seses-enable-without-lvi-cfi",
34*5ffd83dbSDimitry Andric     cl::desc("Force enable speculative execution side effect suppression. "
35*5ffd83dbSDimitry Andric              "(Note: User must pass -mlvi-cfi in order to mitigate indirect "
36*5ffd83dbSDimitry Andric              "branches and returns.)"),
37*5ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
38*5ffd83dbSDimitry Andric 
39*5ffd83dbSDimitry Andric static cl::opt<bool> OneLFENCEPerBasicBlock(
40*5ffd83dbSDimitry Andric     "x86-seses-one-lfence-per-bb",
41*5ffd83dbSDimitry Andric     cl::desc(
42*5ffd83dbSDimitry Andric         "Omit all lfences other than the first to be placed in a basic block."),
43*5ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
44*5ffd83dbSDimitry Andric 
45*5ffd83dbSDimitry Andric static cl::opt<bool> OnlyLFENCENonConst(
46*5ffd83dbSDimitry Andric     "x86-seses-only-lfence-non-const",
47*5ffd83dbSDimitry Andric     cl::desc("Only lfence before groups of terminators where at least one "
48*5ffd83dbSDimitry Andric              "branch instruction has an input to the addressing mode that is a "
49*5ffd83dbSDimitry Andric              "register other than %rip."),
50*5ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
51*5ffd83dbSDimitry Andric 
52*5ffd83dbSDimitry Andric static cl::opt<bool>
53*5ffd83dbSDimitry Andric     OmitBranchLFENCEs("x86-seses-omit-branch-lfences",
54*5ffd83dbSDimitry Andric                       cl::desc("Omit all lfences before branch instructions."),
55*5ffd83dbSDimitry Andric                       cl::init(false), cl::Hidden);
56*5ffd83dbSDimitry Andric 
57*5ffd83dbSDimitry Andric namespace {
58*5ffd83dbSDimitry Andric 
59*5ffd83dbSDimitry Andric class X86SpeculativeExecutionSideEffectSuppression
60*5ffd83dbSDimitry Andric     : public MachineFunctionPass {
61*5ffd83dbSDimitry Andric public:
62*5ffd83dbSDimitry Andric   X86SpeculativeExecutionSideEffectSuppression() : MachineFunctionPass(ID) {}
63*5ffd83dbSDimitry Andric 
64*5ffd83dbSDimitry Andric   static char ID;
65*5ffd83dbSDimitry Andric   StringRef getPassName() const override {
66*5ffd83dbSDimitry Andric     return "X86 Speculative Execution Side Effect Suppression";
67*5ffd83dbSDimitry Andric   }
68*5ffd83dbSDimitry Andric 
69*5ffd83dbSDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
70*5ffd83dbSDimitry Andric };
71*5ffd83dbSDimitry Andric } // namespace
72*5ffd83dbSDimitry Andric 
73*5ffd83dbSDimitry Andric char X86SpeculativeExecutionSideEffectSuppression::ID = 0;
74*5ffd83dbSDimitry Andric 
75*5ffd83dbSDimitry Andric // This function returns whether the passed instruction uses a memory addressing
76*5ffd83dbSDimitry Andric // mode that is constant. We treat all memory addressing modes that read
77*5ffd83dbSDimitry Andric // from a register that is not %rip as non-constant. Note that the use
78*5ffd83dbSDimitry Andric // of the EFLAGS register results in an addressing mode being considered
79*5ffd83dbSDimitry Andric // non-constant, therefore all JCC instructions will return false from this
80*5ffd83dbSDimitry Andric // function since one of their operands will always be the EFLAGS register.
81*5ffd83dbSDimitry Andric static bool hasConstantAddressingMode(const MachineInstr &MI) {
82*5ffd83dbSDimitry Andric   for (const MachineOperand &MO : MI.uses())
83*5ffd83dbSDimitry Andric     if (MO.isReg() && X86::RIP != MO.getReg())
84*5ffd83dbSDimitry Andric       return false;
85*5ffd83dbSDimitry Andric   return true;
86*5ffd83dbSDimitry Andric }
87*5ffd83dbSDimitry Andric 
88*5ffd83dbSDimitry Andric bool X86SpeculativeExecutionSideEffectSuppression::runOnMachineFunction(
89*5ffd83dbSDimitry Andric     MachineFunction &MF) {
90*5ffd83dbSDimitry Andric 
91*5ffd83dbSDimitry Andric   const auto &OptLevel = MF.getTarget().getOptLevel();
92*5ffd83dbSDimitry Andric   const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
93*5ffd83dbSDimitry Andric 
94*5ffd83dbSDimitry Andric   // Check whether SESES needs to run as the fallback for LVI at O0, whether the
95*5ffd83dbSDimitry Andric   // user explicitly passed an SESES flag, or whether the SESES target feature
96*5ffd83dbSDimitry Andric   // was set.
97*5ffd83dbSDimitry Andric   if (!EnableSpeculativeExecutionSideEffectSuppression &&
98*5ffd83dbSDimitry Andric       !(Subtarget.useLVILoadHardening() && OptLevel == CodeGenOpt::None) &&
99*5ffd83dbSDimitry Andric       !Subtarget.useSpeculativeExecutionSideEffectSuppression())
100*5ffd83dbSDimitry Andric     return false;
101*5ffd83dbSDimitry Andric 
102*5ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
103*5ffd83dbSDimitry Andric                     << " **********\n");
104*5ffd83dbSDimitry Andric   bool Modified = false;
105*5ffd83dbSDimitry Andric   const X86InstrInfo *TII = Subtarget.getInstrInfo();
106*5ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : MF) {
107*5ffd83dbSDimitry Andric     MachineInstr *FirstTerminator = nullptr;
108*5ffd83dbSDimitry Andric     // Keep track of whether the previous instruction was an LFENCE to avoid
109*5ffd83dbSDimitry Andric     // adding redundant LFENCEs.
110*5ffd83dbSDimitry Andric     bool PrevInstIsLFENCE = false;
111*5ffd83dbSDimitry Andric     for (auto &MI : MBB) {
112*5ffd83dbSDimitry Andric 
113*5ffd83dbSDimitry Andric       if (MI.getOpcode() == X86::LFENCE) {
114*5ffd83dbSDimitry Andric         PrevInstIsLFENCE = true;
115*5ffd83dbSDimitry Andric         continue;
116*5ffd83dbSDimitry Andric       }
117*5ffd83dbSDimitry Andric       // We want to put an LFENCE before any instruction that
118*5ffd83dbSDimitry Andric       // may load or store. This LFENCE is intended to avoid leaking any secret
119*5ffd83dbSDimitry Andric       // data due to a given load or store. This results in closing the cache
120*5ffd83dbSDimitry Andric       // and memory timing side channels. We will treat terminators that load
121*5ffd83dbSDimitry Andric       // or store separately.
122*5ffd83dbSDimitry Andric       if (MI.mayLoadOrStore() && !MI.isTerminator()) {
123*5ffd83dbSDimitry Andric         if (!PrevInstIsLFENCE) {
124*5ffd83dbSDimitry Andric           BuildMI(MBB, MI, DebugLoc(), TII->get(X86::LFENCE));
125*5ffd83dbSDimitry Andric           NumLFENCEsInserted++;
126*5ffd83dbSDimitry Andric           Modified = true;
127*5ffd83dbSDimitry Andric         }
128*5ffd83dbSDimitry Andric         if (OneLFENCEPerBasicBlock)
129*5ffd83dbSDimitry Andric           break;
130*5ffd83dbSDimitry Andric       }
131*5ffd83dbSDimitry Andric       // The following section will be LFENCEing before groups of terminators
132*5ffd83dbSDimitry Andric       // that include branches. This will close the branch prediction side
133*5ffd83dbSDimitry Andric       // channels since we will prevent code executing after misspeculation as
134*5ffd83dbSDimitry Andric       // a result of the LFENCEs placed with this logic.
135*5ffd83dbSDimitry Andric 
136*5ffd83dbSDimitry Andric       // Keep track of the first terminator in a basic block since if we need
137*5ffd83dbSDimitry Andric       // to LFENCE the terminators in this basic block we must add the
138*5ffd83dbSDimitry Andric       // instruction before the first terminator in the basic block (as
139*5ffd83dbSDimitry Andric       // opposed to before the terminator that indicates an LFENCE is
140*5ffd83dbSDimitry Andric       // required). An example of why this is necessary is that the
141*5ffd83dbSDimitry Andric       // X86InstrInfo::analyzeBranch method assumes all terminators are grouped
142*5ffd83dbSDimitry Andric       // together and terminates it's analysis once the first non-termintor
143*5ffd83dbSDimitry Andric       // instruction is found.
144*5ffd83dbSDimitry Andric       if (MI.isTerminator() && FirstTerminator == nullptr)
145*5ffd83dbSDimitry Andric         FirstTerminator = &MI;
146*5ffd83dbSDimitry Andric 
147*5ffd83dbSDimitry Andric       // Look for branch instructions that will require an LFENCE to be put
148*5ffd83dbSDimitry Andric       // before this basic block's terminators.
149*5ffd83dbSDimitry Andric       if (!MI.isBranch() || OmitBranchLFENCEs) {
150*5ffd83dbSDimitry Andric         // This isn't a branch or we're not putting LFENCEs before branches.
151*5ffd83dbSDimitry Andric         PrevInstIsLFENCE = false;
152*5ffd83dbSDimitry Andric         continue;
153*5ffd83dbSDimitry Andric       }
154*5ffd83dbSDimitry Andric 
155*5ffd83dbSDimitry Andric       if (OnlyLFENCENonConst && hasConstantAddressingMode(MI)) {
156*5ffd83dbSDimitry Andric         // This is a branch, but it only has constant addressing mode and we're
157*5ffd83dbSDimitry Andric         // not adding LFENCEs before such branches.
158*5ffd83dbSDimitry Andric         PrevInstIsLFENCE = false;
159*5ffd83dbSDimitry Andric         continue;
160*5ffd83dbSDimitry Andric       }
161*5ffd83dbSDimitry Andric 
162*5ffd83dbSDimitry Andric       // This branch requires adding an LFENCE.
163*5ffd83dbSDimitry Andric       if (!PrevInstIsLFENCE) {
164*5ffd83dbSDimitry Andric         BuildMI(MBB, FirstTerminator, DebugLoc(), TII->get(X86::LFENCE));
165*5ffd83dbSDimitry Andric         NumLFENCEsInserted++;
166*5ffd83dbSDimitry Andric         Modified = true;
167*5ffd83dbSDimitry Andric       }
168*5ffd83dbSDimitry Andric       break;
169*5ffd83dbSDimitry Andric     }
170*5ffd83dbSDimitry Andric   }
171*5ffd83dbSDimitry Andric 
172*5ffd83dbSDimitry Andric   return Modified;
173*5ffd83dbSDimitry Andric }
174*5ffd83dbSDimitry Andric 
175*5ffd83dbSDimitry Andric FunctionPass *llvm::createX86SpeculativeExecutionSideEffectSuppression() {
176*5ffd83dbSDimitry Andric   return new X86SpeculativeExecutionSideEffectSuppression();
177*5ffd83dbSDimitry Andric }
178*5ffd83dbSDimitry Andric 
179*5ffd83dbSDimitry Andric INITIALIZE_PASS(X86SpeculativeExecutionSideEffectSuppression, "x86-seses",
180*5ffd83dbSDimitry Andric                 "X86 Speculative Execution Side Effect Suppression", false,
181*5ffd83dbSDimitry Andric                 false)
182