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