mirror of
https://github.com/RPCS3/llvm.git
synced 2026-01-31 01:25:19 +01:00
Summary: First, we need to explain the core of the vulnerability. Note that this is a very incomplete description, please see the Project Zero blog post for details: https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html The basis for branch target injection is to direct speculative execution of the processor to some "gadget" of executable code by poisoning the prediction of indirect branches with the address of that gadget. The gadget in turn contains an operation that provides a side channel for reading data. Most commonly, this will look like a load of secret data followed by a branch on the loaded value and then a load of some predictable cache line. The attacker then uses timing of the processors cache to determine which direction the branch took *in the speculative execution*, and in turn what one bit of the loaded value was. Due to the nature of these timing side channels and the branch predictor on Intel processors, this allows an attacker to leak data only accessible to a privileged domain (like the kernel) back into an unprivileged domain. The goal is simple: avoid generating code which contains an indirect branch that could have its prediction poisoned by an attacker. In many cases, the compiler can simply use directed conditional branches and a small search tree. LLVM already has support for lowering switches in this way and the first step of this patch is to disable jump-table lowering of switches and introduce a pass to rewrite explicit indirectbr sequences into a switch over integers. However, there is no fully general alternative to indirect calls. We introduce a new construct we call a "retpoline" to implement indirect calls in a non-speculatable way. It can be thought of loosely as a trampoline for indirect calls which uses the RET instruction on x86. Further, we arrange for a specific call->ret sequence which ensures the processor predicts the return to go to a controlled, known location. The retpoline then "smashes" the return address pushed onto the stack by the call with the desired target of the original indirect call. The result is a predicted return to the next instruction after a call (which can be used to trap speculative execution within an infinite loop) and an actual indirect branch to an arbitrary address. On 64-bit x86 ABIs, this is especially easily done in the compiler by using a guaranteed scratch register to pass the target into this device. For 32-bit ABIs there isn't a guaranteed scratch register and so several different retpoline variants are introduced to use a scratch register if one is available in the calling convention and to otherwise use direct stack push/pop sequences to pass the target address. This "retpoline" mitigation is fully described in the following blog post: https://support.google.com/faqs/answer/7625886 We also support a target feature that disables emission of the retpoline thunk by the compiler to allow for custom thunks if users want them. These are particularly useful in environments like kernels that routinely do hot-patching on boot and want to hot-patch their thunk to different code sequences. They can write this custom thunk and use `-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this case, on x86-64 thu thunk names must be: ``` __llvm_external_retpoline_r11 ``` or on 32-bit: ``` __llvm_external_retpoline_eax __llvm_external_retpoline_ecx __llvm_external_retpoline_edx __llvm_external_retpoline_push ``` And the target of the retpoline is passed in the named register, or in the case of the `push` suffix on the top of the stack via a `pushl` instruction. There is one other important source of indirect branches in x86 ELF binaries: the PLT. These patches also include support for LLD to generate PLT entries that perform a retpoline-style indirection. The only other indirect branches remaining that we are aware of are from precompiled runtimes (such as crt0.o and similar). The ones we have found are not really attackable, and so we have not focused on them here, but eventually these runtimes should also be replicated for retpoline-ed configurations for completeness. For kernels or other freestanding or fully static executables, the compiler switch `-mretpoline` is sufficient to fully mitigate this particular attack. For dynamic executables, you must compile *all* libraries with `-mretpoline` and additionally link the dynamic executable and all shared libraries with LLD and pass `-z retpolineplt` (or use similar functionality from some other linker). We strongly recommend also using `-z now` as non-lazy binding allows the retpoline-mitigated PLT to be substantially smaller. When manually apply similar transformations to `-mretpoline` to the Linux kernel we observed very small performance hits to applications running typical workloads, and relatively minor hits (approximately 2%) even for extremely syscall-heavy applications. This is largely due to the small number of indirect branches that occur in performance sensitive paths of the kernel. When using these patches on statically linked applications, especially C++ applications, you should expect to see a much more dramatic performance hit. For microbenchmarks that are switch, indirect-, or virtual-call heavy we have seen overheads ranging from 10% to 50%. However, real-world workloads exhibit substantially lower performance impact. Notably, techniques such as PGO and ThinLTO dramatically reduce the impact of hot indirect calls (by speculatively promoting them to direct calls) and allow optimized search trees to be used to lower switches. If you need to deploy these techniques in C++ applications, we *strongly* recommend that you ensure all hot call targets are statically linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well tuned servers using all of these techniques saw 5% - 10% overhead from the use of retpoline. We will add detailed documentation covering these components in subsequent patches, but wanted to make the core functionality available as soon as possible. Happy for more code review, but we'd really like to get these patches landed and backported ASAP for obvious reasons. We're planning to backport this to both 6.0 and 5.0 release streams and get a 5.0 release with just this cherry picked ASAP for distros and vendors. This patch is the work of a number of people over the past month: Eric, Reid, Rui, and myself. I'm mailing it out as a single commit due to the time sensitive nature of landing this and the need to backport it. Huge thanks to everyone who helped out here, and everyone at Intel who helped out in discussions about how to craft this. Also, credit goes to Paul Turner (at Google, but not an LLVM contributor) for much of the underlying retpoline design. Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits Differential Revision: https://reviews.llvm.org/D41723 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@323155 91177308-0d34-0410-b5e6-96231b3b80d8
262 lines
10 KiB
C++
262 lines
10 KiB
C++
//===- llvm/CodeGen/TargetSubtargetInfo.h - Target Information --*- C++ -*-===//
|
|
//
|
|
// The LLVM Compiler Infrastructure
|
|
//
|
|
// This file is distributed under the University of Illinois Open Source
|
|
// License. See LICENSE.TXT for details.
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This file describes the subtarget options of a Target machine.
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#ifndef LLVM_CODEGEN_TARGETSUBTARGETINFO_H
|
|
#define LLVM_CODEGEN_TARGETSUBTARGETINFO_H
|
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
|
#include "llvm/ADT/SmallVector.h"
|
|
#include "llvm/ADT/StringRef.h"
|
|
#include "llvm/CodeGen/PBQPRAConstraint.h"
|
|
#include "llvm/CodeGen/ScheduleDAGMutation.h"
|
|
#include "llvm/CodeGen/SchedulerRegistry.h"
|
|
#include "llvm/MC/MCSubtargetInfo.h"
|
|
#include "llvm/Support/CodeGen.h"
|
|
#include <memory>
|
|
#include <vector>
|
|
|
|
|
|
namespace llvm {
|
|
|
|
class CallLowering;
|
|
class InstrItineraryData;
|
|
struct InstrStage;
|
|
class InstructionSelector;
|
|
class LegalizerInfo;
|
|
class MachineInstr;
|
|
struct MachineSchedPolicy;
|
|
struct MCReadAdvanceEntry;
|
|
struct MCWriteLatencyEntry;
|
|
struct MCWriteProcResEntry;
|
|
class RegisterBankInfo;
|
|
class SDep;
|
|
class SelectionDAGTargetInfo;
|
|
struct SubtargetFeatureKV;
|
|
struct SubtargetInfoKV;
|
|
class SUnit;
|
|
class TargetFrameLowering;
|
|
class TargetInstrInfo;
|
|
class TargetLowering;
|
|
class TargetRegisterClass;
|
|
class TargetRegisterInfo;
|
|
class TargetSchedModel;
|
|
class Triple;
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
///
|
|
/// TargetSubtargetInfo - Generic base class for all target subtargets. All
|
|
/// Target-specific options that control code generation and printing should
|
|
/// be exposed through a TargetSubtargetInfo-derived class.
|
|
///
|
|
class TargetSubtargetInfo : public MCSubtargetInfo {
|
|
protected: // Can only create subclasses...
|
|
TargetSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS,
|
|
ArrayRef<SubtargetFeatureKV> PF,
|
|
ArrayRef<SubtargetFeatureKV> PD,
|
|
const SubtargetInfoKV *ProcSched,
|
|
const MCWriteProcResEntry *WPR,
|
|
const MCWriteLatencyEntry *WL,
|
|
const MCReadAdvanceEntry *RA, const InstrStage *IS,
|
|
const unsigned *OC, const unsigned *FP);
|
|
|
|
public:
|
|
// AntiDepBreakMode - Type of anti-dependence breaking that should
|
|
// be performed before post-RA scheduling.
|
|
using AntiDepBreakMode = enum { ANTIDEP_NONE, ANTIDEP_CRITICAL, ANTIDEP_ALL };
|
|
using RegClassVector = SmallVectorImpl<const TargetRegisterClass *>;
|
|
|
|
TargetSubtargetInfo() = delete;
|
|
TargetSubtargetInfo(const TargetSubtargetInfo &) = delete;
|
|
TargetSubtargetInfo &operator=(const TargetSubtargetInfo &) = delete;
|
|
~TargetSubtargetInfo() override;
|
|
|
|
virtual bool isXRaySupported() const { return false; }
|
|
|
|
// Interfaces to the major aspects of target machine information:
|
|
//
|
|
// -- Instruction opcode and operand information
|
|
// -- Pipelines and scheduling information
|
|
// -- Stack frame information
|
|
// -- Selection DAG lowering information
|
|
// -- Call lowering information
|
|
//
|
|
// N.B. These objects may change during compilation. It's not safe to cache
|
|
// them between functions.
|
|
virtual const TargetInstrInfo *getInstrInfo() const { return nullptr; }
|
|
virtual const TargetFrameLowering *getFrameLowering() const {
|
|
return nullptr;
|
|
}
|
|
virtual const TargetLowering *getTargetLowering() const { return nullptr; }
|
|
virtual const SelectionDAGTargetInfo *getSelectionDAGInfo() const {
|
|
return nullptr;
|
|
}
|
|
virtual const CallLowering *getCallLowering() const { return nullptr; }
|
|
|
|
// FIXME: This lets targets specialize the selector by subtarget (which lets
|
|
// us do things like a dedicated avx512 selector). However, we might want
|
|
// to also specialize selectors by MachineFunction, which would let us be
|
|
// aware of optsize/optnone and such.
|
|
virtual const InstructionSelector *getInstructionSelector() const {
|
|
return nullptr;
|
|
}
|
|
|
|
virtual unsigned getHwMode() const { return 0; }
|
|
|
|
/// Target can subclass this hook to select a different DAG scheduler.
|
|
virtual RegisterScheduler::FunctionPassCtor
|
|
getDAGScheduler(CodeGenOpt::Level) const {
|
|
return nullptr;
|
|
}
|
|
|
|
virtual const LegalizerInfo *getLegalizerInfo() const { return nullptr; }
|
|
|
|
/// getRegisterInfo - If register information is available, return it. If
|
|
/// not, return null.
|
|
virtual const TargetRegisterInfo *getRegisterInfo() const { return nullptr; }
|
|
|
|
/// If the information for the register banks is available, return it.
|
|
/// Otherwise return nullptr.
|
|
virtual const RegisterBankInfo *getRegBankInfo() const { return nullptr; }
|
|
|
|
/// getInstrItineraryData - Returns instruction itinerary data for the target
|
|
/// or specific subtarget.
|
|
virtual const InstrItineraryData *getInstrItineraryData() const {
|
|
return nullptr;
|
|
}
|
|
|
|
/// Resolve a SchedClass at runtime, where SchedClass identifies an
|
|
/// MCSchedClassDesc with the isVariant property. This may return the ID of
|
|
/// another variant SchedClass, but repeated invocation must quickly terminate
|
|
/// in a nonvariant SchedClass.
|
|
virtual unsigned resolveSchedClass(unsigned SchedClass,
|
|
const MachineInstr *MI,
|
|
const TargetSchedModel *SchedModel) const {
|
|
return 0;
|
|
}
|
|
|
|
/// \brief True if the subtarget should run MachineScheduler after aggressive
|
|
/// coalescing.
|
|
///
|
|
/// This currently replaces the SelectionDAG scheduler with the "source" order
|
|
/// scheduler (though see below for an option to turn this off and use the
|
|
/// TargetLowering preference). It does not yet disable the postRA scheduler.
|
|
virtual bool enableMachineScheduler() const;
|
|
|
|
/// \brief Support printing of [latency:throughput] comment in output .S file.
|
|
virtual bool supportPrintSchedInfo() const { return false; }
|
|
|
|
/// \brief True if the machine scheduler should disable the TLI preference
|
|
/// for preRA scheduling with the source level scheduler.
|
|
virtual bool enableMachineSchedDefaultSched() const { return true; }
|
|
|
|
/// \brief True if the subtarget should enable joining global copies.
|
|
///
|
|
/// By default this is enabled if the machine scheduler is enabled, but
|
|
/// can be overridden.
|
|
virtual bool enableJoinGlobalCopies() const;
|
|
|
|
/// True if the subtarget should run a scheduler after register allocation.
|
|
///
|
|
/// By default this queries the PostRAScheduling bit in the scheduling model
|
|
/// which is the preferred way to influence this.
|
|
virtual bool enablePostRAScheduler() const;
|
|
|
|
/// \brief True if the subtarget should run the atomic expansion pass.
|
|
virtual bool enableAtomicExpand() const;
|
|
|
|
/// True if the subtarget should run the indirectbr expansion pass.
|
|
virtual bool enableIndirectBrExpand() const;
|
|
|
|
/// \brief Override generic scheduling policy within a region.
|
|
///
|
|
/// This is a convenient way for targets that don't provide any custom
|
|
/// scheduling heuristics (no custom MachineSchedStrategy) to make
|
|
/// changes to the generic scheduling policy.
|
|
virtual void overrideSchedPolicy(MachineSchedPolicy &Policy,
|
|
unsigned NumRegionInstrs) const {}
|
|
|
|
// \brief Perform target specific adjustments to the latency of a schedule
|
|
// dependency.
|
|
virtual void adjustSchedDependency(SUnit *def, SUnit *use, SDep &dep) const {}
|
|
|
|
// For use with PostRAScheduling: get the anti-dependence breaking that should
|
|
// be performed before post-RA scheduling.
|
|
virtual AntiDepBreakMode getAntiDepBreakMode() const { return ANTIDEP_NONE; }
|
|
|
|
// For use with PostRAScheduling: in CriticalPathRCs, return any register
|
|
// classes that should only be considered for anti-dependence breaking if they
|
|
// are on the critical path.
|
|
virtual void getCriticalPathRCs(RegClassVector &CriticalPathRCs) const {
|
|
return CriticalPathRCs.clear();
|
|
}
|
|
|
|
// \brief Provide an ordered list of schedule DAG mutations for the post-RA
|
|
// scheduler.
|
|
virtual void getPostRAMutations(
|
|
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
|
|
}
|
|
|
|
// \brief Provide an ordered list of schedule DAG mutations for the machine
|
|
// pipeliner.
|
|
virtual void getSMSMutations(
|
|
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
|
|
}
|
|
|
|
// For use with PostRAScheduling: get the minimum optimization level needed
|
|
// to enable post-RA scheduling.
|
|
virtual CodeGenOpt::Level getOptLevelToEnablePostRAScheduler() const {
|
|
return CodeGenOpt::Default;
|
|
}
|
|
|
|
/// \brief True if the subtarget should run the local reassignment
|
|
/// heuristic of the register allocator.
|
|
/// This heuristic may be compile time intensive, \p OptLevel provides
|
|
/// a finer grain to tune the register allocator.
|
|
virtual bool enableRALocalReassignment(CodeGenOpt::Level OptLevel) const;
|
|
|
|
/// \brief True if the subtarget should consider the cost of local intervals
|
|
/// created by a split candidate when choosing the best split candidate. This
|
|
/// heuristic may be compile time intensive.
|
|
virtual bool enableAdvancedRASplitCost() const;
|
|
|
|
/// \brief Enable use of alias analysis during code generation (during MI
|
|
/// scheduling, DAGCombine, etc.).
|
|
virtual bool useAA() const;
|
|
|
|
/// \brief Enable the use of the early if conversion pass.
|
|
virtual bool enableEarlyIfConversion() const { return false; }
|
|
|
|
/// \brief Return PBQPConstraint(s) for the target.
|
|
///
|
|
/// Override to provide custom PBQP constraints.
|
|
virtual std::unique_ptr<PBQPRAConstraint> getCustomPBQPConstraints() const {
|
|
return nullptr;
|
|
}
|
|
|
|
/// Enable tracking of subregister liveness in register allocator.
|
|
/// Please use MachineRegisterInfo::subRegLivenessEnabled() instead where
|
|
/// possible.
|
|
virtual bool enableSubRegLiveness() const { return false; }
|
|
|
|
/// Returns string representation of scheduler comment
|
|
std::string getSchedInfoStr(const MachineInstr &MI) const override;
|
|
std::string getSchedInfoStr(MCInst const &MCI) const override;
|
|
|
|
/// This is called after a .mir file was loaded.
|
|
virtual void mirFileLoaded(MachineFunction &MF) const;
|
|
};
|
|
|
|
} // end namespace llvm
|
|
|
|
#endif // LLVM_CODEGEN_TARGETSUBTARGETINFO_H
|