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 
LLVMInitializeX86Target()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   initializeX86FixupSetCCPassPass(PR);
77   initializeX86CallFrameOptimizationPass(PR);
78   initializeX86CmovConverterPassPass(PR);
79   initializeX86ExpandPseudoPass(PR);
80   initializeX86ExecutionDomainFixPass(PR);
81   initializeX86DomainReassignmentPass(PR);
82   initializeX86AvoidSFBPassPass(PR);
83   initializeX86AvoidTrailingCallPassPass(PR);
84   initializeX86SpeculativeLoadHardeningPassPass(PR);
85   initializeX86SpeculativeExecutionSideEffectSuppressionPass(PR);
86   initializeX86FlagsCopyLoweringPassPass(PR);
87   initializeX86CondBrFoldingPassPass(PR);
88   initializeX86LoadValueInjectionLoadHardeningPassPass(PR);
89   initializeX86LoadValueInjectionRetHardeningPassPass(PR);
90   initializeX86OptimizeLEAPassPass(PR);
91   initializeX86PartialReductionPass(PR);
92 }
93 
createTLOF(const Triple & TT)94 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
95   if (TT.isOSBinFormatMachO()) {
96     if (TT.getArch() == Triple::x86_64)
97       return std::make_unique<X86_64MachoTargetObjectFile>();
98     return std::make_unique<TargetLoweringObjectFileMachO>();
99   }
100 
101   if (TT.isOSBinFormatCOFF())
102     return std::make_unique<TargetLoweringObjectFileCOFF>();
103   return std::make_unique<X86ELFTargetObjectFile>();
104 }
105 
computeDataLayout(const Triple & TT)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   // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
118   Ret += "-p270:32:32-p271:32:32-p272:64:64";
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 
getEffectiveRelocModel(const Triple & TT,bool JIT,Optional<Reloc::Model> RM)154 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
155                                            bool JIT,
156                                            Optional<Reloc::Model> RM) {
157   bool is64Bit = TT.getArch() == Triple::x86_64;
158   if (!RM.hasValue()) {
159     // JIT codegen should use static relocations by default, since it's
160     // typically executed in process and not relocatable.
161     if (JIT)
162       return Reloc::Static;
163 
164     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
165     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
166     // use static relocation model by default.
167     if (TT.isOSDarwin()) {
168       if (is64Bit)
169         return Reloc::PIC_;
170       return Reloc::DynamicNoPIC;
171     }
172     if (TT.isOSWindows() && is64Bit)
173       return Reloc::PIC_;
174     return Reloc::Static;
175   }
176 
177   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
178   // is defined as a model for code which may be used in static or dynamic
179   // executables but not necessarily a shared library. On X86-32 we just
180   // compile in -static mode, in x86-64 we use PIC.
181   if (*RM == Reloc::DynamicNoPIC) {
182     if (is64Bit)
183       return Reloc::PIC_;
184     if (!TT.isOSDarwin())
185       return Reloc::Static;
186   }
187 
188   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
189   // the Mach-O file format doesn't support it.
190   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
191     return Reloc::PIC_;
192 
193   return *RM;
194 }
195 
getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,bool JIT,bool Is64Bit)196 static CodeModel::Model getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,
197                                                  bool JIT, bool Is64Bit) {
198   if (CM) {
199     if (*CM == CodeModel::Tiny)
200       report_fatal_error("Target does not support the tiny CodeModel", false);
201     return *CM;
202   }
203   if (JIT)
204     return Is64Bit ? CodeModel::Large : CodeModel::Small;
205   return CodeModel::Small;
206 }
207 
208 /// Create an X86 target.
209 ///
X86TargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)210 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
211                                    StringRef CPU, StringRef FS,
212                                    const TargetOptions &Options,
213                                    Optional<Reloc::Model> RM,
214                                    Optional<CodeModel::Model> CM,
215                                    CodeGenOpt::Level OL, bool JIT)
216     : LLVMTargetMachine(
217           T, computeDataLayout(TT), TT, CPU, FS, Options,
218           getEffectiveRelocModel(TT, JIT, RM),
219           getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64),
220           OL),
221       TLOF(createTLOF(getTargetTriple())), IsJIT(JIT) {
222   // On PS4, the "return address" of a 'noreturn' call must still be within
223   // the calling function, and TrapUnreachable is an easy way to get that.
224   if (TT.isPS4() || TT.isOSBinFormatMachO()) {
225     this->Options.TrapUnreachable = true;
226     this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
227   }
228 
229   setMachineOutliner(true);
230 
231   // x86 supports the debug entry values.
232   setSupportsDebugEntryValues(true);
233 
234   initAsmInfo();
235 }
236 
237 X86TargetMachine::~X86TargetMachine() = default;
238 
239 const X86Subtarget *
getSubtargetImpl(const Function & F) const240 X86TargetMachine::getSubtargetImpl(const Function &F) const {
241   Attribute CPUAttr = F.getFnAttribute("target-cpu");
242   Attribute FSAttr = F.getFnAttribute("target-features");
243 
244   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
245                       ? CPUAttr.getValueAsString()
246                       : (StringRef)TargetCPU;
247   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
248                      ? FSAttr.getValueAsString()
249                      : (StringRef)TargetFS;
250 
251   SmallString<512> Key;
252   Key.reserve(CPU.size() + FS.size());
253   Key += CPU;
254   Key += FS;
255 
256   // FIXME: This is related to the code below to reset the target options,
257   // we need to know whether or not the soft float flag is set on the
258   // function before we can generate a subtarget. We also need to use
259   // it as a key for the subtarget since that can be the only difference
260   // between two functions.
261   bool SoftFloat =
262       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
263   // If the soft float attribute is set on the function turn on the soft float
264   // subtarget feature.
265   if (SoftFloat)
266     Key += FS.empty() ? "+soft-float" : ",+soft-float";
267 
268   // Keep track of the key width after all features are added so we can extract
269   // the feature string out later.
270   unsigned CPUFSWidth = Key.size();
271 
272   // Extract prefer-vector-width attribute.
273   unsigned PreferVectorWidthOverride = 0;
274   if (F.hasFnAttribute("prefer-vector-width")) {
275     StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
276     unsigned Width;
277     if (!Val.getAsInteger(0, Width)) {
278       Key += ",prefer-vector-width=";
279       Key += Val;
280       PreferVectorWidthOverride = Width;
281     }
282   }
283 
284   // Extract min-legal-vector-width attribute.
285   unsigned RequiredVectorWidth = UINT32_MAX;
286   if (F.hasFnAttribute("min-legal-vector-width")) {
287     StringRef Val =
288         F.getFnAttribute("min-legal-vector-width").getValueAsString();
289     unsigned Width;
290     if (!Val.getAsInteger(0, Width)) {
291       Key += ",min-legal-vector-width=";
292       Key += Val;
293       RequiredVectorWidth = Width;
294     }
295   }
296 
297   // Extracted here so that we make sure there is backing for the StringRef. If
298   // we assigned earlier, its possible the SmallString reallocated leaving a
299   // dangling StringRef.
300   FS = Key.slice(CPU.size(), CPUFSWidth);
301 
302   auto &I = SubtargetMap[Key];
303   if (!I) {
304     // This needs to be done before we create a new subtarget since any
305     // creation will depend on the TM and the code generation flags on the
306     // function that reside in TargetOptions.
307     resetTargetOptions(F);
308     I = std::make_unique<X86Subtarget>(
309         TargetTriple, CPU, FS, *this,
310         MaybeAlign(Options.StackAlignmentOverride), PreferVectorWidthOverride,
311         RequiredVectorWidth);
312   }
313   return I.get();
314 }
315 
316 //===----------------------------------------------------------------------===//
317 // X86 TTI query.
318 //===----------------------------------------------------------------------===//
319 
320 TargetTransformInfo
getTargetTransformInfo(const Function & F)321 X86TargetMachine::getTargetTransformInfo(const Function &F) {
322   return TargetTransformInfo(X86TTIImpl(this, F));
323 }
324 
325 //===----------------------------------------------------------------------===//
326 // Pass Pipeline Configuration
327 //===----------------------------------------------------------------------===//
328 
329 namespace {
330 
331 /// X86 Code Generator Pass Configuration Options.
332 class X86PassConfig : public TargetPassConfig {
333 public:
X86PassConfig(X86TargetMachine & TM,PassManagerBase & PM)334   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
335     : TargetPassConfig(TM, PM) {}
336 
getX86TargetMachine() const337   X86TargetMachine &getX86TargetMachine() const {
338     return getTM<X86TargetMachine>();
339   }
340 
341   ScheduleDAGInstrs *
createMachineScheduler(MachineSchedContext * C) const342   createMachineScheduler(MachineSchedContext *C) const override {
343     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
344     DAG->addMutation(createX86MacroFusionDAGMutation());
345     return DAG;
346   }
347 
348   ScheduleDAGInstrs *
createPostMachineScheduler(MachineSchedContext * C) const349   createPostMachineScheduler(MachineSchedContext *C) const override {
350     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
351     DAG->addMutation(createX86MacroFusionDAGMutation());
352     return DAG;
353   }
354 
355   void addIRPasses() override;
356   bool addInstSelector() override;
357   bool addIRTranslator() override;
358   bool addLegalizeMachineIR() override;
359   bool addRegBankSelect() override;
360   bool addGlobalInstructionSelect() override;
361   bool addILPOpts() override;
362   bool addPreISel() override;
363   void addMachineSSAOptimization() override;
364   void addPreRegAlloc() override;
365   void addPostRegAlloc() override;
366   void addPreEmitPass() override;
367   void addPreEmitPass2() override;
368   void addPreSched2() override;
369 
370   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
371 };
372 
373 class X86ExecutionDomainFix : public ExecutionDomainFix {
374 public:
375   static char ID;
X86ExecutionDomainFix()376   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
getPassName() const377   StringRef getPassName() const override {
378     return "X86 Execution Dependency Fix";
379   }
380 };
381 char X86ExecutionDomainFix::ID;
382 
383 } // end anonymous namespace
384 
385 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
386   "X86 Execution Domain Fix", false, false)
INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)387 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
388 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
389   "X86 Execution Domain Fix", false, false)
390 
391 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
392   return new X86PassConfig(*this, PM);
393 }
394 
addIRPasses()395 void X86PassConfig::addIRPasses() {
396   addPass(createAtomicExpandPass());
397 
398   TargetPassConfig::addIRPasses();
399 
400   if (TM->getOptLevel() != CodeGenOpt::None) {
401     addPass(createInterleavedAccessPass());
402     addPass(createX86PartialReductionPass());
403   }
404 
405   // Add passes that handle indirect branch removal and insertion of a retpoline
406   // thunk. These will be a no-op unless a function subtarget has the retpoline
407   // feature enabled.
408   addPass(createIndirectBrExpandPass());
409 
410   // Add Control Flow Guard checks.
411   const Triple &TT = TM->getTargetTriple();
412   if (TT.isOSWindows()) {
413     if (TT.getArch() == Triple::x86_64) {
414       addPass(createCFGuardDispatchPass());
415     } else {
416       addPass(createCFGuardCheckPass());
417     }
418   }
419 }
420 
addInstSelector()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 
addIRTranslator()434 bool X86PassConfig::addIRTranslator() {
435   addPass(new IRTranslator());
436   return false;
437 }
438 
addLegalizeMachineIR()439 bool X86PassConfig::addLegalizeMachineIR() {
440   addPass(new Legalizer());
441   return false;
442 }
443 
addRegBankSelect()444 bool X86PassConfig::addRegBankSelect() {
445   addPass(new RegBankSelect());
446   return false;
447 }
448 
addGlobalInstructionSelect()449 bool X86PassConfig::addGlobalInstructionSelect() {
450   addPass(new InstructionSelect());
451   return false;
452 }
453 
addILPOpts()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 
addPreISel()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 
addPreRegAlloc()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 }
addMachineSSAOptimization()485 void X86PassConfig::addMachineSSAOptimization() {
486   addPass(createX86DomainReassignmentPass());
487   TargetPassConfig::addMachineSSAOptimization();
488 }
489 
addPostRegAlloc()490 void X86PassConfig::addPostRegAlloc() {
491   addPass(createX86FloatingPointStackifierPass());
492   // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
493   // to using the Speculative Execution Side Effect Suppression pass for
494   // mitigation. This is to prevent slow downs due to
495   // analyses needed by the LVIHardening pass when compiling at -O0.
496   if (getOptLevel() != CodeGenOpt::None)
497     addPass(createX86LoadValueInjectionLoadHardeningPass());
498 }
499 
addPreSched2()500 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
501 
addPreEmitPass()502 void X86PassConfig::addPreEmitPass() {
503   if (getOptLevel() != CodeGenOpt::None) {
504     addPass(new X86ExecutionDomainFix());
505     addPass(createBreakFalseDeps());
506   }
507 
508   addPass(createX86IndirectBranchTrackingPass());
509 
510   addPass(createX86IssueVZeroUpperPass());
511 
512   if (getOptLevel() != CodeGenOpt::None) {
513     addPass(createX86FixupBWInsts());
514     addPass(createX86PadShortFunctions());
515     addPass(createX86FixupLEAs());
516   }
517   addPass(createX86EvexToVexInsts());
518   addPass(createX86DiscriminateMemOpsPass());
519   addPass(createX86InsertPrefetchPass());
520   addPass(createX86InsertX87waitPass());
521 }
522 
addPreEmitPass2()523 void X86PassConfig::addPreEmitPass2() {
524   const Triple &TT = TM->getTargetTriple();
525   const MCAsmInfo *MAI = TM->getMCAsmInfo();
526 
527   // The X86 Speculative Execution Pass must run after all control
528   // flow graph modifying passes. As a result it was listed to run right before
529   // the X86 Retpoline Thunks pass. The reason it must run after control flow
530   // graph modifications is that the model of LFENCE in LLVM has to be updated
531   // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
532   // placement of this pass was hand checked to ensure that the subsequent
533   // passes don't move the code around the LFENCEs in a way that will hurt the
534   // correctness of this pass. This placement has been shown to work based on
535   // hand inspection of the codegen output.
536   addPass(createX86SpeculativeExecutionSideEffectSuppression());
537   addPass(createX86IndirectThunksPass());
538 
539   // Insert extra int3 instructions after trailing call instructions to avoid
540   // issues in the unwinder.
541   if (TT.isOSWindows() && TT.getArch() == Triple::x86_64)
542     addPass(createX86AvoidTrailingCallPass());
543 
544   // Verify basic block incoming and outgoing cfa offset and register values and
545   // correct CFA calculation rule where needed by inserting appropriate CFI
546   // instructions.
547   if (!TT.isOSDarwin() &&
548       (!TT.isOSWindows() ||
549        MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
550     addPass(createCFIInstrInserter());
551   // Identify valid longjmp targets for Windows Control Flow Guard.
552   if (TT.isOSWindows())
553     addPass(createCFGuardLongjmpPass());
554   addPass(createX86LoadValueInjectionRetHardeningPass());
555 }
556 
getCSEConfig() const557 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
558   return getStandardCSEConfigForOpt(TM->getOptLevel());
559 }
560