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