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