LLVM 24.0.0git
X86SpeculativeExecutionSideEffectSuppression.cpp
Go to the documentation of this file.
1//===-- X86SpeculativeExecutionSideEffectSuppression.cpp ------------------===//
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/// \file
9///
10/// This file contains the X86 implementation of the speculative execution side
11/// effect suppression mitigation.
12///
13/// This must be used with the -mlvi-cfi flag in order to mitigate indirect
14/// branches and returns.
15//===----------------------------------------------------------------------===//
16
17#include "X86.h"
18#include "X86InstrInfo.h"
19#include "X86Subtarget.h"
20#include "llvm/ADT/Statistic.h"
24#include "llvm/Pass.h"
26using namespace llvm;
27
28#define DEBUG_TYPE "x86-seses"
29
30STATISTIC(NumLFENCEsInserted, "Number of lfence instructions inserted");
31
32namespace {
33
34constexpr StringRef X86SESESPassName =
35 "X86 Speculative Execution Side Effect Suppression";
36
37class X86SpeculativeExecutionSideEffectSuppressionLegacy
38 : public MachineFunctionPass {
39public:
40 X86SpeculativeExecutionSideEffectSuppressionLegacy()
41 : MachineFunctionPass(ID) {}
42
43 static char ID;
44 StringRef getPassName() const override { return X86SESESPassName; }
45
46 bool runOnMachineFunction(MachineFunction &MF) override;
47};
48} // namespace
49
50char X86SpeculativeExecutionSideEffectSuppressionLegacy::ID = 0;
51
52// This function returns whether the passed instruction uses a memory addressing
53// mode that is constant. We treat all memory addressing modes that read
54// from a register that is not %rip as non-constant. Note that the use
55// of the EFLAGS register results in an addressing mode being considered
56// non-constant, therefore all JCC instructions will return false from this
57// function since one of their operands will always be the EFLAGS register.
59 for (const MachineOperand &MO : MI.uses())
60 if (MO.isReg() && X86::RIP != MO.getReg())
61 return false;
62 return true;
63}
64
65static bool
67
68 const auto &OptLevel = MF.getTarget().getOptLevel();
69 const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
70 const X86Options &CLOpts = Subtarget.getCLOpts();
71
72 // Check whether SESES needs to run as the fallback for LVI at O0, whether the
73 // user explicitly passed an SESES flag, or whether the SESES target feature
74 // was set.
75 if (!CLOpts.seses_enable_without_lvi_cfi &&
76 !(Subtarget.useLVILoadHardening() && OptLevel == CodeGenOptLevel::None) &&
77 !Subtarget.useSpeculativeExecutionSideEffectSuppression())
78 return false;
79
80 LLVM_DEBUG(dbgs() << "********** " << X86SESESPassName << " : "
81 << MF.getName() << " **********\n");
82 bool Modified = false;
83 const X86InstrInfo *TII = Subtarget.getInstrInfo();
84 for (MachineBasicBlock &MBB : MF) {
85 MachineInstr *FirstTerminator = nullptr;
86 // Keep track of whether the previous instruction was an LFENCE to avoid
87 // adding redundant LFENCEs.
88 bool PrevInstIsLFENCE = false;
89 for (auto &MI : MBB) {
90
91 if (MI.getOpcode() == X86::LFENCE) {
92 PrevInstIsLFENCE = true;
93 continue;
94 }
95 // We want to put an LFENCE before any instruction that
96 // may load or store. This LFENCE is intended to avoid leaking any secret
97 // data due to a given load or store. This results in closing the cache
98 // and memory timing side channels. We will treat terminators that load
99 // or store separately.
100 if (MI.mayLoadOrStore() && !MI.isTerminator()) {
101 if (!PrevInstIsLFENCE) {
102 BuildMI(MBB, MI, DebugLoc(), TII->get(X86::LFENCE));
103 NumLFENCEsInserted++;
104 Modified = true;
105 }
106 if (CLOpts.seses_one_lfence_per_bb)
107 break;
108 }
109 // The following section will be LFENCEing before groups of terminators
110 // that include branches. This will close the branch prediction side
111 // channels since we will prevent code executing after misspeculation as
112 // a result of the LFENCEs placed with this logic.
113
114 // Keep track of the first terminator in a basic block since if we need
115 // to LFENCE the terminators in this basic block we must add the
116 // instruction before the first terminator in the basic block (as
117 // opposed to before the terminator that indicates an LFENCE is
118 // required). An example of why this is necessary is that the
119 // X86InstrInfo::analyzeBranch method assumes all terminators are grouped
120 // together and terminates it's analysis once the first non-termintor
121 // instruction is found.
122 if (MI.isTerminator() && FirstTerminator == nullptr)
123 FirstTerminator = &MI;
124
125 // Look for branch instructions that will require an LFENCE to be put
126 // before this basic block's terminators.
127 if (!MI.isBranch() || CLOpts.seses_omit_branch_lfences) {
128 // This isn't a branch or we're not putting LFENCEs before branches.
129 PrevInstIsLFENCE = false;
130 continue;
131 }
132
133 if (CLOpts.seses_only_lfence_non_const && hasConstantAddressingMode(MI)) {
134 // This is a branch, but it only has constant addressing mode and we're
135 // not adding LFENCEs before such branches.
136 PrevInstIsLFENCE = false;
137 continue;
138 }
139
140 // This branch requires adding an LFENCE.
141 if (!PrevInstIsLFENCE) {
142 assert(FirstTerminator && "Unknown terminator instruction");
143 BuildMI(MBB, FirstTerminator, DebugLoc(), TII->get(X86::LFENCE));
144 NumLFENCEsInserted++;
145 Modified = true;
146 }
147 break;
148 }
149 }
150
151 return Modified;
152}
153
154bool X86SpeculativeExecutionSideEffectSuppressionLegacy::runOnMachineFunction(
155 MachineFunction &MF) {
157}
158
166
169 return new X86SpeculativeExecutionSideEffectSuppressionLegacy();
170}
171
172INITIALIZE_PASS(X86SpeculativeExecutionSideEffectSuppressionLegacy, "x86-seses",
173 "X86 Speculative Execution Side Effect Suppression", false,
174 false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool runX86SpeculativeExecutionSideEffectSuppression(MachineFunction &MF)
static bool hasConstantAddressingMode(const MachineInstr &MI)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
const X86Options & getCLOpts() const
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
FunctionPass * createX86SpeculativeExecutionSideEffectSuppressionLegacyPass()
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209