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 #ifdef LLVM_BUILD_GLOBAL_ISEL
19 #include "X86RegisterBankInfo.h"
21 #include "X86MacroFusion.h"
22 #include "X86Subtarget.h"
23 #include "X86TargetMachine.h"
24 #include "X86TargetObjectFile.h"
25 #include "X86TargetTransformInfo.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/Analysis/TargetTransformInfo.h"
32 #include "llvm/CodeGen/ExecutionDepsFix.h"
33 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
34 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
35 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
36 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
37 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
38 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
39 #include "llvm/CodeGen/MachineScheduler.h"
40 #include "llvm/CodeGen/Passes.h"
41 #include "llvm/CodeGen/TargetPassConfig.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetOptions.h"
57 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
58 cl::desc("Enable the machine combiner pass"),
59 cl::init(true), cl::Hidden);
63 void initializeWinEHStatePassPass(PassRegistry &);
64 void initializeFixupLEAPassPass(PassRegistry &);
65 void initializeX86ExecutionDepsFixPass(PassRegistry &);
67 } // end namespace llvm
69 extern "C" void LLVMInitializeX86Target() {
70 // Register the target.
71 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
72 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
74 PassRegistry &PR = *PassRegistry::getPassRegistry();
75 initializeGlobalISel(PR);
76 initializeWinEHStatePassPass(PR);
77 initializeFixupBWInstPassPass(PR);
78 initializeEvexToVexInstPassPass(PR);
79 initializeFixupLEAPassPass(PR);
80 initializeX86ExecutionDepsFixPass(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<X86FuchsiaTargetObjectFile>();
96 if (TT.isOSBinFormatELF())
97 return llvm::make_unique<X86ELFTargetObjectFile>();
98 if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
99 return llvm::make_unique<X86WindowsTargetObjectFile>();
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,
151 Optional<Reloc::Model> RM) {
152 bool is64Bit = TT.getArch() == Triple::x86_64;
153 if (!RM.hasValue()) {
154 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
155 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
156 // use static relocation model by default.
157 if (TT.isOSDarwin()) {
160 return Reloc::DynamicNoPIC;
162 if (TT.isOSWindows() && is64Bit)
164 return Reloc::Static;
167 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
168 // is defined as a model for code which may be used in static or dynamic
169 // executables but not necessarily a shared library. On X86-32 we just
170 // compile in -static mode, in x86-64 we use PIC.
171 if (*RM == Reloc::DynamicNoPIC) {
174 if (!TT.isOSDarwin())
175 return Reloc::Static;
178 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
179 // the Mach-O file format doesn't support it.
180 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
186 /// Create an X86 target.
188 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
189 StringRef CPU, StringRef FS,
190 const TargetOptions &Options,
191 Optional<Reloc::Model> RM,
192 CodeModel::Model CM, CodeGenOpt::Level OL)
193 : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
194 getEffectiveRelocModel(TT, RM), CM, OL),
195 TLOF(createTLOF(getTargetTriple())) {
196 // Windows stack unwinder gets confused when execution flow "falls through"
197 // after a call to 'noreturn' function.
198 // To prevent that, we emit a trap for 'unreachable' IR instructions.
199 // (which on X86, happens to be the 'ud2' instruction)
200 // On PS4, the "return address" of a 'noreturn' call must still be within
201 // the calling function, and TrapUnreachable is an easy way to get that.
202 // The check here for 64-bit windows is a bit icky, but as we're unlikely
203 // to ever want to mix 32 and 64-bit windows code in a single module
204 // this should be fine.
205 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
206 this->Options.TrapUnreachable = true;
211 X86TargetMachine::~X86TargetMachine() = default;
213 #ifdef LLVM_BUILD_GLOBAL_ISEL
216 struct X86GISelActualAccessor : public GISelAccessor {
217 std::unique_ptr<CallLowering> CallLoweringInfo;
218 std::unique_ptr<LegalizerInfo> Legalizer;
219 std::unique_ptr<RegisterBankInfo> RegBankInfo;
220 std::unique_ptr<InstructionSelector> InstSelector;
222 const CallLowering *getCallLowering() const override {
223 return CallLoweringInfo.get();
226 const InstructionSelector *getInstructionSelector() const override {
227 return InstSelector.get();
230 const LegalizerInfo *getLegalizerInfo() const override {
231 return Legalizer.get();
234 const RegisterBankInfo *getRegBankInfo() const override {
235 return RegBankInfo.get();
239 } // end anonymous namespace
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 FS = Key.substr(CPU.size());
273 auto &I = SubtargetMap[Key];
275 // This needs to be done before we create a new subtarget since any
276 // creation will depend on the TM and the code generation flags on the
277 // function that reside in TargetOptions.
278 resetTargetOptions(F);
279 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
280 Options.StackAlignmentOverride);
281 #ifndef LLVM_BUILD_GLOBAL_ISEL
282 GISelAccessor *GISel = new GISelAccessor();
284 X86GISelActualAccessor *GISel = new X86GISelActualAccessor();
286 GISel->CallLoweringInfo.reset(new X86CallLowering(*I->getTargetLowering()));
287 GISel->Legalizer.reset(new X86LegalizerInfo(*I, *this));
289 auto *RBI = new X86RegisterBankInfo(*I->getRegisterInfo());
290 GISel->RegBankInfo.reset(RBI);
291 GISel->InstSelector.reset(createX86InstructionSelector(
294 I->setGISelAccessor(*GISel);
299 //===----------------------------------------------------------------------===//
300 // Command line options for x86
301 //===----------------------------------------------------------------------===//
303 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
304 cl::desc("Minimize AVX to SSE transition penalty"),
307 //===----------------------------------------------------------------------===//
309 //===----------------------------------------------------------------------===//
311 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
312 return TargetIRAnalysis([this](const Function &F) {
313 return TargetTransformInfo(X86TTIImpl(this, F));
317 //===----------------------------------------------------------------------===//
318 // Pass Pipeline Configuration
319 //===----------------------------------------------------------------------===//
323 /// X86 Code Generator Pass Configuration Options.
324 class X86PassConfig : public TargetPassConfig {
326 X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM)
327 : TargetPassConfig(TM, PM) {}
329 X86TargetMachine &getX86TargetMachine() const {
330 return getTM<X86TargetMachine>();
334 createMachineScheduler(MachineSchedContext *C) const override {
335 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
336 DAG->addMutation(createX86MacroFusionDAGMutation());
340 void addIRPasses() override;
341 bool addInstSelector() override;
342 #ifdef LLVM_BUILD_GLOBAL_ISEL
343 bool addIRTranslator() override;
344 bool addLegalizeMachineIR() override;
345 bool addRegBankSelect() override;
346 bool addGlobalInstructionSelect() override;
348 bool addILPOpts() override;
349 bool addPreISel() override;
350 void addPreRegAlloc() override;
351 void addPostRegAlloc() override;
352 void addPreEmitPass() override;
353 void addPreSched2() override;
356 class X86ExecutionDepsFix : public ExecutionDepsFix {
359 X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {}
360 StringRef getPassName() const override {
361 return "X86 Execution Dependency Fix";
364 char X86ExecutionDepsFix::ID;
366 } // end anonymous namespace
368 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix",
369 "X86 Execution Dependency Fix", false, false)
371 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
372 return new X86PassConfig(this, PM);
375 void X86PassConfig::addIRPasses() {
376 addPass(createAtomicExpandPass());
378 TargetPassConfig::addIRPasses();
380 if (TM->getOptLevel() != CodeGenOpt::None)
381 addPass(createInterleavedAccessPass());
384 bool X86PassConfig::addInstSelector() {
385 // Install an instruction selector.
386 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
388 // For ELF, cleanup any local-dynamic TLS accesses.
389 if (TM->getTargetTriple().isOSBinFormatELF() &&
390 getOptLevel() != CodeGenOpt::None)
391 addPass(createCleanupLocalDynamicTLSPass());
393 addPass(createX86GlobalBaseRegPass());
397 #ifdef LLVM_BUILD_GLOBAL_ISEL
398 bool X86PassConfig::addIRTranslator() {
399 addPass(new IRTranslator());
403 bool X86PassConfig::addLegalizeMachineIR() {
404 addPass(new Legalizer());
408 bool X86PassConfig::addRegBankSelect() {
409 addPass(new RegBankSelect());
413 bool X86PassConfig::addGlobalInstructionSelect() {
414 addPass(new InstructionSelect());
419 bool X86PassConfig::addILPOpts() {
420 addPass(&EarlyIfConverterID);
421 if (EnableMachineCombinerPass)
422 addPass(&MachineCombinerID);
426 bool X86PassConfig::addPreISel() {
427 // Only add this pass for 32-bit x86 Windows.
428 const Triple &TT = TM->getTargetTriple();
429 if (TT.isOSWindows() && TT.getArch() == Triple::x86)
430 addPass(createX86WinEHStatePass());
434 void X86PassConfig::addPreRegAlloc() {
435 if (getOptLevel() != CodeGenOpt::None) {
436 addPass(createX86FixupSetCC());
437 addPass(createX86OptimizeLEAs());
438 addPass(createX86CallFrameOptimization());
441 addPass(createX86WinAllocaExpander());
444 void X86PassConfig::addPostRegAlloc() {
445 addPass(createX86FloatingPointStackifierPass());
448 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
450 void X86PassConfig::addPreEmitPass() {
451 if (getOptLevel() != CodeGenOpt::None)
452 addPass(new X86ExecutionDepsFix());
455 addPass(createX86IssueVZeroUpperPass());
457 if (getOptLevel() != CodeGenOpt::None) {
458 addPass(createX86FixupBWInsts());
459 addPass(createX86PadShortFunctions());
460 addPass(createX86FixupLEAs());
461 addPass(createX86EvexToVexInsts());