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"
15 #include "TargetInfo/X86TargetInfo.h"
17 #include "X86CallLowering.h"
18 #include "X86LegalizerInfo.h"
19 #include "X86MacroFusion.h"
20 #include "X86Subtarget.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/ExecutionDomainFix.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/MC/MCAsmInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/CFGuard.h"
55 static cl::opt
<bool> EnableMachineCombinerPass("x86-machine-combiner",
56 cl::desc("Enable the machine combiner pass"),
57 cl::init(true), cl::Hidden
);
59 extern "C" LLVM_EXTERNAL_VISIBILITY
void LLVMInitializeX86Target() {
60 // Register the target.
61 RegisterTargetMachine
<X86TargetMachine
> X(getTheX86_32Target());
62 RegisterTargetMachine
<X86TargetMachine
> Y(getTheX86_64Target());
64 PassRegistry
&PR
= *PassRegistry::getPassRegistry();
65 initializeX86LowerAMXIntrinsicsLegacyPassPass(PR
);
66 initializeX86LowerAMXTypeLegacyPassPass(PR
);
67 initializeX86PreAMXConfigPassPass(PR
);
68 initializeGlobalISel(PR
);
69 initializeWinEHStatePassPass(PR
);
70 initializeFixupBWInstPassPass(PR
);
71 initializeEvexToVexInstPassPass(PR
);
72 initializeFixupLEAPassPass(PR
);
73 initializeFPSPass(PR
);
74 initializeX86FixupSetCCPassPass(PR
);
75 initializeX86CallFrameOptimizationPass(PR
);
76 initializeX86CmovConverterPassPass(PR
);
77 initializeX86TileConfigPass(PR
);
78 initializeX86FastTileConfigPass(PR
);
79 initializeX86LowerTileCopyPass(PR
);
80 initializeX86ExpandPseudoPass(PR
);
81 initializeX86ExecutionDomainFixPass(PR
);
82 initializeX86DomainReassignmentPass(PR
);
83 initializeX86AvoidSFBPassPass(PR
);
84 initializeX86AvoidTrailingCallPassPass(PR
);
85 initializeX86SpeculativeLoadHardeningPassPass(PR
);
86 initializeX86SpeculativeExecutionSideEffectSuppressionPass(PR
);
87 initializeX86FlagsCopyLoweringPassPass(PR
);
88 initializeX86LoadValueInjectionLoadHardeningPassPass(PR
);
89 initializeX86LoadValueInjectionRetHardeningPassPass(PR
);
90 initializeX86OptimizeLEAPassPass(PR
);
91 initializeX86PartialReductionPass(PR
);
92 initializePseudoProbeInserterPass(PR
);
95 static std::unique_ptr
<TargetLoweringObjectFile
> createTLOF(const Triple
&TT
) {
96 if (TT
.isOSBinFormatMachO()) {
97 if (TT
.getArch() == Triple::x86_64
)
98 return std::make_unique
<X86_64MachoTargetObjectFile
>();
99 return std::make_unique
<TargetLoweringObjectFileMachO
>();
102 if (TT
.isOSBinFormatCOFF())
103 return std::make_unique
<TargetLoweringObjectFileCOFF
>();
104 return std::make_unique
<X86ELFTargetObjectFile
>();
107 static std::string
computeDataLayout(const Triple
&TT
) {
108 // X86 is little endian
109 std::string Ret
= "e";
111 Ret
+= DataLayout::getManglingComponent(TT
);
112 // X86 and x32 have 32 bit pointers.
113 if (!TT
.isArch64Bit() || TT
.isX32() || TT
.isOSNaCl())
116 // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
117 Ret
+= "-p270:32:32-p271:32:32-p272:64:64";
119 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
120 if (TT
.isArch64Bit() || TT
.isOSWindows() || TT
.isOSNaCl())
122 else if (TT
.isOSIAMCU())
123 Ret
+= "-i64:32-f64:32";
127 // Some ABIs align long double to 128 bits, others to 32.
128 if (TT
.isOSNaCl() || TT
.isOSIAMCU())
130 else if (TT
.isArch64Bit() || TT
.isOSDarwin())
138 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
139 if (TT
.isArch64Bit())
140 Ret
+= "-n8:16:32:64";
144 // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
145 if ((!TT
.isArch64Bit() && TT
.isOSWindows()) || TT
.isOSIAMCU())
146 Ret
+= "-a:0:32-S32";
153 static Reloc::Model
getEffectiveRelocModel(const Triple
&TT
,
155 Optional
<Reloc::Model
> RM
) {
156 bool is64Bit
= TT
.getArch() == Triple::x86_64
;
157 if (!RM
.hasValue()) {
158 // JIT codegen should use static relocations by default, since it's
159 // typically executed in process and not relocatable.
161 return Reloc::Static
;
163 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
164 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
165 // use static relocation model by default.
166 if (TT
.isOSDarwin()) {
169 return Reloc::DynamicNoPIC
;
171 if (TT
.isOSWindows() && is64Bit
)
173 return Reloc::Static
;
176 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
177 // is defined as a model for code which may be used in static or dynamic
178 // executables but not necessarily a shared library. On X86-32 we just
179 // compile in -static mode, in x86-64 we use PIC.
180 if (*RM
== Reloc::DynamicNoPIC
) {
183 if (!TT
.isOSDarwin())
184 return Reloc::Static
;
187 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
188 // the Mach-O file format doesn't support it.
189 if (*RM
== Reloc::Static
&& TT
.isOSDarwin() && is64Bit
)
195 static CodeModel::Model
getEffectiveX86CodeModel(Optional
<CodeModel::Model
> CM
,
196 bool JIT
, bool Is64Bit
) {
198 if (*CM
== CodeModel::Tiny
)
199 report_fatal_error("Target does not support the tiny CodeModel", false);
203 return Is64Bit
? CodeModel::Large
: CodeModel::Small
;
204 return CodeModel::Small
;
207 /// Create an X86 target.
209 X86TargetMachine::X86TargetMachine(const Target
&T
, const Triple
&TT
,
210 StringRef CPU
, StringRef FS
,
211 const TargetOptions
&Options
,
212 Optional
<Reloc::Model
> RM
,
213 Optional
<CodeModel::Model
> CM
,
214 CodeGenOpt::Level OL
, bool JIT
)
216 T
, computeDataLayout(TT
), TT
, CPU
, FS
, Options
,
217 getEffectiveRelocModel(TT
, JIT
, RM
),
218 getEffectiveX86CodeModel(CM
, JIT
, TT
.getArch() == Triple::x86_64
),
220 TLOF(createTLOF(getTargetTriple())), IsJIT(JIT
) {
221 // On PS4, the "return address" of a 'noreturn' call must still be within
222 // the calling function, and TrapUnreachable is an easy way to get that.
223 if (TT
.isPS4() || TT
.isOSBinFormatMachO()) {
224 this->Options
.TrapUnreachable
= true;
225 this->Options
.NoTrapAfterNoreturn
= TT
.isOSBinFormatMachO();
228 setMachineOutliner(true);
230 // x86 supports the debug entry values.
231 setSupportsDebugEntryValues(true);
236 X86TargetMachine::~X86TargetMachine() = default;
239 X86TargetMachine::getSubtargetImpl(const Function
&F
) const {
240 Attribute CPUAttr
= F
.getFnAttribute("target-cpu");
241 Attribute TuneAttr
= F
.getFnAttribute("tune-cpu");
242 Attribute FSAttr
= F
.getFnAttribute("target-features");
245 CPUAttr
.isValid() ? CPUAttr
.getValueAsString() : (StringRef
)TargetCPU
;
247 TuneAttr
.isValid() ? TuneAttr
.getValueAsString() : (StringRef
)CPU
;
249 FSAttr
.isValid() ? FSAttr
.getValueAsString() : (StringRef
)TargetFS
;
251 SmallString
<512> Key
;
252 // The additions here are ordered so that the definitely short strings are
253 // added first so we won't exceed the small size. We append the
254 // much longer FS string at the end so that we only heap allocate at most
257 // Extract prefer-vector-width attribute.
258 unsigned PreferVectorWidthOverride
= 0;
259 Attribute PreferVecWidthAttr
= F
.getFnAttribute("prefer-vector-width");
260 if (PreferVecWidthAttr
.isValid()) {
261 StringRef Val
= PreferVecWidthAttr
.getValueAsString();
263 if (!Val
.getAsInteger(0, Width
)) {
266 PreferVectorWidthOverride
= Width
;
270 // Extract min-legal-vector-width attribute.
271 unsigned RequiredVectorWidth
= UINT32_MAX
;
272 Attribute MinLegalVecWidthAttr
= F
.getFnAttribute("min-legal-vector-width");
273 if (MinLegalVecWidthAttr
.isValid()) {
274 StringRef Val
= MinLegalVecWidthAttr
.getValueAsString();
276 if (!Val
.getAsInteger(0, Width
)) {
279 RequiredVectorWidth
= Width
;
283 // Add CPU to the Key.
286 // Add tune CPU to the Key.
289 // Keep track of the start of the feature portion of the string.
290 unsigned FSStart
= Key
.size();
292 // FIXME: This is related to the code below to reset the target options,
293 // we need to know whether or not the soft float flag is set on the
294 // function before we can generate a subtarget. We also need to use
295 // it as a key for the subtarget since that can be the only difference
296 // between two functions.
297 bool SoftFloat
= F
.getFnAttribute("use-soft-float").getValueAsBool();
298 // If the soft float attribute is set on the function turn on the soft float
299 // subtarget feature.
301 Key
+= FS
.empty() ? "+soft-float" : "+soft-float,";
305 // We may have added +soft-float to the features so move the StringRef to
306 // point to the full string in the Key.
307 FS
= Key
.substr(FSStart
);
309 auto &I
= SubtargetMap
[Key
];
311 // This needs to be done before we create a new subtarget since any
312 // creation will depend on the TM and the code generation flags on the
313 // function that reside in TargetOptions.
314 resetTargetOptions(F
);
315 I
= std::make_unique
<X86Subtarget
>(
316 TargetTriple
, CPU
, TuneCPU
, FS
, *this,
317 MaybeAlign(F
.getParent()->getOverrideStackAlignment()),
318 PreferVectorWidthOverride
, RequiredVectorWidth
);
323 bool X86TargetMachine::isNoopAddrSpaceCast(unsigned SrcAS
,
324 unsigned DestAS
) const {
325 assert(SrcAS
!= DestAS
&& "Expected different address spaces!");
326 if (getPointerSize(SrcAS
) != getPointerSize(DestAS
))
328 return SrcAS
< 256 && DestAS
< 256;
331 //===----------------------------------------------------------------------===//
333 //===----------------------------------------------------------------------===//
336 X86TargetMachine::getTargetTransformInfo(const Function
&F
) {
337 return TargetTransformInfo(X86TTIImpl(this, F
));
340 //===----------------------------------------------------------------------===//
341 // Pass Pipeline Configuration
342 //===----------------------------------------------------------------------===//
346 /// X86 Code Generator Pass Configuration Options.
347 class X86PassConfig
: public TargetPassConfig
{
349 X86PassConfig(X86TargetMachine
&TM
, PassManagerBase
&PM
)
350 : TargetPassConfig(TM
, PM
) {}
352 X86TargetMachine
&getX86TargetMachine() const {
353 return getTM
<X86TargetMachine
>();
357 createMachineScheduler(MachineSchedContext
*C
) const override
{
358 ScheduleDAGMILive
*DAG
= createGenericSchedLive(C
);
359 DAG
->addMutation(createX86MacroFusionDAGMutation());
364 createPostMachineScheduler(MachineSchedContext
*C
) const override
{
365 ScheduleDAGMI
*DAG
= createGenericSchedPostRA(C
);
366 DAG
->addMutation(createX86MacroFusionDAGMutation());
370 void addIRPasses() override
;
371 bool addInstSelector() override
;
372 bool addIRTranslator() override
;
373 bool addLegalizeMachineIR() override
;
374 bool addRegBankSelect() override
;
375 bool addGlobalInstructionSelect() override
;
376 bool addILPOpts() override
;
377 bool addPreISel() override
;
378 void addMachineSSAOptimization() override
;
379 void addPreRegAlloc() override
;
380 bool addPostFastRegAllocRewrite() override
;
381 void addPostRegAlloc() override
;
382 void addPreEmitPass() override
;
383 void addPreEmitPass2() override
;
384 void addPreSched2() override
;
385 bool addPreRewrite() override
;
387 std::unique_ptr
<CSEConfigBase
> getCSEConfig() const override
;
390 class X86ExecutionDomainFix
: public ExecutionDomainFix
{
393 X86ExecutionDomainFix() : ExecutionDomainFix(ID
, X86::VR128XRegClass
) {}
394 StringRef
getPassName() const override
{
395 return "X86 Execution Dependency Fix";
398 char X86ExecutionDomainFix::ID
;
400 } // end anonymous namespace
402 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix
, "x86-execution-domain-fix",
403 "X86 Execution Domain Fix", false, false)
404 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis
)
405 INITIALIZE_PASS_END(X86ExecutionDomainFix
, "x86-execution-domain-fix",
406 "X86 Execution Domain Fix", false, false)
408 TargetPassConfig
*X86TargetMachine::createPassConfig(PassManagerBase
&PM
) {
409 return new X86PassConfig(*this, PM
);
412 void X86PassConfig::addIRPasses() {
413 addPass(createAtomicExpandPass());
415 // We add both pass anyway and when these two passes run, we skip the pass
416 // based on the option level and option attribute.
417 addPass(createX86LowerAMXIntrinsicsPass());
418 addPass(createX86LowerAMXTypePass());
420 if (TM
->getOptLevel() == CodeGenOpt::None
)
421 addPass(createX86PreAMXConfigPass());
423 TargetPassConfig::addIRPasses();
425 if (TM
->getOptLevel() != CodeGenOpt::None
) {
426 addPass(createInterleavedAccessPass());
427 addPass(createX86PartialReductionPass());
430 // Add passes that handle indirect branch removal and insertion of a retpoline
431 // thunk. These will be a no-op unless a function subtarget has the retpoline
433 addPass(createIndirectBrExpandPass());
435 // Add Control Flow Guard checks.
436 const Triple
&TT
= TM
->getTargetTriple();
437 if (TT
.isOSWindows()) {
438 if (TT
.getArch() == Triple::x86_64
) {
439 addPass(createCFGuardDispatchPass());
441 addPass(createCFGuardCheckPass());
446 bool X86PassConfig::addInstSelector() {
447 // Install an instruction selector.
448 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
450 // For ELF, cleanup any local-dynamic TLS accesses.
451 if (TM
->getTargetTriple().isOSBinFormatELF() &&
452 getOptLevel() != CodeGenOpt::None
)
453 addPass(createCleanupLocalDynamicTLSPass());
455 addPass(createX86GlobalBaseRegPass());
459 bool X86PassConfig::addIRTranslator() {
460 addPass(new IRTranslator(getOptLevel()));
464 bool X86PassConfig::addLegalizeMachineIR() {
465 addPass(new Legalizer());
469 bool X86PassConfig::addRegBankSelect() {
470 addPass(new RegBankSelect());
474 bool X86PassConfig::addGlobalInstructionSelect() {
475 addPass(new InstructionSelect(getOptLevel()));
479 bool X86PassConfig::addILPOpts() {
480 addPass(&EarlyIfConverterID
);
481 if (EnableMachineCombinerPass
)
482 addPass(&MachineCombinerID
);
483 addPass(createX86CmovConverterPass());
487 bool X86PassConfig::addPreISel() {
488 // Only add this pass for 32-bit x86 Windows.
489 const Triple
&TT
= TM
->getTargetTriple();
490 if (TT
.isOSWindows() && TT
.getArch() == Triple::x86
)
491 addPass(createX86WinEHStatePass());
495 void X86PassConfig::addPreRegAlloc() {
496 if (getOptLevel() != CodeGenOpt::None
) {
497 addPass(&LiveRangeShrinkID
);
498 addPass(createX86FixupSetCC());
499 addPass(createX86OptimizeLEAs());
500 addPass(createX86CallFrameOptimization());
501 addPass(createX86AvoidStoreForwardingBlocks());
504 addPass(createX86SpeculativeLoadHardeningPass());
505 addPass(createX86FlagsCopyLoweringPass());
506 addPass(createX86WinAllocaExpander());
508 if (getOptLevel() != CodeGenOpt::None
) {
509 addPass(createX86PreTileConfigPass());
513 void X86PassConfig::addMachineSSAOptimization() {
514 addPass(createX86DomainReassignmentPass());
515 TargetPassConfig::addMachineSSAOptimization();
518 void X86PassConfig::addPostRegAlloc() {
519 addPass(createX86LowerTileCopyPass());
520 addPass(createX86FloatingPointStackifierPass());
521 // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
522 // to using the Speculative Execution Side Effect Suppression pass for
523 // mitigation. This is to prevent slow downs due to
524 // analyses needed by the LVIHardening pass when compiling at -O0.
525 if (getOptLevel() != CodeGenOpt::None
)
526 addPass(createX86LoadValueInjectionLoadHardeningPass());
529 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
531 void X86PassConfig::addPreEmitPass() {
532 if (getOptLevel() != CodeGenOpt::None
) {
533 addPass(new X86ExecutionDomainFix());
534 addPass(createBreakFalseDeps());
537 addPass(createX86IndirectBranchTrackingPass());
539 addPass(createX86IssueVZeroUpperPass());
541 if (getOptLevel() != CodeGenOpt::None
) {
542 addPass(createX86FixupBWInsts());
543 addPass(createX86PadShortFunctions());
544 addPass(createX86FixupLEAs());
546 addPass(createX86EvexToVexInsts());
547 addPass(createX86DiscriminateMemOpsPass());
548 addPass(createX86InsertPrefetchPass());
549 addPass(createX86InsertX87waitPass());
552 void X86PassConfig::addPreEmitPass2() {
553 const Triple
&TT
= TM
->getTargetTriple();
554 const MCAsmInfo
*MAI
= TM
->getMCAsmInfo();
556 // The X86 Speculative Execution Pass must run after all control
557 // flow graph modifying passes. As a result it was listed to run right before
558 // the X86 Retpoline Thunks pass. The reason it must run after control flow
559 // graph modifications is that the model of LFENCE in LLVM has to be updated
560 // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
561 // placement of this pass was hand checked to ensure that the subsequent
562 // passes don't move the code around the LFENCEs in a way that will hurt the
563 // correctness of this pass. This placement has been shown to work based on
564 // hand inspection of the codegen output.
565 addPass(createX86SpeculativeExecutionSideEffectSuppression());
566 addPass(createX86IndirectThunksPass());
568 // Insert extra int3 instructions after trailing call instructions to avoid
569 // issues in the unwinder.
570 if (TT
.isOSWindows() && TT
.getArch() == Triple::x86_64
)
571 addPass(createX86AvoidTrailingCallPass());
573 // Verify basic block incoming and outgoing cfa offset and register values and
574 // correct CFA calculation rule where needed by inserting appropriate CFI
576 if (!TT
.isOSDarwin() &&
577 (!TT
.isOSWindows() ||
578 MAI
->getExceptionHandlingType() == ExceptionHandling::DwarfCFI
))
579 addPass(createCFIInstrInserter());
581 if (TT
.isOSWindows()) {
582 // Identify valid longjmp targets for Windows Control Flow Guard.
583 addPass(createCFGuardLongjmpPass());
584 // Identify valid eh continuation targets for Windows EHCont Guard.
585 addPass(createEHContGuardCatchretPass());
587 addPass(createX86LoadValueInjectionRetHardeningPass());
590 bool X86PassConfig::addPostFastRegAllocRewrite() {
591 addPass(createX86FastTileConfigPass());
595 bool X86PassConfig::addPreRewrite() {
596 addPass(createX86TileConfigPass());
600 std::unique_ptr
<CSEConfigBase
> X86PassConfig::getCSEConfig() const {
601 return getStandardCSEConfigForOpt(TM
->getOptLevel());