1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the X86 specific subclass of TargetMachine.
12 //===----------------------------------------------------------------------===//
14 #include "MCTargetDesc/X86MCTargetDesc.h"
16 #include "X86CallLowering.h"
17 #include "X86LegalizerInfo.h"
18 #include "X86MacroFusion.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "X86TargetTransformInfo.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/ExecutionDepsFix.h"
30 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
31 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
32 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
33 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/MachineScheduler.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/TargetPassConfig.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetOptions.h"
53 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
54 cl::desc("Enable the machine combiner pass"),
55 cl::init(true), cl::Hidden);
59 void initializeWinEHStatePassPass(PassRegistry &);
60 void initializeFixupLEAPassPass(PassRegistry &);
61 void initializeX86ExecutionDepsFixPass(PassRegistry &);
63 } // end namespace llvm
65 extern "C" void LLVMInitializeX86Target() {
66 // Register the target.
67 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
68 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
70 PassRegistry &PR = *PassRegistry::getPassRegistry();
71 initializeGlobalISel(PR);
72 initializeWinEHStatePassPass(PR);
73 initializeFixupBWInstPassPass(PR);
74 initializeEvexToVexInstPassPass(PR);
75 initializeFixupLEAPassPass(PR);
76 initializeX86ExecutionDepsFixPass(PR);
79 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
80 if (TT.isOSBinFormatMachO()) {
81 if (TT.getArch() == Triple::x86_64)
82 return llvm::make_unique<X86_64MachoTargetObjectFile>();
83 return llvm::make_unique<TargetLoweringObjectFileMachO>();
87 return llvm::make_unique<X86FreeBSDTargetObjectFile>();
88 if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
89 return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
91 return llvm::make_unique<X86SolarisTargetObjectFile>();
93 return llvm::make_unique<X86FuchsiaTargetObjectFile>();
94 if (TT.isOSBinFormatELF())
95 return llvm::make_unique<X86ELFTargetObjectFile>();
96 if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
97 return llvm::make_unique<X86WindowsTargetObjectFile>();
98 if (TT.isOSBinFormatCOFF())
99 return llvm::make_unique<TargetLoweringObjectFileCOFF>();
100 llvm_unreachable("unknown subtarget type");
103 static std::string computeDataLayout(const Triple &TT) {
104 // X86 is little endian
105 std::string Ret = "e";
107 Ret += DataLayout::getManglingComponent(TT);
108 // X86 and x32 have 32 bit pointers.
109 if ((TT.isArch64Bit() &&
110 (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
114 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
115 if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
117 else if (TT.isOSIAMCU())
118 Ret += "-i64:32-f64:32";
122 // Some ABIs align long double to 128 bits, others to 32.
123 if (TT.isOSNaCl() || TT.isOSIAMCU())
125 else if (TT.isArch64Bit() || TT.isOSDarwin())
133 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
134 if (TT.isArch64Bit())
135 Ret += "-n8:16:32:64";
139 // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
140 if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
141 Ret += "-a:0:32-S32";
148 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
149 Optional<Reloc::Model> RM) {
150 bool is64Bit = TT.getArch() == Triple::x86_64;
151 if (!RM.hasValue()) {
152 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
153 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
154 // use static relocation model by default.
155 if (TT.isOSDarwin()) {
158 return Reloc::DynamicNoPIC;
160 if (TT.isOSWindows() && is64Bit)
162 return Reloc::Static;
165 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
166 // is defined as a model for code which may be used in static or dynamic
167 // executables but not necessarily a shared library. On X86-32 we just
168 // compile in -static mode, in x86-64 we use PIC.
169 if (*RM == Reloc::DynamicNoPIC) {
172 if (!TT.isOSDarwin())
173 return Reloc::Static;
176 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
177 // the Mach-O file format doesn't support it.
178 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
184 /// Create an X86 target.
186 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
187 StringRef CPU, StringRef FS,
188 const TargetOptions &Options,
189 Optional<Reloc::Model> RM,
190 CodeModel::Model CM, CodeGenOpt::Level OL)
191 : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
192 getEffectiveRelocModel(TT, RM), CM, OL),
193 TLOF(createTLOF(getTargetTriple())) {
194 // Windows stack unwinder gets confused when execution flow "falls through"
195 // after a call to 'noreturn' function.
196 // To prevent that, we emit a trap for 'unreachable' IR instructions.
197 // (which on X86, happens to be the 'ud2' instruction)
198 // On PS4, the "return address" of a 'noreturn' call must still be within
199 // the calling function, and TrapUnreachable is an easy way to get that.
200 // The check here for 64-bit windows is a bit icky, but as we're unlikely
201 // to ever want to mix 32 and 64-bit windows code in a single module
202 // this should be fine.
203 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
204 this->Options.TrapUnreachable = true;
209 X86TargetMachine::~X86TargetMachine() = default;
212 X86TargetMachine::getSubtargetImpl(const Function &F) const {
213 Attribute CPUAttr = F.getFnAttribute("target-cpu");
214 Attribute FSAttr = F.getFnAttribute("target-features");
216 StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
217 ? CPUAttr.getValueAsString()
218 : (StringRef)TargetCPU;
219 StringRef FS = !FSAttr.hasAttribute(Attribute::None)
220 ? FSAttr.getValueAsString()
221 : (StringRef)TargetFS;
223 SmallString<512> Key;
224 Key.reserve(CPU.size() + FS.size());
228 // FIXME: This is related to the code below to reset the target options,
229 // we need to know whether or not the soft float flag is set on the
230 // function before we can generate a subtarget. We also need to use
231 // it as a key for the subtarget since that can be the only difference
232 // between two functions.
234 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
235 // If the soft float attribute is set on the function turn on the soft float
236 // subtarget feature.
238 Key += FS.empty() ? "+soft-float" : ",+soft-float";
240 FS = Key.substr(CPU.size());
242 auto &I = SubtargetMap[Key];
244 // This needs to be done before we create a new subtarget since any
245 // creation will depend on the TM and the code generation flags on the
246 // function that reside in TargetOptions.
247 resetTargetOptions(F);
248 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
249 Options.StackAlignmentOverride);
254 //===----------------------------------------------------------------------===//
255 // Command line options for x86
256 //===----------------------------------------------------------------------===//
258 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
259 cl::desc("Minimize AVX to SSE transition penalty"),
262 //===----------------------------------------------------------------------===//
264 //===----------------------------------------------------------------------===//
266 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
267 return TargetIRAnalysis([this](const Function &F) {
268 return TargetTransformInfo(X86TTIImpl(this, F));
272 //===----------------------------------------------------------------------===//
273 // Pass Pipeline Configuration
274 //===----------------------------------------------------------------------===//
278 /// X86 Code Generator Pass Configuration Options.
279 class X86PassConfig : public TargetPassConfig {
281 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
282 : TargetPassConfig(TM, PM) {}
284 X86TargetMachine &getX86TargetMachine() const {
285 return getTM<X86TargetMachine>();
289 createMachineScheduler(MachineSchedContext *C) const override {
290 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
291 DAG->addMutation(createX86MacroFusionDAGMutation());
295 void addIRPasses() override;
296 bool addInstSelector() override;
297 #ifdef LLVM_BUILD_GLOBAL_ISEL
298 bool addIRTranslator() override;
299 bool addLegalizeMachineIR() override;
300 bool addRegBankSelect() override;
301 bool addGlobalInstructionSelect() override;
303 bool addILPOpts() override;
304 bool addPreISel() override;
305 void addPreRegAlloc() override;
306 void addPostRegAlloc() override;
307 void addPreEmitPass() override;
308 void addPreEmitPass2() override;
309 void addPreSched2() override;
312 class X86ExecutionDepsFix : public ExecutionDepsFix {
315 X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {}
316 StringRef getPassName() const override {
317 return "X86 Execution Dependency Fix";
320 char X86ExecutionDepsFix::ID;
322 } // end anonymous namespace
324 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix",
325 "X86 Execution Dependency Fix", false, false)
327 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
328 return new X86PassConfig(*this, PM);
331 void X86PassConfig::addIRPasses() {
332 addPass(createAtomicExpandPass());
334 TargetPassConfig::addIRPasses();
336 if (TM->getOptLevel() != CodeGenOpt::None)
337 addPass(createInterleavedAccessPass());
339 // Add passes that handle indirect branch removal and insertion of a retpoline
340 // thunk. These will be a no-op unless a function subtarget has the retpoline
342 addPass(createIndirectBrExpandPass());
345 bool X86PassConfig::addInstSelector() {
346 // Install an instruction selector.
347 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
349 // For ELF, cleanup any local-dynamic TLS accesses.
350 if (TM->getTargetTriple().isOSBinFormatELF() &&
351 getOptLevel() != CodeGenOpt::None)
352 addPass(createCleanupLocalDynamicTLSPass());
354 addPass(createX86GlobalBaseRegPass());
358 #ifdef LLVM_BUILD_GLOBAL_ISEL
359 bool X86PassConfig::addIRTranslator() {
360 addPass(new IRTranslator());
364 bool X86PassConfig::addLegalizeMachineIR() {
365 addPass(new Legalizer());
369 bool X86PassConfig::addRegBankSelect() {
370 addPass(new RegBankSelect());
374 bool X86PassConfig::addGlobalInstructionSelect() {
375 addPass(new InstructionSelect());
380 bool X86PassConfig::addILPOpts() {
381 addPass(&EarlyIfConverterID);
382 if (EnableMachineCombinerPass)
383 addPass(&MachineCombinerID);
384 addPass(createX86CmovConverterPass());
388 bool X86PassConfig::addPreISel() {
389 // Only add this pass for 32-bit x86 Windows.
390 const Triple &TT = TM->getTargetTriple();
391 if (TT.isOSWindows() && TT.getArch() == Triple::x86)
392 addPass(createX86WinEHStatePass());
396 void X86PassConfig::addPreRegAlloc() {
397 if (getOptLevel() != CodeGenOpt::None) {
398 addPass(&LiveRangeShrinkID);
399 addPass(createX86FixupSetCC());
400 addPass(createX86OptimizeLEAs());
401 addPass(createX86CallFrameOptimization());
404 addPass(createX86WinAllocaExpander());
407 void X86PassConfig::addPostRegAlloc() {
408 addPass(createX86FloatingPointStackifierPass());
411 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
413 void X86PassConfig::addPreEmitPass() {
414 if (getOptLevel() != CodeGenOpt::None)
415 addPass(new X86ExecutionDepsFix());
418 addPass(createX86IssueVZeroUpperPass());
420 if (getOptLevel() != CodeGenOpt::None) {
421 addPass(createX86FixupBWInsts());
422 addPass(createX86PadShortFunctions());
423 addPass(createX86FixupLEAs());
424 addPass(createX86EvexToVexInsts());
428 void X86PassConfig::addPreEmitPass2() {
429 addPass(createX86RetpolineThunksPass());