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 "TargetInfo/X86TargetInfo.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/TargetPassConfig.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/MC/MCAsmInfo.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/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/CFGuard.h"
50 #include <memory>
51 #include <string>
52 
53 using namespace llvm;
54 
55 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
56                                cl::desc("Enable the machine combiner pass"),
57                                cl::init(true), cl::Hidden);
58 
59 static cl::opt<bool> EnableCondBrFoldingPass("x86-condbr-folding",
60                                cl::desc("Enable the conditional branch "
61                                         "folding pass"),
62                                cl::init(false), cl::Hidden);
63 
64 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86Target() {
65   // Register the target.
66   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
67   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
68 
69   PassRegistry &PR = *PassRegistry::getPassRegistry();
70   initializeGlobalISel(PR);
71   initializeWinEHStatePassPass(PR);
72   initializeFixupBWInstPassPass(PR);
73   initializeEvexToVexInstPassPass(PR);
74   initializeFixupLEAPassPass(PR);
75   initializeFPSPass(PR);
76   initializeX86CallFrameOptimizationPass(PR);
77   initializeX86CmovConverterPassPass(PR);
78   initializeX86ExpandPseudoPass(PR);
79   initializeX86ExecutionDomainFixPass(PR);
80   initializeX86DomainReassignmentPass(PR);
81   initializeX86AvoidSFBPassPass(PR);
82   initializeX86AvoidTrailingCallPassPass(PR);
83   initializeX86SpeculativeLoadHardeningPassPass(PR);
84   initializeX86FlagsCopyLoweringPassPass(PR);
85   initializeX86CondBrFoldingPassPass(PR);
86   initializeX86LoadValueInjectionRetHardeningPassPass(PR);
87   initializeX86OptimizeLEAPassPass(PR);
88   initializeX86PartialReductionPass(PR);
89 }
90 
91 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
92   if (TT.isOSBinFormatMachO()) {
93     if (TT.getArch() == Triple::x86_64)
94       return std::make_unique<X86_64MachoTargetObjectFile>();
95     return std::make_unique<TargetLoweringObjectFileMachO>();
96   }
97 
98   if (TT.isOSBinFormatCOFF())
99     return std::make_unique<TargetLoweringObjectFileCOFF>();
100   return std::make_unique<X86ELFTargetObjectFile>();
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   // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
115   Ret += "-p270:32:32-p271:32:32-p272:64:64";
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", false);
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())), IsJIT(JIT) {
219   // On PS4, the "return address" of a 'noreturn' call must still be within
220   // the calling function, and TrapUnreachable is an easy way to get that.
221   if (TT.isPS4() || TT.isOSBinFormatMachO()) {
222     this->Options.TrapUnreachable = true;
223     this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
224   }
225 
226   setMachineOutliner(true);
227 
228   // x86 supports the debug entry values.
229   setSupportsDebugEntryValues(true);
230 
231   initAsmInfo();
232 }
233 
234 X86TargetMachine::~X86TargetMachine() = default;
235 
236 const X86Subtarget *
237 X86TargetMachine::getSubtargetImpl(const Function &F) const {
238   Attribute CPUAttr = F.getFnAttribute("target-cpu");
239   Attribute FSAttr = F.getFnAttribute("target-features");
240 
241   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
242                       ? CPUAttr.getValueAsString()
243                       : (StringRef)TargetCPU;
244   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
245                      ? FSAttr.getValueAsString()
246                      : (StringRef)TargetFS;
247 
248   SmallString<512> Key;
249   Key.reserve(CPU.size() + FS.size());
250   Key += CPU;
251   Key += FS;
252 
253   // FIXME: This is related to the code below to reset the target options,
254   // we need to know whether or not the soft float flag is set on the
255   // function before we can generate a subtarget. We also need to use
256   // it as a key for the subtarget since that can be the only difference
257   // between two functions.
258   bool SoftFloat =
259       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
260   // If the soft float attribute is set on the function turn on the soft float
261   // subtarget feature.
262   if (SoftFloat)
263     Key += FS.empty() ? "+soft-float" : ",+soft-float";
264 
265   // Keep track of the key width after all features are added so we can extract
266   // the feature string out later.
267   unsigned CPUFSWidth = Key.size();
268 
269   // Extract prefer-vector-width attribute.
270   unsigned PreferVectorWidthOverride = 0;
271   if (F.hasFnAttribute("prefer-vector-width")) {
272     StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
273     unsigned Width;
274     if (!Val.getAsInteger(0, Width)) {
275       Key += ",prefer-vector-width=";
276       Key += Val;
277       PreferVectorWidthOverride = Width;
278     }
279   }
280 
281   // Extract min-legal-vector-width attribute.
282   unsigned RequiredVectorWidth = UINT32_MAX;
283   if (F.hasFnAttribute("min-legal-vector-width")) {
284     StringRef Val =
285         F.getFnAttribute("min-legal-vector-width").getValueAsString();
286     unsigned Width;
287     if (!Val.getAsInteger(0, Width)) {
288       Key += ",min-legal-vector-width=";
289       Key += Val;
290       RequiredVectorWidth = Width;
291     }
292   }
293 
294   // Extracted here so that we make sure there is backing for the StringRef. If
295   // we assigned earlier, its possible the SmallString reallocated leaving a
296   // dangling StringRef.
297   FS = Key.slice(CPU.size(), CPUFSWidth);
298 
299   auto &I = SubtargetMap[Key];
300   if (!I) {
301     // This needs to be done before we create a new subtarget since any
302     // creation will depend on the TM and the code generation flags on the
303     // function that reside in TargetOptions.
304     resetTargetOptions(F);
305     I = std::make_unique<X86Subtarget>(
306         TargetTriple, CPU, FS, *this,
307         MaybeAlign(Options.StackAlignmentOverride), PreferVectorWidthOverride,
308         RequiredVectorWidth);
309   }
310   return I.get();
311 }
312 
313 //===----------------------------------------------------------------------===//
314 // Command line options for x86
315 //===----------------------------------------------------------------------===//
316 static cl::opt<bool>
317 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
318   cl::desc("Minimize AVX to SSE transition penalty"),
319   cl::init(true));
320 
321 //===----------------------------------------------------------------------===//
322 // X86 TTI query.
323 //===----------------------------------------------------------------------===//
324 
325 TargetTransformInfo
326 X86TargetMachine::getTargetTransformInfo(const Function &F) {
327   return TargetTransformInfo(X86TTIImpl(this, F));
328 }
329 
330 //===----------------------------------------------------------------------===//
331 // Pass Pipeline Configuration
332 //===----------------------------------------------------------------------===//
333 
334 namespace {
335 
336 /// X86 Code Generator Pass Configuration Options.
337 class X86PassConfig : public TargetPassConfig {
338 public:
339   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
340     : TargetPassConfig(TM, PM) {}
341 
342   X86TargetMachine &getX86TargetMachine() const {
343     return getTM<X86TargetMachine>();
344   }
345 
346   ScheduleDAGInstrs *
347   createMachineScheduler(MachineSchedContext *C) const override {
348     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
349     DAG->addMutation(createX86MacroFusionDAGMutation());
350     return DAG;
351   }
352 
353   ScheduleDAGInstrs *
354   createPostMachineScheduler(MachineSchedContext *C) const override {
355     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
356     DAG->addMutation(createX86MacroFusionDAGMutation());
357     return DAG;
358   }
359 
360   void addIRPasses() override;
361   bool addInstSelector() override;
362   bool addIRTranslator() override;
363   bool addLegalizeMachineIR() override;
364   bool addRegBankSelect() override;
365   bool addGlobalInstructionSelect() override;
366   bool addILPOpts() override;
367   bool addPreISel() override;
368   void addMachineSSAOptimization() override;
369   void addPreRegAlloc() override;
370   void addPostRegAlloc() override;
371   void addPreEmitPass() override;
372   void addPreEmitPass2() override;
373   void addPreSched2() override;
374 
375   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
376 };
377 
378 class X86ExecutionDomainFix : public ExecutionDomainFix {
379 public:
380   static char ID;
381   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
382   StringRef getPassName() const override {
383     return "X86 Execution Dependency Fix";
384   }
385 };
386 char X86ExecutionDomainFix::ID;
387 
388 } // end anonymous namespace
389 
390 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
391   "X86 Execution Domain Fix", false, false)
392 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
393 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
394   "X86 Execution Domain Fix", false, false)
395 
396 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
397   return new X86PassConfig(*this, PM);
398 }
399 
400 void X86PassConfig::addIRPasses() {
401   addPass(createAtomicExpandPass());
402 
403   TargetPassConfig::addIRPasses();
404 
405   if (TM->getOptLevel() != CodeGenOpt::None) {
406     addPass(createInterleavedAccessPass());
407     addPass(createX86PartialReductionPass());
408   }
409 
410   // Add passes that handle indirect branch removal and insertion of a retpoline
411   // thunk. These will be a no-op unless a function subtarget has the retpoline
412   // feature enabled.
413   addPass(createIndirectBrExpandPass());
414 
415   // Add Control Flow Guard checks.
416   const Triple &TT = TM->getTargetTriple();
417   if (TT.isOSWindows()) {
418     if (TT.getArch() == Triple::x86_64) {
419       addPass(createCFGuardDispatchPass());
420     } else {
421       addPass(createCFGuardCheckPass());
422     }
423   }
424 }
425 
426 bool X86PassConfig::addInstSelector() {
427   // Install an instruction selector.
428   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
429 
430   // For ELF, cleanup any local-dynamic TLS accesses.
431   if (TM->getTargetTriple().isOSBinFormatELF() &&
432       getOptLevel() != CodeGenOpt::None)
433     addPass(createCleanupLocalDynamicTLSPass());
434 
435   addPass(createX86GlobalBaseRegPass());
436   return false;
437 }
438 
439 bool X86PassConfig::addIRTranslator() {
440   addPass(new IRTranslator());
441   return false;
442 }
443 
444 bool X86PassConfig::addLegalizeMachineIR() {
445   addPass(new Legalizer());
446   return false;
447 }
448 
449 bool X86PassConfig::addRegBankSelect() {
450   addPass(new RegBankSelect());
451   return false;
452 }
453 
454 bool X86PassConfig::addGlobalInstructionSelect() {
455   addPass(new InstructionSelect());
456   return false;
457 }
458 
459 bool X86PassConfig::addILPOpts() {
460   if (EnableCondBrFoldingPass)
461     addPass(createX86CondBrFolding());
462   addPass(&EarlyIfConverterID);
463   if (EnableMachineCombinerPass)
464     addPass(&MachineCombinerID);
465   addPass(createX86CmovConverterPass());
466   return true;
467 }
468 
469 bool X86PassConfig::addPreISel() {
470   // Only add this pass for 32-bit x86 Windows.
471   const Triple &TT = TM->getTargetTriple();
472   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
473     addPass(createX86WinEHStatePass());
474   return true;
475 }
476 
477 void X86PassConfig::addPreRegAlloc() {
478   if (getOptLevel() != CodeGenOpt::None) {
479     addPass(&LiveRangeShrinkID);
480     addPass(createX86FixupSetCC());
481     addPass(createX86OptimizeLEAs());
482     addPass(createX86CallFrameOptimization());
483     addPass(createX86AvoidStoreForwardingBlocks());
484   }
485 
486   addPass(createX86SpeculativeLoadHardeningPass());
487   addPass(createX86FlagsCopyLoweringPass());
488   addPass(createX86WinAllocaExpander());
489 }
490 void X86PassConfig::addMachineSSAOptimization() {
491   addPass(createX86DomainReassignmentPass());
492   TargetPassConfig::addMachineSSAOptimization();
493 }
494 
495 void X86PassConfig::addPostRegAlloc() {
496   addPass(createX86FloatingPointStackifierPass());
497 }
498 
499 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
500 
501 void X86PassConfig::addPreEmitPass() {
502   if (getOptLevel() != CodeGenOpt::None) {
503     addPass(new X86ExecutionDomainFix());
504     addPass(createBreakFalseDeps());
505   }
506 
507   addPass(createX86IndirectBranchTrackingPass());
508 
509   if (UseVZeroUpper)
510     addPass(createX86IssueVZeroUpperPass());
511 
512   if (getOptLevel() != CodeGenOpt::None) {
513     addPass(createX86FixupBWInsts());
514     addPass(createX86PadShortFunctions());
515     addPass(createX86FixupLEAs());
516     addPass(createX86EvexToVexInsts());
517   }
518   addPass(createX86DiscriminateMemOpsPass());
519   addPass(createX86InsertPrefetchPass());
520   addPass(createX86InsertX87waitPass());
521 }
522 
523 void X86PassConfig::addPreEmitPass2() {
524   const Triple &TT = TM->getTargetTriple();
525   const MCAsmInfo *MAI = TM->getMCAsmInfo();
526 
527   addPass(createX86IndirectThunksPass());
528 
529   // Insert extra int3 instructions after trailing call instructions to avoid
530   // issues in the unwinder.
531   if (TT.isOSWindows() && TT.getArch() == Triple::x86_64)
532     addPass(createX86AvoidTrailingCallPass());
533 
534   // Verify basic block incoming and outgoing cfa offset and register values and
535   // correct CFA calculation rule where needed by inserting appropriate CFI
536   // instructions.
537   if (!TT.isOSDarwin() &&
538       (!TT.isOSWindows() ||
539        MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
540     addPass(createCFIInstrInserter());
541   // Identify valid longjmp targets for Windows Control Flow Guard.
542   if (TT.isOSWindows())
543     addPass(createCFGuardLongjmpPass());
544   addPass(createX86LoadValueInjectionRetHardeningPass());
545 }
546 
547 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
548   return getStandardCSEConfigForOpt(TM->getOptLevel());
549 }
550