1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the X86 specific subclass of TargetMachine.
11 //===----------------------------------------------------------------------===//
13 #include "X86TargetMachine.h"
14 #include "MCTargetDesc/X86MCTargetDesc.h"
16 #include "X86CallLowering.h"
17 #include "X86LegalizerInfo.h"
18 #include "X86MacroFusion.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetObjectFile.h"
21 #include "X86TargetTransformInfo.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/CodeGen/ExecutionDomainFix.h"
29 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
30 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
33 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
34 #include "llvm/CodeGen/MachineScheduler.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetOptions.h"
52 static cl::opt
<bool> EnableMachineCombinerPass("x86-machine-combiner",
53 cl::desc("Enable the machine combiner pass"),
54 cl::init(true), cl::Hidden
);
56 static cl::opt
<bool> EnableCondBrFoldingPass("x86-condbr-folding",
57 cl::desc("Enable the conditional branch "
59 cl::init(false), cl::Hidden
);
61 extern "C" void LLVMInitializeX86Target() {
62 // Register the target.
63 RegisterTargetMachine
<X86TargetMachine
> X(getTheX86_32Target());
64 RegisterTargetMachine
<X86TargetMachine
> Y(getTheX86_64Target());
66 PassRegistry
&PR
= *PassRegistry::getPassRegistry();
67 initializeGlobalISel(PR
);
68 initializeWinEHStatePassPass(PR
);
69 initializeFixupBWInstPassPass(PR
);
70 initializeEvexToVexInstPassPass(PR
);
71 initializeFixupLEAPassPass(PR
);
72 initializeShadowCallStackPass(PR
);
73 initializeX86CallFrameOptimizationPass(PR
);
74 initializeX86CmovConverterPassPass(PR
);
75 initializeX86ExecutionDomainFixPass(PR
);
76 initializeX86DomainReassignmentPass(PR
);
77 initializeX86AvoidSFBPassPass(PR
);
78 initializeX86SpeculativeLoadHardeningPassPass(PR
);
79 initializeX86FlagsCopyLoweringPassPass(PR
);
80 initializeX86CondBrFoldingPassPass(PR
);
83 static std::unique_ptr
<TargetLoweringObjectFile
> createTLOF(const Triple
&TT
) {
84 if (TT
.isOSBinFormatMachO()) {
85 if (TT
.getArch() == Triple::x86_64
)
86 return llvm::make_unique
<X86_64MachoTargetObjectFile
>();
87 return llvm::make_unique
<TargetLoweringObjectFileMachO
>();
91 return llvm::make_unique
<X86FreeBSDTargetObjectFile
>();
92 if (TT
.isOSLinux() || TT
.isOSNaCl() || TT
.isOSIAMCU())
93 return llvm::make_unique
<X86LinuxNaClTargetObjectFile
>();
95 return llvm::make_unique
<X86SolarisTargetObjectFile
>();
97 return llvm::make_unique
<X86FuchsiaTargetObjectFile
>();
98 if (TT
.isOSBinFormatELF())
99 return llvm::make_unique
<X86ELFTargetObjectFile
>();
100 if (TT
.isOSBinFormatCOFF())
101 return llvm::make_unique
<TargetLoweringObjectFileCOFF
>();
102 llvm_unreachable("unknown subtarget type");
105 static std::string
computeDataLayout(const Triple
&TT
) {
106 // X86 is little endian
107 std::string Ret
= "e";
109 Ret
+= DataLayout::getManglingComponent(TT
);
110 // X86 and x32 have 32 bit pointers.
111 if ((TT
.isArch64Bit() &&
112 (TT
.getEnvironment() == Triple::GNUX32
|| TT
.isOSNaCl())) ||
116 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
117 if (TT
.isArch64Bit() || TT
.isOSWindows() || TT
.isOSNaCl())
119 else if (TT
.isOSIAMCU())
120 Ret
+= "-i64:32-f64:32";
124 // Some ABIs align long double to 128 bits, others to 32.
125 if (TT
.isOSNaCl() || TT
.isOSIAMCU())
127 else if (TT
.isArch64Bit() || TT
.isOSDarwin())
135 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
136 if (TT
.isArch64Bit())
137 Ret
+= "-n8:16:32:64";
141 // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
142 if ((!TT
.isArch64Bit() && TT
.isOSWindows()) || TT
.isOSIAMCU())
143 Ret
+= "-a:0:32-S32";
150 static Reloc::Model
getEffectiveRelocModel(const Triple
&TT
,
152 Optional
<Reloc::Model
> RM
) {
153 bool is64Bit
= TT
.getArch() == Triple::x86_64
;
154 if (!RM
.hasValue()) {
155 // JIT codegen should use static relocations by default, since it's
156 // typically executed in process and not relocatable.
158 return Reloc::Static
;
160 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
161 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
162 // use static relocation model by default.
163 if (TT
.isOSDarwin()) {
166 return Reloc::DynamicNoPIC
;
168 if (TT
.isOSWindows() && is64Bit
)
170 return Reloc::Static
;
173 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
174 // is defined as a model for code which may be used in static or dynamic
175 // executables but not necessarily a shared library. On X86-32 we just
176 // compile in -static mode, in x86-64 we use PIC.
177 if (*RM
== Reloc::DynamicNoPIC
) {
180 if (!TT
.isOSDarwin())
181 return Reloc::Static
;
184 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
185 // the Mach-O file format doesn't support it.
186 if (*RM
== Reloc::Static
&& TT
.isOSDarwin() && is64Bit
)
192 static CodeModel::Model
getEffectiveX86CodeModel(Optional
<CodeModel::Model
> CM
,
193 bool JIT
, bool Is64Bit
) {
195 if (*CM
== CodeModel::Tiny
)
196 report_fatal_error("Target does not support the tiny CodeModel");
200 return Is64Bit
? CodeModel::Large
: CodeModel::Small
;
201 return CodeModel::Small
;
204 /// Create an X86 target.
206 X86TargetMachine::X86TargetMachine(const Target
&T
, const Triple
&TT
,
207 StringRef CPU
, StringRef FS
,
208 const TargetOptions
&Options
,
209 Optional
<Reloc::Model
> RM
,
210 Optional
<CodeModel::Model
> CM
,
211 CodeGenOpt::Level OL
, bool JIT
)
213 T
, computeDataLayout(TT
), TT
, CPU
, FS
, Options
,
214 getEffectiveRelocModel(TT
, JIT
, RM
),
215 getEffectiveX86CodeModel(CM
, JIT
, TT
.getArch() == Triple::x86_64
),
217 TLOF(createTLOF(getTargetTriple())) {
218 // Windows stack unwinder gets confused when execution flow "falls through"
219 // after a call to 'noreturn' function.
220 // To prevent that, we emit a trap for 'unreachable' IR instructions.
221 // (which on X86, happens to be the 'ud2' instruction)
222 // On PS4, the "return address" of a 'noreturn' call must still be within
223 // the calling function, and TrapUnreachable is an easy way to get that.
224 // The check here for 64-bit windows is a bit icky, but as we're unlikely
225 // to ever want to mix 32 and 64-bit windows code in a single module
226 // this should be fine.
227 if ((TT
.isOSWindows() && TT
.getArch() == Triple::x86_64
) || TT
.isPS4() ||
228 TT
.isOSBinFormatMachO()) {
229 this->Options
.TrapUnreachable
= true;
230 this->Options
.NoTrapAfterNoreturn
= TT
.isOSBinFormatMachO();
233 // Outlining is available for x86-64.
234 if (TT
.getArch() == Triple::x86_64
)
235 setMachineOutliner(true);
240 X86TargetMachine::~X86TargetMachine() = default;
243 X86TargetMachine::getSubtargetImpl(const Function
&F
) const {
244 Attribute CPUAttr
= F
.getFnAttribute("target-cpu");
245 Attribute FSAttr
= F
.getFnAttribute("target-features");
247 StringRef CPU
= !CPUAttr
.hasAttribute(Attribute::None
)
248 ? CPUAttr
.getValueAsString()
249 : (StringRef
)TargetCPU
;
250 StringRef FS
= !FSAttr
.hasAttribute(Attribute::None
)
251 ? FSAttr
.getValueAsString()
252 : (StringRef
)TargetFS
;
254 SmallString
<512> Key
;
255 Key
.reserve(CPU
.size() + FS
.size());
259 // FIXME: This is related to the code below to reset the target options,
260 // we need to know whether or not the soft float flag is set on the
261 // function before we can generate a subtarget. We also need to use
262 // it as a key for the subtarget since that can be the only difference
263 // between two functions.
265 F
.getFnAttribute("use-soft-float").getValueAsString() == "true";
266 // If the soft float attribute is set on the function turn on the soft float
267 // subtarget feature.
269 Key
+= FS
.empty() ? "+soft-float" : ",+soft-float";
271 // Keep track of the key width after all features are added so we can extract
272 // the feature string out later.
273 unsigned CPUFSWidth
= Key
.size();
275 // Extract prefer-vector-width attribute.
276 unsigned PreferVectorWidthOverride
= 0;
277 if (F
.hasFnAttribute("prefer-vector-width")) {
278 StringRef Val
= F
.getFnAttribute("prefer-vector-width").getValueAsString();
280 if (!Val
.getAsInteger(0, Width
)) {
281 Key
+= ",prefer-vector-width=";
283 PreferVectorWidthOverride
= Width
;
287 // Extract min-legal-vector-width attribute.
288 unsigned RequiredVectorWidth
= UINT32_MAX
;
289 if (F
.hasFnAttribute("min-legal-vector-width")) {
291 F
.getFnAttribute("min-legal-vector-width").getValueAsString();
293 if (!Val
.getAsInteger(0, Width
)) {
294 Key
+= ",min-legal-vector-width=";
296 RequiredVectorWidth
= Width
;
300 // Extracted here so that we make sure there is backing for the StringRef. If
301 // we assigned earlier, its possible the SmallString reallocated leaving a
302 // dangling StringRef.
303 FS
= Key
.slice(CPU
.size(), CPUFSWidth
);
305 auto &I
= SubtargetMap
[Key
];
307 // This needs to be done before we create a new subtarget since any
308 // creation will depend on the TM and the code generation flags on the
309 // function that reside in TargetOptions.
310 resetTargetOptions(F
);
311 I
= llvm::make_unique
<X86Subtarget
>(TargetTriple
, CPU
, FS
, *this,
312 Options
.StackAlignmentOverride
,
313 PreferVectorWidthOverride
,
314 RequiredVectorWidth
);
319 //===----------------------------------------------------------------------===//
320 // Command line options for x86
321 //===----------------------------------------------------------------------===//
323 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden
,
324 cl::desc("Minimize AVX to SSE transition penalty"),
327 //===----------------------------------------------------------------------===//
329 //===----------------------------------------------------------------------===//
332 X86TargetMachine::getTargetTransformInfo(const Function
&F
) {
333 return TargetTransformInfo(X86TTIImpl(this, F
));
336 //===----------------------------------------------------------------------===//
337 // Pass Pipeline Configuration
338 //===----------------------------------------------------------------------===//
342 /// X86 Code Generator Pass Configuration Options.
343 class X86PassConfig
: public TargetPassConfig
{
345 X86PassConfig(X86TargetMachine
&TM
, PassManagerBase
&PM
)
346 : TargetPassConfig(TM
, PM
) {}
348 X86TargetMachine
&getX86TargetMachine() const {
349 return getTM
<X86TargetMachine
>();
353 createMachineScheduler(MachineSchedContext
*C
) const override
{
354 ScheduleDAGMILive
*DAG
= createGenericSchedLive(C
);
355 DAG
->addMutation(createX86MacroFusionDAGMutation());
359 void addIRPasses() override
;
360 bool addInstSelector() override
;
361 bool addIRTranslator() override
;
362 bool addLegalizeMachineIR() override
;
363 bool addRegBankSelect() override
;
364 bool addGlobalInstructionSelect() override
;
365 bool addILPOpts() override
;
366 bool addPreISel() override
;
367 void addMachineSSAOptimization() override
;
368 void addPreRegAlloc() override
;
369 void addPostRegAlloc() override
;
370 void addPreEmitPass() override
;
371 void addPreEmitPass2() override
;
372 void addPreSched2() override
;
375 class X86ExecutionDomainFix
: public ExecutionDomainFix
{
378 X86ExecutionDomainFix() : ExecutionDomainFix(ID
, X86::VR128XRegClass
) {}
379 StringRef
getPassName() const override
{
380 return "X86 Execution Dependency Fix";
383 char X86ExecutionDomainFix::ID
;
385 } // end anonymous namespace
387 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix
, "x86-execution-domain-fix",
388 "X86 Execution Domain Fix", false, false)
389 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis
)
390 INITIALIZE_PASS_END(X86ExecutionDomainFix
, "x86-execution-domain-fix",
391 "X86 Execution Domain Fix", false, false)
393 TargetPassConfig
*X86TargetMachine::createPassConfig(PassManagerBase
&PM
) {
394 return new X86PassConfig(*this, PM
);
397 void X86PassConfig::addIRPasses() {
398 addPass(createAtomicExpandPass());
400 TargetPassConfig::addIRPasses();
402 if (TM
->getOptLevel() != CodeGenOpt::None
)
403 addPass(createInterleavedAccessPass());
405 // Add passes that handle indirect branch removal and insertion of a retpoline
406 // thunk. These will be a no-op unless a function subtarget has the retpoline
408 addPass(createIndirectBrExpandPass());
411 bool X86PassConfig::addInstSelector() {
412 // Install an instruction selector.
413 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
415 // For ELF, cleanup any local-dynamic TLS accesses.
416 if (TM
->getTargetTriple().isOSBinFormatELF() &&
417 getOptLevel() != CodeGenOpt::None
)
418 addPass(createCleanupLocalDynamicTLSPass());
420 addPass(createX86GlobalBaseRegPass());
424 bool X86PassConfig::addIRTranslator() {
425 addPass(new IRTranslator());
429 bool X86PassConfig::addLegalizeMachineIR() {
430 addPass(new Legalizer());
434 bool X86PassConfig::addRegBankSelect() {
435 addPass(new RegBankSelect());
439 bool X86PassConfig::addGlobalInstructionSelect() {
440 addPass(new InstructionSelect());
444 bool X86PassConfig::addILPOpts() {
445 if (EnableCondBrFoldingPass
)
446 addPass(createX86CondBrFolding());
447 addPass(&EarlyIfConverterID
);
448 if (EnableMachineCombinerPass
)
449 addPass(&MachineCombinerID
);
450 addPass(createX86CmovConverterPass());
454 bool X86PassConfig::addPreISel() {
455 // Only add this pass for 32-bit x86 Windows.
456 const Triple
&TT
= TM
->getTargetTriple();
457 if (TT
.isOSWindows() && TT
.getArch() == Triple::x86
)
458 addPass(createX86WinEHStatePass());
462 void X86PassConfig::addPreRegAlloc() {
463 if (getOptLevel() != CodeGenOpt::None
) {
464 addPass(&LiveRangeShrinkID
);
465 addPass(createX86FixupSetCC());
466 addPass(createX86OptimizeLEAs());
467 addPass(createX86CallFrameOptimization());
468 addPass(createX86AvoidStoreForwardingBlocks());
471 addPass(createX86SpeculativeLoadHardeningPass());
472 addPass(createX86FlagsCopyLoweringPass());
473 addPass(createX86WinAllocaExpander());
475 void X86PassConfig::addMachineSSAOptimization() {
476 addPass(createX86DomainReassignmentPass());
477 TargetPassConfig::addMachineSSAOptimization();
480 void X86PassConfig::addPostRegAlloc() {
481 addPass(createX86FloatingPointStackifierPass());
484 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
486 void X86PassConfig::addPreEmitPass() {
487 if (getOptLevel() != CodeGenOpt::None
) {
488 addPass(new X86ExecutionDomainFix());
489 addPass(createBreakFalseDeps());
492 addPass(createShadowCallStackPass());
493 addPass(createX86IndirectBranchTrackingPass());
496 addPass(createX86IssueVZeroUpperPass());
498 if (getOptLevel() != CodeGenOpt::None
) {
499 addPass(createX86FixupBWInsts());
500 addPass(createX86PadShortFunctions());
501 addPass(createX86FixupLEAs());
502 addPass(createX86EvexToVexInsts());
504 addPass(createX86DiscriminateMemOpsPass());
505 addPass(createX86InsertPrefetchPass());
508 void X86PassConfig::addPreEmitPass2() {
509 addPass(createX86RetpolineThunksPass());
510 // Verify basic block incoming and outgoing cfa offset and register values and
511 // correct CFA calculation rule where needed by inserting appropriate CFI
513 const Triple
&TT
= TM
->getTargetTriple();
514 if (!TT
.isOSDarwin() && !TT
.isOSWindows())
515 addPass(createCFIInstrInserter());