2002-10-30 06:37:54 +08:00
|
|
|
//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
|
2005-04-22 07:38:14 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
2007-12-30 04:36:04 +08:00
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
2005-04-22 07:38:14 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2005-04-22 07:38:14 +08:00
|
|
|
//
|
2002-10-30 06:37:54 +08:00
|
|
|
// This file defines the X86 specific subclass of TargetMachine.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2017-11-17 09:07:10 +08:00
|
|
|
#include "X86TargetMachine.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "MCTargetDesc/X86MCTargetDesc.h"
|
2002-12-24 08:04:01 +08:00
|
|
|
#include "X86.h"
|
2016-11-15 14:34:33 +08:00
|
|
|
#include "X86CallLowering.h"
|
2017-02-10 15:05:56 +08:00
|
|
|
#include "X86LegalizerInfo.h"
|
2017-02-01 10:54:34 +08:00
|
|
|
#include "X86MacroFusion.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "X86Subtarget.h"
|
2014-11-13 17:26:31 +08:00
|
|
|
#include "X86TargetObjectFile.h"
|
2015-01-31 19:17:59 +08:00
|
|
|
#include "X86TargetTransformInfo.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/ADT/Optional.h"
|
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2017-06-06 19:49:48 +08:00
|
|
|
#include "llvm/ADT/SmallString.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
|
|
|
#include "llvm/ADT/Triple.h"
|
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
2018-01-22 18:06:33 +08:00
|
|
|
#include "llvm/CodeGen/ExecutionDomainFix.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/CodeGen/GlobalISel/CallLowering.h"
|
2016-11-15 14:34:33 +08:00
|
|
|
#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
|
2017-03-18 13:08:58 +08:00
|
|
|
#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
|
2017-02-10 15:05:56 +08:00
|
|
|
#include "llvm/CodeGen/GlobalISel/Legalizer.h"
|
|
|
|
#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
|
2016-11-29 04:11:54 +08:00
|
|
|
#include "llvm/CodeGen/MachineScheduler.h"
|
2003-01-13 08:51:23 +08:00
|
|
|
#include "llvm/CodeGen/Passes.h"
|
2016-05-10 11:21:59 +08:00
|
|
|
#include "llvm/CodeGen/TargetPassConfig.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/IR/Attributes.h"
|
|
|
|
#include "llvm/IR/DataLayout.h"
|
2014-10-06 14:45:36 +08:00
|
|
|
#include "llvm/IR/Function.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/Pass.h"
|
|
|
|
#include "llvm/Support/CodeGen.h"
|
2011-08-23 09:14:17 +08:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include "llvm/Support/ErrorHandling.h"
|
2011-08-25 02:08:43 +08:00
|
|
|
#include "llvm/Support/TargetRegistry.h"
|
2018-03-24 07:58:19 +08:00
|
|
|
#include "llvm/Target/TargetLoweringObjectFile.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Target/TargetOptions.h"
|
2017-02-03 06:55:55 +08:00
|
|
|
#include <memory>
|
|
|
|
#include <string>
|
|
|
|
|
2003-12-20 09:22:19 +08:00
|
|
|
using namespace llvm;
|
2003-11-12 06:41:34 +08:00
|
|
|
|
2015-06-11 04:32:21 +08:00
|
|
|
static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
|
|
|
|
cl::desc("Enable the machine combiner pass"),
|
|
|
|
cl::init(true), cl::Hidden);
|
|
|
|
|
2015-08-19 03:07:12 +08:00
|
|
|
namespace llvm {
|
2017-02-03 06:55:55 +08:00
|
|
|
|
2015-08-19 03:07:12 +08:00
|
|
|
void initializeWinEHStatePassPass(PassRegistry &);
|
2017-05-18 16:11:50 +08:00
|
|
|
void initializeFixupLEAPassPass(PassRegistry &);
|
2017-10-24 13:47:07 +08:00
|
|
|
void initializeX86CallFrameOptimizationPass(PassRegistry &);
|
2017-10-03 05:46:37 +08:00
|
|
|
void initializeX86CmovConverterPassPass(PassRegistry &);
|
2018-01-22 18:05:23 +08:00
|
|
|
void initializeX86ExecutionDomainFixPass(PassRegistry &);
|
2017-10-22 19:43:08 +08:00
|
|
|
void initializeX86DomainReassignmentPass(PassRegistry &);
|
2018-04-02 21:48:28 +08:00
|
|
|
void initializeX86AvoidSFBPassPass(PassRegistry &);
|
2017-02-03 06:55:55 +08:00
|
|
|
|
|
|
|
} // end namespace llvm
|
2015-08-19 03:07:12 +08:00
|
|
|
|
2011-02-17 20:23:50 +08:00
|
|
|
extern "C" void LLVMInitializeX86Target() {
|
2009-07-25 14:49:55 +08:00
|
|
|
// Register the target.
|
2016-10-10 07:00:34 +08:00
|
|
|
RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
|
|
|
|
RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
|
2015-08-19 03:07:12 +08:00
|
|
|
|
|
|
|
PassRegistry &PR = *PassRegistry::getPassRegistry();
|
2016-11-15 14:34:33 +08:00
|
|
|
initializeGlobalISel(PR);
|
2015-08-19 03:07:12 +08:00
|
|
|
initializeWinEHStatePassPass(PR);
|
2016-05-07 09:11:10 +08:00
|
|
|
initializeFixupBWInstPassPass(PR);
|
2016-12-28 18:12:48 +08:00
|
|
|
initializeEvexToVexInstPassPass(PR);
|
2017-05-18 16:11:50 +08:00
|
|
|
initializeFixupLEAPassPass(PR);
|
2017-10-24 13:47:07 +08:00
|
|
|
initializeX86CallFrameOptimizationPass(PR);
|
2017-10-03 05:46:37 +08:00
|
|
|
initializeX86CmovConverterPassPass(PR);
|
2018-01-22 18:05:23 +08:00
|
|
|
initializeX86ExecutionDomainFixPass(PR);
|
2017-10-22 19:43:08 +08:00
|
|
|
initializeX86DomainReassignmentPass(PR);
|
2018-04-02 21:48:28 +08:00
|
|
|
initializeX86AvoidSFBPassPass(PR);
|
2006-09-08 07:39:26 +08:00
|
|
|
}
|
2006-09-08 14:48:29 +08:00
|
|
|
|
2014-11-13 17:26:31 +08:00
|
|
|
static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
|
|
|
|
if (TT.isOSBinFormatMachO()) {
|
|
|
|
if (TT.getArch() == Triple::x86_64)
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86_64MachoTargetObjectFile>();
|
|
|
|
return llvm::make_unique<TargetLoweringObjectFileMachO>();
|
2014-11-13 17:26:31 +08:00
|
|
|
}
|
|
|
|
|
2016-09-27 06:53:15 +08:00
|
|
|
if (TT.isOSFreeBSD())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86FreeBSDTargetObjectFile>();
|
2017-05-09 18:14:03 +08:00
|
|
|
if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
|
2017-06-22 04:36:32 +08:00
|
|
|
if (TT.isOSSolaris())
|
|
|
|
return llvm::make_unique<X86SolarisTargetObjectFile>();
|
2016-10-06 13:17:26 +08:00
|
|
|
if (TT.isOSFuchsia())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86FuchsiaTargetObjectFile>();
|
2014-11-13 17:26:31 +08:00
|
|
|
if (TT.isOSBinFormatELF())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86ELFTargetObjectFile>();
|
2015-08-15 06:41:43 +08:00
|
|
|
if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<X86WindowsTargetObjectFile>();
|
2014-11-13 17:26:31 +08:00
|
|
|
if (TT.isOSBinFormatCOFF())
|
2017-02-03 06:55:55 +08:00
|
|
|
return llvm::make_unique<TargetLoweringObjectFileCOFF>();
|
2014-11-13 17:26:31 +08:00
|
|
|
llvm_unreachable("unknown subtarget type");
|
|
|
|
}
|
|
|
|
|
2015-01-27 03:03:15 +08:00
|
|
|
static std::string computeDataLayout(const Triple &TT) {
|
|
|
|
// X86 is little endian
|
|
|
|
std::string Ret = "e";
|
|
|
|
|
|
|
|
Ret += DataLayout::getManglingComponent(TT);
|
|
|
|
// X86 and x32 have 32 bit pointers.
|
|
|
|
if ((TT.isArch64Bit() &&
|
|
|
|
(TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
|
|
|
|
!TT.isArch64Bit())
|
|
|
|
Ret += "-p:32:32";
|
|
|
|
|
|
|
|
// Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
|
|
|
|
if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
|
|
|
|
Ret += "-i64:64";
|
2016-02-10 19:57:06 +08:00
|
|
|
else if (TT.isOSIAMCU())
|
|
|
|
Ret += "-i64:32-f64:32";
|
2015-01-27 03:03:15 +08:00
|
|
|
else
|
|
|
|
Ret += "-f64:32:64";
|
|
|
|
|
|
|
|
// Some ABIs align long double to 128 bits, others to 32.
|
2016-02-10 19:57:06 +08:00
|
|
|
if (TT.isOSNaCl() || TT.isOSIAMCU())
|
2015-01-27 03:03:15 +08:00
|
|
|
; // No f80
|
|
|
|
else if (TT.isArch64Bit() || TT.isOSDarwin())
|
|
|
|
Ret += "-f80:128";
|
|
|
|
else
|
|
|
|
Ret += "-f80:32";
|
|
|
|
|
2016-02-10 19:57:06 +08:00
|
|
|
if (TT.isOSIAMCU())
|
|
|
|
Ret += "-f128:32";
|
|
|
|
|
2015-01-27 03:03:15 +08:00
|
|
|
// The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
|
|
|
|
if (TT.isArch64Bit())
|
|
|
|
Ret += "-n8:16:32:64";
|
|
|
|
else
|
|
|
|
Ret += "-n8:16:32";
|
|
|
|
|
|
|
|
// The stack is aligned to 32 bits on some ABIs and 128 bits on others.
|
2016-02-10 19:57:06 +08:00
|
|
|
if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
|
2015-05-01 06:11:59 +08:00
|
|
|
Ret += "-a:0:32-S32";
|
2015-01-27 03:03:15 +08:00
|
|
|
else
|
|
|
|
Ret += "-S128";
|
|
|
|
|
|
|
|
return Ret;
|
|
|
|
}
|
|
|
|
|
2016-05-19 06:04:49 +08:00
|
|
|
static Reloc::Model getEffectiveRelocModel(const Triple &TT,
|
|
|
|
Optional<Reloc::Model> RM) {
|
|
|
|
bool is64Bit = TT.getArch() == Triple::x86_64;
|
|
|
|
if (!RM.hasValue()) {
|
|
|
|
// Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
|
|
|
|
// Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
|
|
|
|
// use static relocation model by default.
|
|
|
|
if (TT.isOSDarwin()) {
|
|
|
|
if (is64Bit)
|
|
|
|
return Reloc::PIC_;
|
|
|
|
return Reloc::DynamicNoPIC;
|
|
|
|
}
|
|
|
|
if (TT.isOSWindows() && is64Bit)
|
|
|
|
return Reloc::PIC_;
|
|
|
|
return Reloc::Static;
|
|
|
|
}
|
|
|
|
|
|
|
|
// ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
|
|
|
|
// is defined as a model for code which may be used in static or dynamic
|
|
|
|
// executables but not necessarily a shared library. On X86-32 we just
|
|
|
|
// compile in -static mode, in x86-64 we use PIC.
|
|
|
|
if (*RM == Reloc::DynamicNoPIC) {
|
|
|
|
if (is64Bit)
|
|
|
|
return Reloc::PIC_;
|
|
|
|
if (!TT.isOSDarwin())
|
|
|
|
return Reloc::Static;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are on Darwin, disallow static relocation model in X86-64 mode, since
|
|
|
|
// the Mach-O file format doesn't support it.
|
|
|
|
if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
|
|
|
|
return Reloc::PIC_;
|
|
|
|
|
|
|
|
return *RM;
|
|
|
|
}
|
|
|
|
|
2017-08-03 10:16:21 +08:00
|
|
|
static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
|
|
|
|
bool JIT, bool Is64Bit) {
|
|
|
|
if (CM)
|
|
|
|
return *CM;
|
|
|
|
if (JIT)
|
|
|
|
return Is64Bit ? CodeModel::Large : CodeModel::Small;
|
|
|
|
return CodeModel::Small;
|
|
|
|
}
|
|
|
|
|
2016-05-19 00:00:24 +08:00
|
|
|
/// Create an X86 target.
|
2002-10-30 06:37:54 +08:00
|
|
|
///
|
2015-06-12 03:41:26 +08:00
|
|
|
X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
|
|
|
|
StringRef CPU, StringRef FS,
|
|
|
|
const TargetOptions &Options,
|
2016-05-19 06:04:49 +08:00
|
|
|
Optional<Reloc::Model> RM,
|
2017-08-03 10:16:21 +08:00
|
|
|
Optional<CodeModel::Model> CM,
|
|
|
|
CodeGenOpt::Level OL, bool JIT)
|
2017-10-13 06:57:28 +08:00
|
|
|
: LLVMTargetMachine(
|
2017-08-03 10:16:21 +08:00
|
|
|
T, computeDataLayout(TT), TT, CPU, FS, Options,
|
|
|
|
getEffectiveRelocModel(TT, RM),
|
|
|
|
getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL),
|
2016-09-21 06:19:33 +08:00
|
|
|
TLOF(createTLOF(getTargetTriple())) {
|
2015-10-09 09:13:17 +08:00
|
|
|
// Windows stack unwinder gets confused when execution flow "falls through"
|
|
|
|
// after a call to 'noreturn' function.
|
|
|
|
// To prevent that, we emit a trap for 'unreachable' IR instructions.
|
|
|
|
// (which on X86, happens to be the 'ud2' instruction)
|
2016-03-24 08:10:03 +08:00
|
|
|
// On PS4, the "return address" of a 'noreturn' call must still be within
|
|
|
|
// the calling function, and TrapUnreachable is an easy way to get that.
|
2016-09-21 00:04:59 +08:00
|
|
|
// The check here for 64-bit windows is a bit icky, but as we're unlikely
|
|
|
|
// to ever want to mix 32 and 64-bit windows code in a single module
|
|
|
|
// this should be fine.
|
|
|
|
if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
|
2015-10-09 09:13:17 +08:00
|
|
|
this->Options.TrapUnreachable = true;
|
|
|
|
|
2014-01-08 08:08:50 +08:00
|
|
|
initAsmInfo();
|
2006-02-04 02:59:39 +08:00
|
|
|
}
|
2002-10-30 06:37:54 +08:00
|
|
|
|
2017-02-03 06:55:55 +08:00
|
|
|
X86TargetMachine::~X86TargetMachine() = default;
|
2014-11-21 07:37:18 +08:00
|
|
|
|
2014-10-06 14:45:36 +08:00
|
|
|
const X86Subtarget *
|
|
|
|
X86TargetMachine::getSubtargetImpl(const Function &F) const {
|
2015-02-14 09:59:52 +08:00
|
|
|
Attribute CPUAttr = F.getFnAttribute("target-cpu");
|
|
|
|
Attribute FSAttr = F.getFnAttribute("target-features");
|
2014-10-06 14:45:36 +08:00
|
|
|
|
2016-05-21 04:41:24 +08:00
|
|
|
StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
|
|
|
|
? CPUAttr.getValueAsString()
|
|
|
|
: (StringRef)TargetCPU;
|
|
|
|
StringRef FS = !FSAttr.hasAttribute(Attribute::None)
|
|
|
|
? FSAttr.getValueAsString()
|
|
|
|
: (StringRef)TargetFS;
|
|
|
|
|
|
|
|
SmallString<512> Key;
|
|
|
|
Key.reserve(CPU.size() + FS.size());
|
|
|
|
Key += CPU;
|
|
|
|
Key += FS;
|
2014-10-06 14:45:36 +08:00
|
|
|
|
|
|
|
// FIXME: This is related to the code below to reset the target options,
|
|
|
|
// we need to know whether or not the soft float flag is set on the
|
|
|
|
// function before we can generate a subtarget. We also need to use
|
|
|
|
// it as a key for the subtarget since that can be the only difference
|
|
|
|
// between two functions.
|
2015-05-12 09:26:05 +08:00
|
|
|
bool SoftFloat =
|
|
|
|
F.getFnAttribute("use-soft-float").getValueAsString() == "true";
|
|
|
|
// If the soft float attribute is set on the function turn on the soft float
|
|
|
|
// subtarget feature.
|
|
|
|
if (SoftFloat)
|
2016-05-21 04:41:24 +08:00
|
|
|
Key += FS.empty() ? "+soft-float" : ",+soft-float";
|
2015-05-12 09:26:05 +08:00
|
|
|
|
2018-01-20 08:26:08 +08:00
|
|
|
// Keep track of the key width after all features are added so we can extract
|
|
|
|
// the feature string out later.
|
|
|
|
unsigned CPUFSWidth = Key.size();
|
|
|
|
|
2018-02-11 16:06:27 +08:00
|
|
|
// Extract prefer-vector-width attribute.
|
2018-01-20 08:26:08 +08:00
|
|
|
unsigned PreferVectorWidthOverride = 0;
|
|
|
|
if (F.hasFnAttribute("prefer-vector-width")) {
|
|
|
|
StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
|
|
|
|
unsigned Width;
|
|
|
|
if (!Val.getAsInteger(0, Width)) {
|
|
|
|
Key += ",prefer-vector-width=";
|
|
|
|
Key += Val;
|
|
|
|
PreferVectorWidthOverride = Width;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-11 16:06:27 +08:00
|
|
|
// Extract required-vector-width attribute.
|
|
|
|
unsigned RequiredVectorWidth = UINT32_MAX;
|
|
|
|
if (F.hasFnAttribute("required-vector-width")) {
|
|
|
|
StringRef Val = F.getFnAttribute("required-vector-width").getValueAsString();
|
|
|
|
unsigned Width;
|
|
|
|
if (!Val.getAsInteger(0, Width)) {
|
|
|
|
Key += ",required-vector-width=";
|
|
|
|
Key += Val;
|
|
|
|
RequiredVectorWidth = Width;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extracted here so that we make sure there is backing for the StringRef. If
|
|
|
|
// we assigned earlier, its possible the SmallString reallocated leaving a
|
|
|
|
// dangling StringRef.
|
2018-01-20 08:26:08 +08:00
|
|
|
FS = Key.slice(CPU.size(), CPUFSWidth);
|
2016-05-21 02:16:06 +08:00
|
|
|
|
|
|
|
auto &I = SubtargetMap[Key];
|
2014-10-06 14:45:36 +08:00
|
|
|
if (!I) {
|
|
|
|
// This needs to be done before we create a new subtarget since any
|
|
|
|
// creation will depend on the TM and the code generation flags on the
|
|
|
|
// function that reside in TargetOptions.
|
|
|
|
resetTargetOptions(F);
|
2015-06-16 23:44:21 +08:00
|
|
|
I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
|
2018-01-20 08:26:08 +08:00
|
|
|
Options.StackAlignmentOverride,
|
2018-02-11 16:06:27 +08:00
|
|
|
PreferVectorWidthOverride,
|
|
|
|
RequiredVectorWidth);
|
2014-10-06 14:45:36 +08:00
|
|
|
}
|
|
|
|
return I.get();
|
|
|
|
}
|
|
|
|
|
2011-08-23 09:14:17 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Command line options for x86
|
|
|
|
//===----------------------------------------------------------------------===//
|
2011-09-03 11:45:06 +08:00
|
|
|
static cl::opt<bool>
|
2013-10-19 07:38:13 +08:00
|
|
|
UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
|
2011-08-23 09:14:17 +08:00
|
|
|
cl::desc("Minimize AVX to SSE transition penalty"),
|
2011-11-17 08:21:52 +08:00
|
|
|
cl::init(true));
|
2011-08-23 09:14:17 +08:00
|
|
|
|
Switch TargetTransformInfo from an immutable analysis pass that requires
a TargetMachine to construct (and thus isn't always available), to an
analysis group that supports layered implementations much like
AliasAnalysis does. This is a pretty massive change, with a few parts
that I was unable to easily separate (sorry), so I'll walk through it.
The first step of this conversion was to make TargetTransformInfo an
analysis group, and to sink the nonce implementations in
ScalarTargetTransformInfo and VectorTargetTranformInfo into
a NoTargetTransformInfo pass. This allows other passes to add a hard
requirement on TTI, and assume they will always get at least on
implementation.
The TargetTransformInfo analysis group leverages the delegation chaining
trick that AliasAnalysis uses, where the base class for the analysis
group delegates to the previous analysis *pass*, allowing all but tho
NoFoo analysis passes to only implement the parts of the interfaces they
support. It also introduces a new trick where each pass in the group
retains a pointer to the top-most pass that has been initialized. This
allows passes to implement one API in terms of another API and benefit
when some other pass above them in the stack has more precise results
for the second API.
The second step of this conversion is to create a pass that implements
the TargetTransformInfo analysis using the target-independent
abstractions in the code generator. This replaces the
ScalarTargetTransformImpl and VectorTargetTransformImpl classes in
lib/Target with a single pass in lib/CodeGen called
BasicTargetTransformInfo. This class actually provides most of the TTI
functionality, basing it upon the TargetLowering abstraction and other
information in the target independent code generator.
The third step of the conversion adds support to all TargetMachines to
register custom analysis passes. This allows building those passes with
access to TargetLowering or other target-specific classes, and it also
allows each target to customize the set of analysis passes desired in
the pass manager. The baseline LLVMTargetMachine implements this
interface to add the BasicTTI pass to the pass manager, and all of the
tools that want to support target-aware TTI passes call this routine on
whatever target machine they end up with to add the appropriate passes.
The fourth step of the conversion created target-specific TTI analysis
passes for the X86 and ARM backends. These passes contain the custom
logic that was previously in their extensions of the
ScalarTargetTransformInfo and VectorTargetTransformInfo interfaces.
I separated them into their own file, as now all of the interface bits
are private and they just expose a function to create the pass itself.
Then I extended these target machines to set up a custom set of analysis
passes, first adding BasicTTI as a fallback, and then adding their
customized TTI implementations.
The fourth step required logic that was shared between the target
independent layer and the specific targets to move to a different
interface, as they no longer derive from each other. As a consequence,
a helper functions were added to TargetLowering representing the common
logic needed both in the target implementation and the codegen
implementation of the TTI pass. While technically this is the only
change that could have been committed separately, it would have been
a nightmare to extract.
The final step of the conversion was just to delete all the old
boilerplate. This got rid of the ScalarTargetTransformInfo and
VectorTargetTransformInfo classes, all of the support in all of the
targets for producing instances of them, and all of the support in the
tools for manually constructing a pass based around them.
Now that TTI is a relatively normal analysis group, two things become
straightforward. First, we can sink it into lib/Analysis which is a more
natural layer for it to live. Second, clients of this interface can
depend on it *always* being available which will simplify their code and
behavior. These (and other) simplifications will follow in subsequent
commits, this one is clearly big enough.
Finally, I'm very aware that much of the comments and documentation
needs to be updated. As soon as I had this working, and plausibly well
commented, I wanted to get it committed and in front of the build bots.
I'll be doing a few passes over documentation later if it sticks.
Commits to update DragonEgg and Clang will be made presently.
llvm-svn: 171681
2013-01-07 09:37:14 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2015-01-31 19:17:59 +08:00
|
|
|
// X86 TTI query.
|
Switch TargetTransformInfo from an immutable analysis pass that requires
a TargetMachine to construct (and thus isn't always available), to an
analysis group that supports layered implementations much like
AliasAnalysis does. This is a pretty massive change, with a few parts
that I was unable to easily separate (sorry), so I'll walk through it.
The first step of this conversion was to make TargetTransformInfo an
analysis group, and to sink the nonce implementations in
ScalarTargetTransformInfo and VectorTargetTranformInfo into
a NoTargetTransformInfo pass. This allows other passes to add a hard
requirement on TTI, and assume they will always get at least on
implementation.
The TargetTransformInfo analysis group leverages the delegation chaining
trick that AliasAnalysis uses, where the base class for the analysis
group delegates to the previous analysis *pass*, allowing all but tho
NoFoo analysis passes to only implement the parts of the interfaces they
support. It also introduces a new trick where each pass in the group
retains a pointer to the top-most pass that has been initialized. This
allows passes to implement one API in terms of another API and benefit
when some other pass above them in the stack has more precise results
for the second API.
The second step of this conversion is to create a pass that implements
the TargetTransformInfo analysis using the target-independent
abstractions in the code generator. This replaces the
ScalarTargetTransformImpl and VectorTargetTransformImpl classes in
lib/Target with a single pass in lib/CodeGen called
BasicTargetTransformInfo. This class actually provides most of the TTI
functionality, basing it upon the TargetLowering abstraction and other
information in the target independent code generator.
The third step of the conversion adds support to all TargetMachines to
register custom analysis passes. This allows building those passes with
access to TargetLowering or other target-specific classes, and it also
allows each target to customize the set of analysis passes desired in
the pass manager. The baseline LLVMTargetMachine implements this
interface to add the BasicTTI pass to the pass manager, and all of the
tools that want to support target-aware TTI passes call this routine on
whatever target machine they end up with to add the appropriate passes.
The fourth step of the conversion created target-specific TTI analysis
passes for the X86 and ARM backends. These passes contain the custom
logic that was previously in their extensions of the
ScalarTargetTransformInfo and VectorTargetTransformInfo interfaces.
I separated them into their own file, as now all of the interface bits
are private and they just expose a function to create the pass itself.
Then I extended these target machines to set up a custom set of analysis
passes, first adding BasicTTI as a fallback, and then adding their
customized TTI implementations.
The fourth step required logic that was shared between the target
independent layer and the specific targets to move to a different
interface, as they no longer derive from each other. As a consequence,
a helper functions were added to TargetLowering representing the common
logic needed both in the target implementation and the codegen
implementation of the TTI pass. While technically this is the only
change that could have been committed separately, it would have been
a nightmare to extract.
The final step of the conversion was just to delete all the old
boilerplate. This got rid of the ScalarTargetTransformInfo and
VectorTargetTransformInfo classes, all of the support in all of the
targets for producing instances of them, and all of the support in the
tools for manually constructing a pass based around them.
Now that TTI is a relatively normal analysis group, two things become
straightforward. First, we can sink it into lib/Analysis which is a more
natural layer for it to live. Second, clients of this interface can
depend on it *always* being available which will simplify their code and
behavior. These (and other) simplifications will follow in subsequent
commits, this one is clearly big enough.
Finally, I'm very aware that much of the comments and documentation
needs to be updated. As soon as I had this working, and plausibly well
commented, I wanted to get it committed and in front of the build bots.
I'll be doing a few passes over documentation later if it sticks.
Commits to update DragonEgg and Clang will be made presently.
llvm-svn: 171681
2013-01-07 09:37:14 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
(Re-landing) Expose a TargetMachine::getTargetTransformInfo function
Re-land r321234. It had to be reverted because it broke the shared
library build. The shared library build broke because there was a
missing LLVMBuild dependency from lib/Passes (which calls
TargetMachine::getTargetIRAnalysis) to lib/Target. As far as I can
tell, this problem was always there but was somehow masked
before (perhaps because TargetMachine::getTargetIRAnalysis was a
virtual function).
Original commit message:
This makes the TargetMachine interface a bit simpler. We still need
the std::function in TargetIRAnalysis to avoid having to add a
dependency from Analysis to Target.
See discussion:
http://lists.llvm.org/pipermail/llvm-dev/2017-December/119749.html
I avoided adding all of the backend owners to this review since the
change is simple, but let me know if you feel differently about this.
Reviewers: echristo, MatzeB, hfinkel
Reviewed By: hfinkel
Subscribers: jholewinski, jfb, arsenm, dschuff, mcrosier, sdardis, nemanjai, nhaehnle, javed.absar, sbc100, jgravelle-google, aheejin, kbarton, llvm-commits
Differential Revision: https://reviews.llvm.org/D41464
llvm-svn: 321375
2017-12-23 02:21:59 +08:00
|
|
|
TargetTransformInfo
|
|
|
|
X86TargetMachine::getTargetTransformInfo(const Function &F) {
|
|
|
|
return TargetTransformInfo(X86TTIImpl(this, F));
|
Switch TargetTransformInfo from an immutable analysis pass that requires
a TargetMachine to construct (and thus isn't always available), to an
analysis group that supports layered implementations much like
AliasAnalysis does. This is a pretty massive change, with a few parts
that I was unable to easily separate (sorry), so I'll walk through it.
The first step of this conversion was to make TargetTransformInfo an
analysis group, and to sink the nonce implementations in
ScalarTargetTransformInfo and VectorTargetTranformInfo into
a NoTargetTransformInfo pass. This allows other passes to add a hard
requirement on TTI, and assume they will always get at least on
implementation.
The TargetTransformInfo analysis group leverages the delegation chaining
trick that AliasAnalysis uses, where the base class for the analysis
group delegates to the previous analysis *pass*, allowing all but tho
NoFoo analysis passes to only implement the parts of the interfaces they
support. It also introduces a new trick where each pass in the group
retains a pointer to the top-most pass that has been initialized. This
allows passes to implement one API in terms of another API and benefit
when some other pass above them in the stack has more precise results
for the second API.
The second step of this conversion is to create a pass that implements
the TargetTransformInfo analysis using the target-independent
abstractions in the code generator. This replaces the
ScalarTargetTransformImpl and VectorTargetTransformImpl classes in
lib/Target with a single pass in lib/CodeGen called
BasicTargetTransformInfo. This class actually provides most of the TTI
functionality, basing it upon the TargetLowering abstraction and other
information in the target independent code generator.
The third step of the conversion adds support to all TargetMachines to
register custom analysis passes. This allows building those passes with
access to TargetLowering or other target-specific classes, and it also
allows each target to customize the set of analysis passes desired in
the pass manager. The baseline LLVMTargetMachine implements this
interface to add the BasicTTI pass to the pass manager, and all of the
tools that want to support target-aware TTI passes call this routine on
whatever target machine they end up with to add the appropriate passes.
The fourth step of the conversion created target-specific TTI analysis
passes for the X86 and ARM backends. These passes contain the custom
logic that was previously in their extensions of the
ScalarTargetTransformInfo and VectorTargetTransformInfo interfaces.
I separated them into their own file, as now all of the interface bits
are private and they just expose a function to create the pass itself.
Then I extended these target machines to set up a custom set of analysis
passes, first adding BasicTTI as a fallback, and then adding their
customized TTI implementations.
The fourth step required logic that was shared between the target
independent layer and the specific targets to move to a different
interface, as they no longer derive from each other. As a consequence,
a helper functions were added to TargetLowering representing the common
logic needed both in the target implementation and the codegen
implementation of the TTI pass. While technically this is the only
change that could have been committed separately, it would have been
a nightmare to extract.
The final step of the conversion was just to delete all the old
boilerplate. This got rid of the ScalarTargetTransformInfo and
VectorTargetTransformInfo classes, all of the support in all of the
targets for producing instances of them, and all of the support in the
tools for manually constructing a pass based around them.
Now that TTI is a relatively normal analysis group, two things become
straightforward. First, we can sink it into lib/Analysis which is a more
natural layer for it to live. Second, clients of this interface can
depend on it *always* being available which will simplify their code and
behavior. These (and other) simplifications will follow in subsequent
commits, this one is clearly big enough.
Finally, I'm very aware that much of the comments and documentation
needs to be updated. As soon as I had this working, and plausibly well
commented, I wanted to get it committed and in front of the build bots.
I'll be doing a few passes over documentation later if it sticks.
Commits to update DragonEgg and Clang will be made presently.
llvm-svn: 171681
2013-01-07 09:37:14 +08:00
|
|
|
}
|
|
|
|
|
2006-09-04 12:14:57 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Pass Pipeline Configuration
|
|
|
|
//===----------------------------------------------------------------------===//
|
2003-08-06 00:34:44 +08:00
|
|
|
|
2012-02-03 13:12:41 +08:00
|
|
|
namespace {
|
2017-02-03 06:55:55 +08:00
|
|
|
|
2012-02-03 13:12:41 +08:00
|
|
|
/// X86 Code Generator Pass Configuration Options.
|
|
|
|
class X86PassConfig : public TargetPassConfig {
|
|
|
|
public:
|
2017-05-31 05:36:41 +08:00
|
|
|
X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
|
2012-02-04 10:56:59 +08:00
|
|
|
: TargetPassConfig(TM, PM) {}
|
2012-02-03 13:12:41 +08:00
|
|
|
|
|
|
|
X86TargetMachine &getX86TargetMachine() const {
|
|
|
|
return getTM<X86TargetMachine>();
|
|
|
|
}
|
|
|
|
|
2016-11-29 04:11:54 +08:00
|
|
|
ScheduleDAGInstrs *
|
|
|
|
createMachineScheduler(MachineSchedContext *C) const override {
|
|
|
|
ScheduleDAGMILive *DAG = createGenericSchedLive(C);
|
2017-02-01 10:54:34 +08:00
|
|
|
DAG->addMutation(createX86MacroFusionDAGMutation());
|
2016-11-29 04:11:54 +08:00
|
|
|
return DAG;
|
|
|
|
}
|
|
|
|
|
2014-07-02 02:53:31 +08:00
|
|
|
void addIRPasses() override;
|
2014-03-09 15:44:38 +08:00
|
|
|
bool addInstSelector() override;
|
2016-11-15 14:34:33 +08:00
|
|
|
bool addIRTranslator() override;
|
|
|
|
bool addLegalizeMachineIR() override;
|
|
|
|
bool addRegBankSelect() override;
|
|
|
|
bool addGlobalInstructionSelect() override;
|
2017-02-03 06:55:55 +08:00
|
|
|
bool addILPOpts() override;
|
2015-05-06 01:44:16 +08:00
|
|
|
bool addPreISel() override;
|
2017-10-22 19:43:08 +08:00
|
|
|
void addMachineSSAOptimization() override;
|
2015-02-02 00:56:04 +08:00
|
|
|
void addPreRegAlloc() override;
|
2014-12-12 05:26:47 +08:00
|
|
|
void addPostRegAlloc() override;
|
|
|
|
void addPreEmitPass() override;
|
Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..
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
llvm-svn: 323155
2018-01-23 06:05:25 +08:00
|
|
|
void addPreEmitPass2() override;
|
2015-05-23 02:10:47 +08:00
|
|
|
void addPreSched2() override;
|
2012-02-03 13:12:41 +08:00
|
|
|
};
|
2017-02-03 06:55:55 +08:00
|
|
|
|
2018-01-22 18:05:23 +08:00
|
|
|
class X86ExecutionDomainFix : public ExecutionDomainFix {
|
2017-03-18 13:08:58 +08:00
|
|
|
public:
|
|
|
|
static char ID;
|
2018-01-22 18:05:23 +08:00
|
|
|
X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
|
2017-03-18 13:08:58 +08:00
|
|
|
StringRef getPassName() const override {
|
|
|
|
return "X86 Execution Dependency Fix";
|
|
|
|
}
|
|
|
|
};
|
2018-01-22 18:05:23 +08:00
|
|
|
char X86ExecutionDomainFix::ID;
|
2017-03-18 13:08:58 +08:00
|
|
|
|
2017-02-03 06:55:55 +08:00
|
|
|
} // end anonymous namespace
|
2012-02-03 13:12:41 +08:00
|
|
|
|
2018-01-22 18:05:23 +08:00
|
|
|
INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
|
|
|
|
"X86 Execution Domain Fix", false, false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
|
|
|
|
INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
|
|
|
|
"X86 Execution Domain Fix", false, false)
|
2017-03-18 13:08:58 +08:00
|
|
|
|
2012-02-04 10:56:59 +08:00
|
|
|
TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
|
2017-05-31 05:36:41 +08:00
|
|
|
return new X86PassConfig(*this, PM);
|
2012-02-03 13:12:41 +08:00
|
|
|
}
|
|
|
|
|
2014-07-02 02:53:31 +08:00
|
|
|
void X86PassConfig::addIRPasses() {
|
2017-05-19 01:21:13 +08:00
|
|
|
addPass(createAtomicExpandPass());
|
2014-07-02 02:53:31 +08:00
|
|
|
|
|
|
|
TargetPassConfig::addIRPasses();
|
2016-10-15 02:20:41 +08:00
|
|
|
|
|
|
|
if (TM->getOptLevel() != CodeGenOpt::None)
|
2017-05-19 01:21:13 +08:00
|
|
|
addPass(createInterleavedAccessPass());
|
Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..
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
llvm-svn: 323155
2018-01-23 06:05:25 +08:00
|
|
|
|
|
|
|
// Add passes that handle indirect branch removal and insertion of a retpoline
|
|
|
|
// thunk. These will be a no-op unless a function subtarget has the retpoline
|
|
|
|
// feature enabled.
|
|
|
|
addPass(createIndirectBrExpandPass());
|
2014-07-02 02:53:31 +08:00
|
|
|
}
|
|
|
|
|
2012-02-03 13:12:41 +08:00
|
|
|
bool X86PassConfig::addInstSelector() {
|
2005-08-19 07:53:15 +08:00
|
|
|
// Install an instruction selector.
|
2012-07-03 03:48:31 +08:00
|
|
|
addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
|
2008-10-26 01:46:52 +08:00
|
|
|
|
2012-06-02 00:27:21 +08:00
|
|
|
// For ELF, cleanup any local-dynamic TLS accesses.
|
2015-06-16 23:44:21 +08:00
|
|
|
if (TM->getTargetTriple().isOSBinFormatELF() &&
|
2015-02-06 03:27:04 +08:00
|
|
|
getOptLevel() != CodeGenOpt::None)
|
2012-07-03 03:48:31 +08:00
|
|
|
addPass(createCleanupLocalDynamicTLSPass());
|
2012-06-02 00:27:21 +08:00
|
|
|
|
2014-05-22 09:46:02 +08:00
|
|
|
addPass(createX86GlobalBaseRegPass());
|
2006-09-04 12:14:57 +08:00
|
|
|
return false;
|
2013-01-17 08:58:38 +08:00
|
|
|
}
|
|
|
|
|
2016-11-15 14:34:33 +08:00
|
|
|
bool X86PassConfig::addIRTranslator() {
|
|
|
|
addPass(new IRTranslator());
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool X86PassConfig::addLegalizeMachineIR() {
|
2017-02-10 15:05:56 +08:00
|
|
|
addPass(new Legalizer());
|
2016-11-15 14:34:33 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool X86PassConfig::addRegBankSelect() {
|
2017-02-10 15:05:56 +08:00
|
|
|
addPass(new RegBankSelect());
|
2016-11-15 14:34:33 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool X86PassConfig::addGlobalInstructionSelect() {
|
2017-02-22 20:25:09 +08:00
|
|
|
addPass(new InstructionSelect());
|
2016-11-15 14:34:33 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-01-17 08:58:38 +08:00
|
|
|
bool X86PassConfig::addILPOpts() {
|
2014-05-22 07:40:26 +08:00
|
|
|
addPass(&EarlyIfConverterID);
|
2015-06-11 04:32:21 +08:00
|
|
|
if (EnableMachineCombinerPass)
|
|
|
|
addPass(&MachineCombinerID);
|
2017-07-17 01:39:56 +08:00
|
|
|
addPass(createX86CmovConverterPass());
|
2014-05-22 07:40:26 +08:00
|
|
|
return true;
|
2003-06-19 05:43:21 +08:00
|
|
|
}
|
|
|
|
|
2015-05-06 01:44:16 +08:00
|
|
|
bool X86PassConfig::addPreISel() {
|
2015-05-30 04:43:10 +08:00
|
|
|
// Only add this pass for 32-bit x86 Windows.
|
2015-06-16 23:44:21 +08:00
|
|
|
const Triple &TT = TM->getTargetTriple();
|
2015-05-30 04:43:10 +08:00
|
|
|
if (TT.isOSWindows() && TT.getArch() == Triple::x86)
|
2015-05-06 01:44:16 +08:00
|
|
|
addPass(createX86WinEHStatePass());
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-02-02 00:56:04 +08:00
|
|
|
void X86PassConfig::addPreRegAlloc() {
|
2016-07-12 04:40:44 +08:00
|
|
|
if (getOptLevel() != CodeGenOpt::None) {
|
Add LiveRangeShrink pass to shrink live range within BB.
Summary: LiveRangeShrink pass moves instruction right after the definition with the same BB if the instruction and its operands all have more than one use. This pass is inexpensive and guarantees optimal live-range within BB.
Reviewers: davidxl, wmi, hfinkel, MatzeB, andreadb
Reviewed By: MatzeB, andreadb
Subscribers: hiraditya, jyknight, sanjoy, skatkov, gberry, jholewinski, qcolombet, javed.absar, krytarowski, atrick, spatel, RKSimon, andreadb, MatzeB, mehdi_amini, mgorny, efriedma, davide, dberlin, llvm-commits
Differential Revision: https://reviews.llvm.org/D32563
llvm-svn: 304371
2017-06-01 07:25:25 +08:00
|
|
|
addPass(&LiveRangeShrinkID);
|
2016-07-14 23:07:44 +08:00
|
|
|
addPass(createX86FixupSetCC());
|
|
|
|
addPass(createX86OptimizeLEAs());
|
2016-07-14 23:40:22 +08:00
|
|
|
addPass(createX86CallFrameOptimization());
|
2018-04-02 21:48:28 +08:00
|
|
|
addPass(createX86AvoidStoreForwardingBlocks());
|
2016-07-12 04:40:44 +08:00
|
|
|
}
|
2015-12-04 18:53:15 +08:00
|
|
|
|
2016-05-19 00:10:17 +08:00
|
|
|
addPass(createX86WinAllocaExpander());
|
2015-02-02 00:56:04 +08:00
|
|
|
}
|
2017-10-22 19:43:08 +08:00
|
|
|
void X86PassConfig::addMachineSSAOptimization() {
|
|
|
|
addPass(createX86DomainReassignmentPass());
|
|
|
|
TargetPassConfig::addMachineSSAOptimization();
|
|
|
|
}
|
2015-02-02 00:56:04 +08:00
|
|
|
|
2014-12-12 05:26:47 +08:00
|
|
|
void X86PassConfig::addPostRegAlloc() {
|
2012-07-03 03:48:31 +08:00
|
|
|
addPass(createX86FloatingPointStackifierPass());
|
2006-09-04 12:14:57 +08:00
|
|
|
}
|
2003-01-13 08:51:23 +08:00
|
|
|
|
2015-05-23 02:10:47 +08:00
|
|
|
void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
|
|
|
|
|
2014-12-12 05:26:47 +08:00
|
|
|
void X86PassConfig::addPreEmitPass() {
|
2018-01-22 18:05:23 +08:00
|
|
|
if (getOptLevel() != CodeGenOpt::None) {
|
|
|
|
addPass(new X86ExecutionDomainFix());
|
2018-01-22 18:06:50 +08:00
|
|
|
addPass(createBreakFalseDeps());
|
2018-01-22 18:05:23 +08:00
|
|
|
}
|
2011-08-23 09:14:17 +08:00
|
|
|
|
2018-01-09 16:51:18 +08:00
|
|
|
addPass(createX86IndirectBranchTrackingPass());
|
|
|
|
|
2014-12-12 05:26:47 +08:00
|
|
|
if (UseVZeroUpper)
|
2014-12-12 07:18:03 +08:00
|
|
|
addPass(createX86IssueVZeroUpperPass());
|
2011-09-16 02:27:32 +08:00
|
|
|
|
2014-05-22 09:46:02 +08:00
|
|
|
if (getOptLevel() != CodeGenOpt::None) {
|
2016-02-12 03:43:04 +08:00
|
|
|
addPass(createX86FixupBWInsts());
|
2014-12-12 07:18:03 +08:00
|
|
|
addPass(createX86PadShortFunctions());
|
2013-04-26 04:29:37 +08:00
|
|
|
addPass(createX86FixupLEAs());
|
2016-12-28 18:12:48 +08:00
|
|
|
addPass(createX86EvexToVexInsts());
|
2013-04-26 04:29:37 +08:00
|
|
|
}
|
2010-03-26 01:25:00 +08:00
|
|
|
}
|
Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..
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
llvm-svn: 323155
2018-01-23 06:05:25 +08:00
|
|
|
|
|
|
|
void X86PassConfig::addPreEmitPass2() {
|
|
|
|
addPass(createX86RetpolineThunksPass());
|
|
|
|
}
|