115#define DEBUG_TYPE "aarch64-speculation-hardening"
117#define AARCH64_SPECULATION_HARDENING_NAME "AArch64 speculation hardening pass"
120 cl::desc(
"Sanitize loads from memory."),
143 unsigned MisspeculatingTaintReg;
144 unsigned MisspeculatingTaintReg32Bit;
145 bool UseControlFlowSpeculationBarrier;
151 bool &UsesFullSpeculationBarrier);
161 unsigned TmpReg)
const;
171 bool UsesFullSpeculationBarrier);
174 bool UsesFullSpeculationBarrier);
181char AArch64SpeculationHardening::ID = 0;
186bool AArch64SpeculationHardening::endsWithCondControlFlow(
188 AArch64CC::CondCode &CondCode)
const {
194 if (analyzeBranchCondCode.
empty())
212 assert(analyzeBranchCondCode.
size() == 1 &&
"unknown Cond array format");
217void AArch64SpeculationHardening::insertFullSpeculationBarrier(
225void AArch64SpeculationHardening::insertTrackingCode(
228 if (UseControlFlowSpeculationBarrier) {
229 insertFullSpeculationBarrier(SplitEdgeBB, SplitEdgeBB.
begin(),
DL);
232 .
addDef(MisspeculatingTaintReg)
233 .
addUse(MisspeculatingTaintReg)
240bool AArch64SpeculationHardening::instrumentControlFlow(
249 if (!endsWithCondControlFlow(
MBB,
TBB, FBB, CondCode)) {
261 assert(SplitEdgeTBB !=
nullptr);
262 assert(SplitEdgeFBB !=
nullptr);
268 insertTrackingCode(*SplitEdgeTBB, CondCode,
DL);
269 insertTrackingCode(*SplitEdgeFBB, InvCondCode,
DL);
286 bool TmpRegisterNotAvailableEverywhere =
false;
293 if (!
MI.isReturn() && !
MI.isCall())
311 << ((TmpReg == 0) ?
"no register " :
"register ");
313 dbgs() <<
"to be available at MI " <<
MI);
315 TmpRegisterNotAvailableEverywhere =
true;
318 else if (
MI.isCall())
322 if (TmpRegisterNotAvailableEverywhere) {
329 UsesFullSpeculationBarrier =
true;
332 for (
auto MI_Reg : ReturnInstructions) {
333 assert(MI_Reg.second != 0);
336 <<
" About to insert Reg to SP taint propagation with temp register "
338 <<
" on instruction: " << *MI_Reg.first);
339 insertRegToSPTaintPropagation(
MBB, MI_Reg.first, MI_Reg.second);
343 for (
auto MI_Reg : CallInstructions) {
344 assert(MI_Reg.second != 0);
346 "propagation with temp register "
348 <<
" around instruction: " << *MI_Reg.first);
350 insertSPToRegTaintPropagation(
353 insertRegToSPTaintPropagation(
MBB, MI_Reg.first, MI_Reg.second);
360void AArch64SpeculationHardening::insertSPToRegTaintPropagation(
365 if (UseControlFlowSpeculationBarrier) {
378 .
addDef(MisspeculatingTaintReg)
384void AArch64SpeculationHardening::insertRegToSPTaintPropagation(
386 unsigned TmpReg)
const {
390 if (UseControlFlowSpeculationBarrier)
413bool AArch64SpeculationHardening::functionUsesHardeningRegister(
421 if (
MI.readsRegister(MisspeculatingTaintReg,
TRI) ||
422 MI.modifiesRegister(MisspeculatingTaintReg,
TRI))
432bool AArch64SpeculationHardening::makeGPRSpeculationSafe(
436 AArch64::GPR64allRegClass.
contains(Reg));
443 if (Reg == AArch64::SP || Reg == AArch64::WSP)
447 if (RegsAlreadyMasked[Reg])
450 const bool Is64Bit = AArch64::GPR64allRegClass.contains(Reg);
451 LLVM_DEBUG(
dbgs() <<
"About to harden register : " << Reg <<
"\n");
453 TII->get(Is64Bit ? AArch64::SpeculationSafeValueX
454 : AArch64::SpeculationSafeValueW))
457 RegsAlreadyMasked.set(Reg);
466 RegsAlreadyMasked.reset();
470 for (;
MBBI != E;
MBBI = NextMBBI) {
472 NextMBBI = std::next(
MBBI);
487 return Op.isReg() && (AArch64::GPR32allRegClass.contains(Op.getReg()) ||
488 AArch64::GPR64allRegClass.contains(Op.getReg()));
494 bool HardenLoadedData = AllDefsAreGPR;
495 bool HardenAddressLoadedFrom = !HardenLoadedData;
502 RegsAlreadyMasked.reset(*AI);
510 if (HardenLoadedData)
511 for (
auto Def :
MI.defs()) {
523 if (HardenAddressLoadedFrom)
524 for (
auto Use :
MI.uses()) {
538 if (!(AArch64::GPR32allRegClass.
contains(Reg) ||
539 AArch64::GPR64allRegClass.
contains(Reg)))
549bool AArch64SpeculationHardening::expandSpeculationSafeValue(
551 bool UsesFullSpeculationBarrier) {
553 unsigned Opcode =
MI.getOpcode();
559 case AArch64::SpeculationSafeValueW:
562 case AArch64::SpeculationSafeValueX:
566 if (!UseControlFlowSpeculationBarrier && !UsesFullSpeculationBarrier) {
574 RegsNeedingCSDBBeforeUse.set(*AI);
578 Is64Bit ?
TII->get(AArch64::ANDXrs) :
TII->get(AArch64::ANDWrs))
581 .
addUse(Is64Bit ? MisspeculatingTaintReg
582 : MisspeculatingTaintReg32Bit)
585 MI.eraseFromParent();
594 assert(!UseControlFlowSpeculationBarrier &&
"No need to insert CSDBs when "
595 "control flow miss-speculation "
596 "is already blocked");
599 RegsNeedingCSDBBeforeUse.reset();
603bool AArch64SpeculationHardening::lowerSpeculationSafeValuePseudos(
607 RegsNeedingCSDBBeforeUse.reset();
623 DL =
MI.getDebugLoc();
629 bool NeedToEmitBarrier =
false;
630 if (RegsNeedingCSDBBeforeUse.any() && (
MI.isCall() ||
MI.isTerminator()))
631 NeedToEmitBarrier =
true;
632 if (!NeedToEmitBarrier)
634 if (
Op.isReg() && RegsNeedingCSDBBeforeUse[
Op.getReg()]) {
635 NeedToEmitBarrier =
true;
639 if (NeedToEmitBarrier && !UsesFullSpeculationBarrier)
643 expandSpeculationSafeValue(
MBB,
MBBI, UsesFullSpeculationBarrier);
648 if (RegsNeedingCSDBBeforeUse.any() && !UsesFullSpeculationBarrier)
654bool AArch64SpeculationHardening::runOnMachineFunction(
MachineFunction &MF) {
658 MisspeculatingTaintReg = AArch64::X16;
659 MisspeculatingTaintReg32Bit = AArch64::W16;
662 RegsNeedingCSDBBeforeUse.resize(
TRI->getNumRegs());
663 RegsAlreadyMasked.resize(
TRI->getNumRegs());
664 UseControlFlowSpeculationBarrier = functionUsesHardeningRegister(MF);
671 dbgs() <<
"***** AArch64SpeculationHardening - automatic insertion of "
672 "SpeculationSafeValue intrinsics *****\n");
680 <<
"***** AArch64SpeculationHardening - track control flow *****\n");
685 EntryBlocks.
push_back(LPI.LandingPadBlock);
686 for (
auto *Entry : EntryBlocks)
687 insertSPToRegTaintPropagation(
688 *Entry,
Entry->SkipPHIsLabelsAndDebug(
Entry->begin()));
691 for (
auto &
MBB : MF) {
692 bool UsesFullSpeculationBarrier =
false;
693 Modified |= instrumentControlFlow(
MBB, UsesFullSpeculationBarrier);
695 lowerSpeculationSafeValuePseudos(
MBB, UsesFullSpeculationBarrier);
703 return new AArch64SpeculationHardening();
#define AARCH64_SPECULATION_HARDENING_NAME
static cl::opt< bool > HardenLoads("aarch64-slh-loads", cl::Hidden, cl::desc("Sanitize loads from memory."), cl::init(true))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file implements the BitVector class.
const HexagonInstrInfo * TII
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
This class represents an Operation in the Expression.
FunctionPass class - This class is used to implement most global optimizations.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
MCRegAliasIterator enumerates all registers aliasing Reg.
instr_iterator instr_begin()
MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
unsigned succ_size() const
instr_iterator instr_end()
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, std::vector< SparseBitVector<> > *LiveInSets=nullptr)
Split the critical edge from this block to the given successor block, and return the newly created bl...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
Register FindUnusedReg(const TargetRegisterClass *RC) const
Find an unused register of the specified register class.
void backward()
Update internal register state and move MBB iterator backwards.
void enterBasicBlock(MachineBasicBlock &MBB)
Start tracking liveness from the begin of basic block MBB.
Wrapper class representing virtual and physical registers.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
A Use represents the edge between a Value definition and its users.
static CondCode getInvertedCondCode(CondCode Code)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
@ Renamable
Register that may be renamed.
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void initializeAArch64SpeculationHardeningPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionPass * createAArch64SpeculationHardeningPass()
Returns an instance of the pseudo instruction expansion pass.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This structure is used to retain landing pad info for the current function.