1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the X86 specific subclass of TargetMachine.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86TargetMachine.h"
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 "X86TargetObjectFile.h"
21 #include "X86TargetTransformInfo.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/CodeGen/ExecutionDomainFix.h"
29 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
30 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
31 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
32 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
33 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
34 #include "llvm/CodeGen/MachineScheduler.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include <memory>
48 #include <string>
49 
50 using namespace llvm;
51 
52 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
53                                cl::desc("Enable the machine combiner pass"),
54                                cl::init(true), cl::Hidden);
55 
56 static cl::opt<bool> EnableCondBrFoldingPass("x86-condbr-folding",
57                                cl::desc("Enable the conditional branch "
58                                         "folding pass"),
59                                cl::init(false), cl::Hidden);
60 
61 extern "C" void LLVMInitializeX86Target() {
62   // Register the target.
63   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
64   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
65 
66   PassRegistry &PR = *PassRegistry::getPassRegistry();
67   initializeGlobalISel(PR);
68   initializeWinEHStatePassPass(PR);
69   initializeFixupBWInstPassPass(PR);
70   initializeEvexToVexInstPassPass(PR);
71   initializeFixupLEAPassPass(PR);
72   initializeX86CallFrameOptimizationPass(PR);
73   initializeX86CmovConverterPassPass(PR);
74   initializeX86ExecutionDomainFixPass(PR);
75   initializeX86DomainReassignmentPass(PR);
76   initializeX86AvoidSFBPassPass(PR);
77   initializeX86SpeculativeLoadHardeningPassPass(PR);
78   initializeX86FlagsCopyLoweringPassPass(PR);
79   initializeX86CondBrFoldingPassPass(PR);
80 }
81 
82 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
83   if (TT.isOSBinFormatMachO()) {
84     if (TT.getArch() == Triple::x86_64)
85       return llvm::make_unique<X86_64MachoTargetObjectFile>();
86     return llvm::make_unique<TargetLoweringObjectFileMachO>();
87   }
88 
89   if (TT.isOSFreeBSD())
90     return llvm::make_unique<X86FreeBSDTargetObjectFile>();
91   if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
92     return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
93   if (TT.isOSSolaris())
94     return llvm::make_unique<X86SolarisTargetObjectFile>();
95   if (TT.isOSFuchsia())
96     return llvm::make_unique<X86FuchsiaTargetObjectFile>();
97   if (TT.isOSBinFormatELF())
98     return llvm::make_unique<X86ELFTargetObjectFile>();
99   if (TT.isOSBinFormatCOFF())
100     return llvm::make_unique<TargetLoweringObjectFileCOFF>();
101   llvm_unreachable("unknown subtarget type");
102 }
103 
104 static std::string computeDataLayout(const Triple &TT) {
105   // X86 is little endian
106   std::string Ret = "e";
107 
108   Ret += DataLayout::getManglingComponent(TT);
109   // X86 and x32 have 32 bit pointers.
110   if ((TT.isArch64Bit() &&
111        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
112       !TT.isArch64Bit())
113     Ret += "-p:32:32";
114 
115   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
116   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
117     Ret += "-i64:64";
118   else if (TT.isOSIAMCU())
119     Ret += "-i64:32-f64:32";
120   else
121     Ret += "-f64:32:64";
122 
123   // Some ABIs align long double to 128 bits, others to 32.
124   if (TT.isOSNaCl() || TT.isOSIAMCU())
125     ; // No f80
126   else if (TT.isArch64Bit() || TT.isOSDarwin())
127     Ret += "-f80:128";
128   else
129     Ret += "-f80:32";
130 
131   if (TT.isOSIAMCU())
132     Ret += "-f128:32";
133 
134   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
135   if (TT.isArch64Bit())
136     Ret += "-n8:16:32:64";
137   else
138     Ret += "-n8:16:32";
139 
140   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
141   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
142     Ret += "-a:0:32-S32";
143   else
144     Ret += "-S128";
145 
146   return Ret;
147 }
148 
149 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
150                                            bool JIT,
151                                            Optional<Reloc::Model> RM) {
152   bool is64Bit = TT.getArch() == Triple::x86_64;
153   if (!RM.hasValue()) {
154     // JIT codegen should use static relocations by default, since it's
155     // typically executed in process and not relocatable.
156     if (JIT)
157       return Reloc::Static;
158 
159     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
160     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
161     // use static relocation model by default.
162     if (TT.isOSDarwin()) {
163       if (is64Bit)
164         return Reloc::PIC_;
165       return Reloc::DynamicNoPIC;
166     }
167     if (TT.isOSWindows() && is64Bit)
168       return Reloc::PIC_;
169     return Reloc::Static;
170   }
171 
172   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
173   // is defined as a model for code which may be used in static or dynamic
174   // executables but not necessarily a shared library. On X86-32 we just
175   // compile in -static mode, in x86-64 we use PIC.
176   if (*RM == Reloc::DynamicNoPIC) {
177     if (is64Bit)
178       return Reloc::PIC_;
179     if (!TT.isOSDarwin())
180       return Reloc::Static;
181   }
182 
183   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
184   // the Mach-O file format doesn't support it.
185   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
186     return Reloc::PIC_;
187 
188   return *RM;
189 }
190 
191 static CodeModel::Model getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,
192                                                  bool JIT, bool Is64Bit) {
193   if (CM) {
194     if (*CM == CodeModel::Tiny)
195       report_fatal_error("Target does not support the tiny CodeModel");
196     return *CM;
197   }
198   if (JIT)
199     return Is64Bit ? CodeModel::Large : CodeModel::Small;
200   return CodeModel::Small;
201 }
202 
203 /// Create an X86 target.
204 ///
205 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
206                                    StringRef CPU, StringRef FS,
207                                    const TargetOptions &Options,
208                                    Optional<Reloc::Model> RM,
209                                    Optional<CodeModel::Model> CM,
210                                    CodeGenOpt::Level OL, bool JIT)
211     : LLVMTargetMachine(
212           T, computeDataLayout(TT), TT, CPU, FS, Options,
213           getEffectiveRelocModel(TT, JIT, RM),
214           getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64),
215           OL),
216       TLOF(createTLOF(getTargetTriple())) {
217   // Windows stack unwinder gets confused when execution flow "falls through"
218   // after a call to 'noreturn' function.
219   // To prevent that, we emit a trap for 'unreachable' IR instructions.
220   // (which on X86, happens to be the 'ud2' instruction)
221   // On PS4, the "return address" of a 'noreturn' call must still be within
222   // the calling function, and TrapUnreachable is an easy way to get that.
223   // The check here for 64-bit windows is a bit icky, but as we're unlikely
224   // to ever want to mix 32 and 64-bit windows code in a single module
225   // this should be fine.
226   if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4() ||
227       TT.isOSBinFormatMachO()) {
228     this->Options.TrapUnreachable = true;
229     this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
230   }
231 
232   // Outlining is available for x86-64.
233   if (TT.getArch() == Triple::x86_64)
234     setMachineOutliner(true);
235 
236   initAsmInfo();
237 }
238 
239 X86TargetMachine::~X86TargetMachine() = default;
240 
241 const X86Subtarget *
242 X86TargetMachine::getSubtargetImpl(const Function &F) const {
243   Attribute CPUAttr = F.getFnAttribute("target-cpu");
244   Attribute FSAttr = F.getFnAttribute("target-features");
245 
246   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
247                       ? CPUAttr.getValueAsString()
248                       : (StringRef)TargetCPU;
249   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
250                      ? FSAttr.getValueAsString()
251                      : (StringRef)TargetFS;
252 
253   SmallString<512> Key;
254   Key.reserve(CPU.size() + FS.size());
255   Key += CPU;
256   Key += FS;
257 
258   // FIXME: This is related to the code below to reset the target options,
259   // we need to know whether or not the soft float flag is set on the
260   // function before we can generate a subtarget. We also need to use
261   // it as a key for the subtarget since that can be the only difference
262   // between two functions.
263   bool SoftFloat =
264       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
265   // If the soft float attribute is set on the function turn on the soft float
266   // subtarget feature.
267   if (SoftFloat)
268     Key += FS.empty() ? "+soft-float" : ",+soft-float";
269 
270   // Keep track of the key width after all features are added so we can extract
271   // the feature string out later.
272   unsigned CPUFSWidth = Key.size();
273 
274   // Extract prefer-vector-width attribute.
275   unsigned PreferVectorWidthOverride = 0;
276   if (F.hasFnAttribute("prefer-vector-width")) {
277     StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
278     unsigned Width;
279     if (!Val.getAsInteger(0, Width)) {
280       Key += ",prefer-vector-width=";
281       Key += Val;
282       PreferVectorWidthOverride = Width;
283     }
284   }
285 
286   // Extract min-legal-vector-width attribute.
287   unsigned RequiredVectorWidth = UINT32_MAX;
288   if (F.hasFnAttribute("min-legal-vector-width")) {
289     StringRef Val =
290         F.getFnAttribute("min-legal-vector-width").getValueAsString();
291     unsigned Width;
292     if (!Val.getAsInteger(0, Width)) {
293       Key += ",min-legal-vector-width=";
294       Key += Val;
295       RequiredVectorWidth = Width;
296     }
297   }
298 
299   // Extracted here so that we make sure there is backing for the StringRef. If
300   // we assigned earlier, its possible the SmallString reallocated leaving a
301   // dangling StringRef.
302   FS = Key.slice(CPU.size(), CPUFSWidth);
303 
304   auto &I = SubtargetMap[Key];
305   if (!I) {
306     // This needs to be done before we create a new subtarget since any
307     // creation will depend on the TM and the code generation flags on the
308     // function that reside in TargetOptions.
309     resetTargetOptions(F);
310     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
311                                         Options.StackAlignmentOverride,
312                                         PreferVectorWidthOverride,
313                                         RequiredVectorWidth);
314   }
315   return I.get();
316 }
317 
318 //===----------------------------------------------------------------------===//
319 // Command line options for x86
320 //===----------------------------------------------------------------------===//
321 static cl::opt<bool>
322 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
323   cl::desc("Minimize AVX to SSE transition penalty"),
324   cl::init(true));
325 
326 //===----------------------------------------------------------------------===//
327 // X86 TTI query.
328 //===----------------------------------------------------------------------===//
329 
330 TargetTransformInfo
331 X86TargetMachine::getTargetTransformInfo(const Function &F) {
332   return TargetTransformInfo(X86TTIImpl(this, F));
333 }
334 
335 //===----------------------------------------------------------------------===//
336 // Pass Pipeline Configuration
337 //===----------------------------------------------------------------------===//
338 
339 namespace {
340 
341 /// X86 Code Generator Pass Configuration Options.
342 class X86PassConfig : public TargetPassConfig {
343 public:
344   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
345     : TargetPassConfig(TM, PM) {}
346 
347   X86TargetMachine &getX86TargetMachine() const {
348     return getTM<X86TargetMachine>();
349   }
350 
351   ScheduleDAGInstrs *
352   createMachineScheduler(MachineSchedContext *C) const override {
353     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
354     DAG->addMutation(createX86MacroFusionDAGMutation());
355     return DAG;
356   }
357 
358   void addIRPasses() override;
359   bool addInstSelector() override;
360   bool addIRTranslator() override;
361   bool addLegalizeMachineIR() override;
362   bool addRegBankSelect() override;
363   bool addGlobalInstructionSelect() override;
364   bool addILPOpts() override;
365   bool addPreISel() override;
366   void addMachineSSAOptimization() override;
367   void addPreRegAlloc() override;
368   void addPostRegAlloc() override;
369   void addPreEmitPass() override;
370   void addPreEmitPass2() override;
371   void addPreSched2() override;
372 };
373 
374 class X86ExecutionDomainFix : public ExecutionDomainFix {
375 public:
376   static char ID;
377   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
378   StringRef getPassName() const override {
379     return "X86 Execution Dependency Fix";
380   }
381 };
382 char X86ExecutionDomainFix::ID;
383 
384 } // end anonymous namespace
385 
386 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
387   "X86 Execution Domain Fix", false, false)
388 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
389 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
390   "X86 Execution Domain Fix", false, false)
391 
392 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
393   return new X86PassConfig(*this, PM);
394 }
395 
396 void X86PassConfig::addIRPasses() {
397   addPass(createAtomicExpandPass());
398 
399   TargetPassConfig::addIRPasses();
400 
401   if (TM->getOptLevel() != CodeGenOpt::None)
402     addPass(createInterleavedAccessPass());
403 
404   // Add passes that handle indirect branch removal and insertion of a retpoline
405   // thunk. These will be a no-op unless a function subtarget has the retpoline
406   // feature enabled.
407   addPass(createIndirectBrExpandPass());
408 }
409 
410 bool X86PassConfig::addInstSelector() {
411   // Install an instruction selector.
412   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
413 
414   // For ELF, cleanup any local-dynamic TLS accesses.
415   if (TM->getTargetTriple().isOSBinFormatELF() &&
416       getOptLevel() != CodeGenOpt::None)
417     addPass(createCleanupLocalDynamicTLSPass());
418 
419   addPass(createX86GlobalBaseRegPass());
420   return false;
421 }
422 
423 bool X86PassConfig::addIRTranslator() {
424   addPass(new IRTranslator());
425   return false;
426 }
427 
428 bool X86PassConfig::addLegalizeMachineIR() {
429   addPass(new Legalizer());
430   return false;
431 }
432 
433 bool X86PassConfig::addRegBankSelect() {
434   addPass(new RegBankSelect());
435   return false;
436 }
437 
438 bool X86PassConfig::addGlobalInstructionSelect() {
439   addPass(new InstructionSelect());
440   return false;
441 }
442 
443 bool X86PassConfig::addILPOpts() {
444   if (EnableCondBrFoldingPass)
445     addPass(createX86CondBrFolding());
446   addPass(&EarlyIfConverterID);
447   if (EnableMachineCombinerPass)
448     addPass(&MachineCombinerID);
449   addPass(createX86CmovConverterPass());
450   return true;
451 }
452 
453 bool X86PassConfig::addPreISel() {
454   // Only add this pass for 32-bit x86 Windows.
455   const Triple &TT = TM->getTargetTriple();
456   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
457     addPass(createX86WinEHStatePass());
458   return true;
459 }
460 
461 void X86PassConfig::addPreRegAlloc() {
462   if (getOptLevel() != CodeGenOpt::None) {
463     addPass(&LiveRangeShrinkID);
464     addPass(createX86FixupSetCC());
465     addPass(createX86OptimizeLEAs());
466     addPass(createX86CallFrameOptimization());
467     addPass(createX86AvoidStoreForwardingBlocks());
468   }
469 
470   addPass(createX86SpeculativeLoadHardeningPass());
471   addPass(createX86FlagsCopyLoweringPass());
472   addPass(createX86WinAllocaExpander());
473 }
474 void X86PassConfig::addMachineSSAOptimization() {
475   addPass(createX86DomainReassignmentPass());
476   TargetPassConfig::addMachineSSAOptimization();
477 }
478 
479 void X86PassConfig::addPostRegAlloc() {
480   addPass(createX86FloatingPointStackifierPass());
481 }
482 
483 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
484 
485 void X86PassConfig::addPreEmitPass() {
486   if (getOptLevel() != CodeGenOpt::None) {
487     addPass(new X86ExecutionDomainFix());
488     addPass(createBreakFalseDeps());
489   }
490 
491   addPass(createX86IndirectBranchTrackingPass());
492 
493   if (UseVZeroUpper)
494     addPass(createX86IssueVZeroUpperPass());
495 
496   if (getOptLevel() != CodeGenOpt::None) {
497     addPass(createX86FixupBWInsts());
498     addPass(createX86PadShortFunctions());
499     addPass(createX86FixupLEAs());
500     addPass(createX86EvexToVexInsts());
501   }
502   addPass(createX86DiscriminateMemOpsPass());
503   addPass(createX86InsertPrefetchPass());
504 }
505 
506 void X86PassConfig::addPreEmitPass2() {
507   addPass(createX86RetpolineThunksPass());
508   // Verify basic block incoming and outgoing cfa offset and register values and
509   // correct CFA calculation rule where needed by inserting appropriate CFI
510   // instructions.
511   const Triple &TT = TM->getTargetTriple();
512   if (!TT.isOSDarwin() && !TT.isOSWindows())
513     addPass(createCFIInstrInserter());
514 }
515