1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the X86 specific subclass of TargetMachine.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86TargetMachine.h"
15 #include "X86.h"
16 #include "X86CallLowering.h"
17 #include "X86MacroFusion.h"
18 #include "X86TargetObjectFile.h"
19 #include "X86TargetTransformInfo.h"
20 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
21 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
22 #include "llvm/CodeGen/MachineScheduler.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/LegacyPassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Target/TargetOptions.h"
31 using namespace llvm;
32 
33 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
34                                cl::desc("Enable the machine combiner pass"),
35                                cl::init(true), cl::Hidden);
36 
37 namespace llvm {
38 void initializeWinEHStatePassPass(PassRegistry &);
39 }
40 
41 extern "C" void LLVMInitializeX86Target() {
42   // Register the target.
43   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
44   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
45 
46   PassRegistry &PR = *PassRegistry::getPassRegistry();
47   initializeGlobalISel(PR);
48   initializeWinEHStatePassPass(PR);
49   initializeFixupBWInstPassPass(PR);
50   initializeEvexToVexInstPassPass(PR);
51 }
52 
53 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
54   if (TT.isOSBinFormatMachO()) {
55     if (TT.getArch() == Triple::x86_64)
56       return make_unique<X86_64MachoTargetObjectFile>();
57     return make_unique<TargetLoweringObjectFileMachO>();
58   }
59 
60   if (TT.isOSFreeBSD())
61     return make_unique<X86FreeBSDTargetObjectFile>();
62   if (TT.isOSLinux() || TT.isOSNaCl())
63     return make_unique<X86LinuxNaClTargetObjectFile>();
64   if (TT.isOSFuchsia())
65     return make_unique<X86FuchsiaTargetObjectFile>();
66   if (TT.isOSBinFormatELF())
67     return make_unique<X86ELFTargetObjectFile>();
68   if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
69     return make_unique<X86WindowsTargetObjectFile>();
70   if (TT.isOSBinFormatCOFF())
71     return make_unique<TargetLoweringObjectFileCOFF>();
72   llvm_unreachable("unknown subtarget type");
73 }
74 
75 static std::string computeDataLayout(const Triple &TT) {
76   // X86 is little endian
77   std::string Ret = "e";
78 
79   Ret += DataLayout::getManglingComponent(TT);
80   // X86 and x32 have 32 bit pointers.
81   if ((TT.isArch64Bit() &&
82        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
83       !TT.isArch64Bit())
84     Ret += "-p:32:32";
85 
86   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
87   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
88     Ret += "-i64:64";
89   else if (TT.isOSIAMCU())
90     Ret += "-i64:32-f64:32";
91   else
92     Ret += "-f64:32:64";
93 
94   // Some ABIs align long double to 128 bits, others to 32.
95   if (TT.isOSNaCl() || TT.isOSIAMCU())
96     ; // No f80
97   else if (TT.isArch64Bit() || TT.isOSDarwin())
98     Ret += "-f80:128";
99   else
100     Ret += "-f80:32";
101 
102   if (TT.isOSIAMCU())
103     Ret += "-f128:32";
104 
105   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
106   if (TT.isArch64Bit())
107     Ret += "-n8:16:32:64";
108   else
109     Ret += "-n8:16:32";
110 
111   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
112   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
113     Ret += "-a:0:32-S32";
114   else
115     Ret += "-S128";
116 
117   return Ret;
118 }
119 
120 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
121                                            Optional<Reloc::Model> RM) {
122   bool is64Bit = TT.getArch() == Triple::x86_64;
123   if (!RM.hasValue()) {
124     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
125     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
126     // use static relocation model by default.
127     if (TT.isOSDarwin()) {
128       if (is64Bit)
129         return Reloc::PIC_;
130       return Reloc::DynamicNoPIC;
131     }
132     if (TT.isOSWindows() && is64Bit)
133       return Reloc::PIC_;
134     return Reloc::Static;
135   }
136 
137   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
138   // is defined as a model for code which may be used in static or dynamic
139   // executables but not necessarily a shared library. On X86-32 we just
140   // compile in -static mode, in x86-64 we use PIC.
141   if (*RM == Reloc::DynamicNoPIC) {
142     if (is64Bit)
143       return Reloc::PIC_;
144     if (!TT.isOSDarwin())
145       return Reloc::Static;
146   }
147 
148   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
149   // the Mach-O file format doesn't support it.
150   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
151     return Reloc::PIC_;
152 
153   return *RM;
154 }
155 
156 /// Create an X86 target.
157 ///
158 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
159                                    StringRef CPU, StringRef FS,
160                                    const TargetOptions &Options,
161                                    Optional<Reloc::Model> RM,
162                                    CodeModel::Model CM, CodeGenOpt::Level OL)
163     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
164                         getEffectiveRelocModel(TT, RM), CM, OL),
165       TLOF(createTLOF(getTargetTriple())) {
166   // Windows stack unwinder gets confused when execution flow "falls through"
167   // after a call to 'noreturn' function.
168   // To prevent that, we emit a trap for 'unreachable' IR instructions.
169   // (which on X86, happens to be the 'ud2' instruction)
170   // On PS4, the "return address" of a 'noreturn' call must still be within
171   // the calling function, and TrapUnreachable is an easy way to get that.
172   // The check here for 64-bit windows is a bit icky, but as we're unlikely
173   // to ever want to mix 32 and 64-bit windows code in a single module
174   // this should be fine.
175   if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
176     this->Options.TrapUnreachable = true;
177 
178   initAsmInfo();
179 }
180 
181 X86TargetMachine::~X86TargetMachine() {}
182 
183 #ifdef LLVM_BUILD_GLOBAL_ISEL
184 namespace {
185 struct X86GISelActualAccessor : public GISelAccessor {
186   std::unique_ptr<CallLowering> CL;
187   X86GISelActualAccessor(CallLowering* CL): CL(CL) {}
188   const CallLowering *getCallLowering() const override {
189     return CL.get();
190   }
191   const InstructionSelector *getInstructionSelector() const override {
192     //TODO: Implement
193     return nullptr;
194   }
195   const LegalizerInfo *getLegalizerInfo() const override {
196     //TODO: Implement
197     return nullptr;
198   }
199   const RegisterBankInfo *getRegBankInfo() const override {
200     //TODO: Implement
201     return nullptr;
202   }
203 };
204 } // End anonymous namespace.
205 #endif
206 const X86Subtarget *
207 X86TargetMachine::getSubtargetImpl(const Function &F) const {
208   Attribute CPUAttr = F.getFnAttribute("target-cpu");
209   Attribute FSAttr = F.getFnAttribute("target-features");
210 
211   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
212                       ? CPUAttr.getValueAsString()
213                       : (StringRef)TargetCPU;
214   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
215                      ? FSAttr.getValueAsString()
216                      : (StringRef)TargetFS;
217 
218   SmallString<512> Key;
219   Key.reserve(CPU.size() + FS.size());
220   Key += CPU;
221   Key += FS;
222 
223   // FIXME: This is related to the code below to reset the target options,
224   // we need to know whether or not the soft float flag is set on the
225   // function before we can generate a subtarget. We also need to use
226   // it as a key for the subtarget since that can be the only difference
227   // between two functions.
228   bool SoftFloat =
229       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
230   // If the soft float attribute is set on the function turn on the soft float
231   // subtarget feature.
232   if (SoftFloat)
233     Key += FS.empty() ? "+soft-float" : ",+soft-float";
234 
235   FS = Key.substr(CPU.size());
236 
237   auto &I = SubtargetMap[Key];
238   if (!I) {
239     // This needs to be done before we create a new subtarget since any
240     // creation will depend on the TM and the code generation flags on the
241     // function that reside in TargetOptions.
242     resetTargetOptions(F);
243     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
244                                         Options.StackAlignmentOverride);
245 #ifndef LLVM_BUILD_GLOBAL_ISEL
246     GISelAccessor *GISel = new GISelAccessor();
247 #else
248     X86GISelActualAccessor *GISel = new X86GISelActualAccessor(
249         new X86CallLowering(*I->getTargetLowering()));
250 #endif
251     I->setGISelAccessor(*GISel);
252   }
253   return I.get();
254 }
255 
256 //===----------------------------------------------------------------------===//
257 // Command line options for x86
258 //===----------------------------------------------------------------------===//
259 static cl::opt<bool>
260 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
261   cl::desc("Minimize AVX to SSE transition penalty"),
262   cl::init(true));
263 
264 //===----------------------------------------------------------------------===//
265 // X86 TTI query.
266 //===----------------------------------------------------------------------===//
267 
268 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
269   return TargetIRAnalysis([this](const Function &F) {
270     return TargetTransformInfo(X86TTIImpl(this, F));
271   });
272 }
273 
274 
275 //===----------------------------------------------------------------------===//
276 // Pass Pipeline Configuration
277 //===----------------------------------------------------------------------===//
278 
279 namespace {
280 /// X86 Code Generator Pass Configuration Options.
281 class X86PassConfig : public TargetPassConfig {
282 public:
283   X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM)
284     : TargetPassConfig(TM, PM) {}
285 
286   X86TargetMachine &getX86TargetMachine() const {
287     return getTM<X86TargetMachine>();
288   }
289 
290   ScheduleDAGInstrs *
291   createMachineScheduler(MachineSchedContext *C) const override {
292     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
293     DAG->addMutation(createX86MacroFusionDAGMutation());
294     return DAG;
295   }
296 
297   void addIRPasses() override;
298   bool addInstSelector() override;
299 #ifdef LLVM_BUILD_GLOBAL_ISEL
300   bool addIRTranslator() override;
301   bool addLegalizeMachineIR() override;
302   bool addRegBankSelect() override;
303   bool addGlobalInstructionSelect() override;
304 #endif
305 bool addILPOpts() override;
306   bool addPreISel() override;
307   void addPreRegAlloc() override;
308   void addPostRegAlloc() override;
309   void addPreEmitPass() override;
310   void addPreSched2() override;
311 };
312 } // namespace
313 
314 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
315   return new X86PassConfig(this, PM);
316 }
317 
318 void X86PassConfig::addIRPasses() {
319   addPass(createAtomicExpandPass(&getX86TargetMachine()));
320 
321   TargetPassConfig::addIRPasses();
322 
323   if (TM->getOptLevel() != CodeGenOpt::None)
324     addPass(createInterleavedAccessPass(TM));
325 }
326 
327 bool X86PassConfig::addInstSelector() {
328   // Install an instruction selector.
329   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
330 
331   // For ELF, cleanup any local-dynamic TLS accesses.
332   if (TM->getTargetTriple().isOSBinFormatELF() &&
333       getOptLevel() != CodeGenOpt::None)
334     addPass(createCleanupLocalDynamicTLSPass());
335 
336   addPass(createX86GlobalBaseRegPass());
337   return false;
338 }
339 
340 #ifdef LLVM_BUILD_GLOBAL_ISEL
341 bool X86PassConfig::addIRTranslator() {
342   addPass(new IRTranslator());
343   return false;
344 }
345 
346 bool X86PassConfig::addLegalizeMachineIR() {
347   //TODO: Implement
348   return false;
349 }
350 
351 bool X86PassConfig::addRegBankSelect() {
352   //TODO: Implement
353   return false;
354 }
355 
356 bool X86PassConfig::addGlobalInstructionSelect() {
357   //TODO: Implement
358   return false;
359 }
360 #endif
361 
362 bool X86PassConfig::addILPOpts() {
363   addPass(&EarlyIfConverterID);
364   if (EnableMachineCombinerPass)
365     addPass(&MachineCombinerID);
366   return true;
367 }
368 
369 bool X86PassConfig::addPreISel() {
370   // Only add this pass for 32-bit x86 Windows.
371   const Triple &TT = TM->getTargetTriple();
372   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
373     addPass(createX86WinEHStatePass());
374   return true;
375 }
376 
377 void X86PassConfig::addPreRegAlloc() {
378   if (getOptLevel() != CodeGenOpt::None) {
379     addPass(createX86FixupSetCC());
380     addPass(createX86OptimizeLEAs());
381     addPass(createX86CallFrameOptimization());
382   }
383 
384   addPass(createX86WinAllocaExpander());
385 }
386 
387 void X86PassConfig::addPostRegAlloc() {
388   addPass(createX86FloatingPointStackifierPass());
389 }
390 
391 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
392 
393 void X86PassConfig::addPreEmitPass() {
394   if (getOptLevel() != CodeGenOpt::None)
395     addPass(createExecutionDependencyFixPass(&X86::VR128XRegClass));
396 
397   if (UseVZeroUpper)
398     addPass(createX86IssueVZeroUpperPass());
399 
400   if (getOptLevel() != CodeGenOpt::None) {
401     addPass(createX86FixupBWInsts());
402     addPass(createX86PadShortFunctions());
403     addPass(createX86FixupLEAs());
404     addPass(createX86EvexToVexInsts());
405   }
406 }
407