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