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/ExecutionDomainFix.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 initializeX86ExecutionDomainFixPass(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   initializeX86ExecutionDomainFixPass(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   // Extract prefer-vector-width attribute.
263   unsigned PreferVectorWidthOverride = 0;
264   if (F.hasFnAttribute("prefer-vector-width")) {
265     StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
266     unsigned Width;
267     if (!Val.getAsInteger(0, Width)) {
268       Key += ",prefer-vector-width=";
269       Key += Val;
270       PreferVectorWidthOverride = Width;
271     }
272   }
273 
274   // Extract required-vector-width attribute.
275   unsigned RequiredVectorWidth = UINT32_MAX;
276   if (F.hasFnAttribute("required-vector-width")) {
277     StringRef Val = F.getFnAttribute("required-vector-width").getValueAsString();
278     unsigned Width;
279     if (!Val.getAsInteger(0, Width)) {
280       Key += ",required-vector-width=";
281       Key += Val;
282       RequiredVectorWidth = Width;
283     }
284   }
285 
286   // Extracted here so that we make sure there is backing for the StringRef. If
287   // we assigned earlier, its possible the SmallString reallocated leaving a
288   // dangling StringRef.
289   FS = Key.slice(CPU.size(), CPUFSWidth);
290 
291   auto &I = SubtargetMap[Key];
292   if (!I) {
293     // This needs to be done before we create a new subtarget since any
294     // creation will depend on the TM and the code generation flags on the
295     // function that reside in TargetOptions.
296     resetTargetOptions(F);
297     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
298                                         Options.StackAlignmentOverride,
299                                         PreferVectorWidthOverride,
300                                         RequiredVectorWidth);
301   }
302   return I.get();
303 }
304 
305 //===----------------------------------------------------------------------===//
306 // Command line options for x86
307 //===----------------------------------------------------------------------===//
308 static cl::opt<bool>
309 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
310   cl::desc("Minimize AVX to SSE transition penalty"),
311   cl::init(true));
312 
313 //===----------------------------------------------------------------------===//
314 // X86 TTI query.
315 //===----------------------------------------------------------------------===//
316 
317 TargetTransformInfo
318 X86TargetMachine::getTargetTransformInfo(const Function &F) {
319   return TargetTransformInfo(X86TTIImpl(this, F));
320 }
321 
322 //===----------------------------------------------------------------------===//
323 // Pass Pipeline Configuration
324 //===----------------------------------------------------------------------===//
325 
326 namespace {
327 
328 /// X86 Code Generator Pass Configuration Options.
329 class X86PassConfig : public TargetPassConfig {
330 public:
331   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
332     : TargetPassConfig(TM, PM) {}
333 
334   X86TargetMachine &getX86TargetMachine() const {
335     return getTM<X86TargetMachine>();
336   }
337 
338   ScheduleDAGInstrs *
339   createMachineScheduler(MachineSchedContext *C) const override {
340     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
341     DAG->addMutation(createX86MacroFusionDAGMutation());
342     return DAG;
343   }
344 
345   void addIRPasses() override;
346   bool addInstSelector() override;
347   bool addIRTranslator() override;
348   bool addLegalizeMachineIR() override;
349   bool addRegBankSelect() override;
350   bool addGlobalInstructionSelect() override;
351   bool addILPOpts() override;
352   bool addPreISel() override;
353   void addMachineSSAOptimization() override;
354   void addPreRegAlloc() override;
355   void addPostRegAlloc() override;
356   void addPreEmitPass() override;
357   void addPreEmitPass2() override;
358   void addPreSched2() override;
359 };
360 
361 class X86ExecutionDomainFix : public ExecutionDomainFix {
362 public:
363   static char ID;
364   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
365   StringRef getPassName() const override {
366     return "X86 Execution Dependency Fix";
367   }
368 };
369 char X86ExecutionDomainFix::ID;
370 
371 } // end anonymous namespace
372 
373 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
374   "X86 Execution Domain Fix", false, false)
375 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
376 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
377   "X86 Execution Domain Fix", false, false)
378 
379 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
380   return new X86PassConfig(*this, PM);
381 }
382 
383 void X86PassConfig::addIRPasses() {
384   addPass(createAtomicExpandPass());
385 
386   TargetPassConfig::addIRPasses();
387 
388   if (TM->getOptLevel() != CodeGenOpt::None)
389     addPass(createInterleavedAccessPass());
390 
391   // Add passes that handle indirect branch removal and insertion of a retpoline
392   // thunk. These will be a no-op unless a function subtarget has the retpoline
393   // feature enabled.
394   addPass(createIndirectBrExpandPass());
395 }
396 
397 bool X86PassConfig::addInstSelector() {
398   // Install an instruction selector.
399   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
400 
401   // For ELF, cleanup any local-dynamic TLS accesses.
402   if (TM->getTargetTriple().isOSBinFormatELF() &&
403       getOptLevel() != CodeGenOpt::None)
404     addPass(createCleanupLocalDynamicTLSPass());
405 
406   addPass(createX86GlobalBaseRegPass());
407   return false;
408 }
409 
410 bool X86PassConfig::addIRTranslator() {
411   addPass(new IRTranslator());
412   return false;
413 }
414 
415 bool X86PassConfig::addLegalizeMachineIR() {
416   addPass(new Legalizer());
417   return false;
418 }
419 
420 bool X86PassConfig::addRegBankSelect() {
421   addPass(new RegBankSelect());
422   return false;
423 }
424 
425 bool X86PassConfig::addGlobalInstructionSelect() {
426   addPass(new InstructionSelect());
427   return false;
428 }
429 
430 bool X86PassConfig::addILPOpts() {
431   addPass(&EarlyIfConverterID);
432   if (EnableMachineCombinerPass)
433     addPass(&MachineCombinerID);
434   addPass(createX86CmovConverterPass());
435   return true;
436 }
437 
438 bool X86PassConfig::addPreISel() {
439   // Only add this pass for 32-bit x86 Windows.
440   const Triple &TT = TM->getTargetTriple();
441   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
442     addPass(createX86WinEHStatePass());
443   return true;
444 }
445 
446 void X86PassConfig::addPreRegAlloc() {
447   if (getOptLevel() != CodeGenOpt::None) {
448     addPass(&LiveRangeShrinkID);
449     addPass(createX86FixupSetCC());
450     addPass(createX86OptimizeLEAs());
451     addPass(createX86CallFrameOptimization());
452   }
453 
454   addPass(createX86WinAllocaExpander());
455 }
456 void X86PassConfig::addMachineSSAOptimization() {
457   addPass(createX86DomainReassignmentPass());
458   TargetPassConfig::addMachineSSAOptimization();
459 }
460 
461 void X86PassConfig::addPostRegAlloc() {
462   addPass(createX86FloatingPointStackifierPass());
463 }
464 
465 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
466 
467 void X86PassConfig::addPreEmitPass() {
468   if (getOptLevel() != CodeGenOpt::None) {
469     addPass(new X86ExecutionDomainFix());
470     addPass(createBreakFalseDeps());
471   }
472 
473   addPass(createX86IndirectBranchTrackingPass());
474 
475   if (UseVZeroUpper)
476     addPass(createX86IssueVZeroUpperPass());
477 
478   if (getOptLevel() != CodeGenOpt::None) {
479     addPass(createX86FixupBWInsts());
480     addPass(createX86PadShortFunctions());
481     addPass(createX86FixupLEAs());
482     addPass(createX86EvexToVexInsts());
483   }
484 }
485 
486 void X86PassConfig::addPreEmitPass2() {
487   addPass(createX86RetpolineThunksPass());
488 }
489