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 "X86MachineFunctionInfo.h"
20 #include "X86MacroFusion.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetObjectFile.h"
23 #include "X86TargetTransformInfo.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/CodeGen/ExecutionDomainFix.h"
29 #include "llvm/CodeGen/GlobalISel/CSEInfo.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/InstructionSelector.h"
34 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
35 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
36 #include "llvm/CodeGen/MachineScheduler.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/CodeGen/TargetPassConfig.h"
40 #include "llvm/IR/Attributes.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/TargetRegistry.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/TargetParser/Triple.h"
52 #include "llvm/Transforms/CFGuard.h"
53 #include <memory>
54 #include <optional>
55 #include <string>
56 
57 using namespace llvm;
58 
59 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
60                                cl::desc("Enable the machine combiner pass"),
61                                cl::init(true), cl::Hidden);
62 
63 static cl::opt<bool>
64     EnableTileRAPass("x86-tile-ra",
65                      cl::desc("Enable the tile register allocation pass"),
66                      cl::init(true), cl::Hidden);
67 
68 extern "C" LLVM_EXTERNAL_VISIBILITY 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   initializeX86LowerAMXIntrinsicsLegacyPassPass(PR);
75   initializeX86LowerAMXTypeLegacyPassPass(PR);
76   initializeX86PreAMXConfigPassPass(PR);
77   initializeX86PreTileConfigPass(PR);
78   initializeGlobalISel(PR);
79   initializeWinEHStatePassPass(PR);
80   initializeFixupBWInstPassPass(PR);
81   initializeEvexToVexInstPassPass(PR);
82   initializeFixupLEAPassPass(PR);
83   initializeFPSPass(PR);
84   initializeX86FixupSetCCPassPass(PR);
85   initializeX86CallFrameOptimizationPass(PR);
86   initializeX86CmovConverterPassPass(PR);
87   initializeX86TileConfigPass(PR);
88   initializeX86FastPreTileConfigPass(PR);
89   initializeX86FastTileConfigPass(PR);
90   initializeKCFIPass(PR);
91   initializeX86LowerTileCopyPass(PR);
92   initializeX86ExpandPseudoPass(PR);
93   initializeX86ExecutionDomainFixPass(PR);
94   initializeX86DomainReassignmentPass(PR);
95   initializeX86AvoidSFBPassPass(PR);
96   initializeX86AvoidTrailingCallPassPass(PR);
97   initializeX86SpeculativeLoadHardeningPassPass(PR);
98   initializeX86SpeculativeExecutionSideEffectSuppressionPass(PR);
99   initializeX86FlagsCopyLoweringPassPass(PR);
100   initializeX86LoadValueInjectionLoadHardeningPassPass(PR);
101   initializeX86LoadValueInjectionRetHardeningPassPass(PR);
102   initializeX86OptimizeLEAPassPass(PR);
103   initializeX86PartialReductionPass(PR);
104   initializePseudoProbeInserterPass(PR);
105   initializeX86ReturnThunksPass(PR);
106   initializeX86DAGToDAGISelPass(PR);
107   initializeX86ArgumentStackSlotPassPass(PR);
108 }
109 
110 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
111   if (TT.isOSBinFormatMachO()) {
112     if (TT.getArch() == Triple::x86_64)
113       return std::make_unique<X86_64MachoTargetObjectFile>();
114     return std::make_unique<TargetLoweringObjectFileMachO>();
115   }
116 
117   if (TT.isOSBinFormatCOFF())
118     return std::make_unique<TargetLoweringObjectFileCOFF>();
119   return std::make_unique<X86ELFTargetObjectFile>();
120 }
121 
122 static std::string computeDataLayout(const Triple &TT) {
123   // X86 is little endian
124   std::string Ret = "e";
125 
126   Ret += DataLayout::getManglingComponent(TT);
127   // X86 and x32 have 32 bit pointers.
128   if (!TT.isArch64Bit() || TT.isX32() || TT.isOSNaCl())
129     Ret += "-p:32:32";
130 
131   // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
132   Ret += "-p270:32:32-p271:32:32-p272:64:64";
133 
134   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
135   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
136     Ret += "-i64:64";
137   else if (TT.isOSIAMCU())
138     Ret += "-i64:32-f64:32";
139   else
140     Ret += "-f64:32:64";
141 
142   // Some ABIs align long double to 128 bits, others to 32.
143   if (TT.isOSNaCl() || TT.isOSIAMCU())
144     ; // No f80
145   else if (TT.isArch64Bit() || TT.isOSDarwin() || TT.isWindowsMSVCEnvironment())
146     Ret += "-f80:128";
147   else
148     Ret += "-f80:32";
149 
150   if (TT.isOSIAMCU())
151     Ret += "-f128:32";
152 
153   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
154   if (TT.isArch64Bit())
155     Ret += "-n8:16:32:64";
156   else
157     Ret += "-n8:16:32";
158 
159   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
160   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
161     Ret += "-a:0:32-S32";
162   else
163     Ret += "-S128";
164 
165   return Ret;
166 }
167 
168 static Reloc::Model getEffectiveRelocModel(const Triple &TT, bool JIT,
169                                            std::optional<Reloc::Model> RM) {
170   bool is64Bit = TT.getArch() == Triple::x86_64;
171   if (!RM) {
172     // JIT codegen should use static relocations by default, since it's
173     // typically executed in process and not relocatable.
174     if (JIT)
175       return Reloc::Static;
176 
177     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
178     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
179     // use static relocation model by default.
180     if (TT.isOSDarwin()) {
181       if (is64Bit)
182         return Reloc::PIC_;
183       return Reloc::DynamicNoPIC;
184     }
185     if (TT.isOSWindows() && is64Bit)
186       return Reloc::PIC_;
187     return Reloc::Static;
188   }
189 
190   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
191   // is defined as a model for code which may be used in static or dynamic
192   // executables but not necessarily a shared library. On X86-32 we just
193   // compile in -static mode, in x86-64 we use PIC.
194   if (*RM == Reloc::DynamicNoPIC) {
195     if (is64Bit)
196       return Reloc::PIC_;
197     if (!TT.isOSDarwin())
198       return Reloc::Static;
199   }
200 
201   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
202   // the Mach-O file format doesn't support it.
203   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
204     return Reloc::PIC_;
205 
206   return *RM;
207 }
208 
209 static CodeModel::Model
210 getEffectiveX86CodeModel(std::optional<CodeModel::Model> CM, bool JIT,
211                          bool Is64Bit) {
212   if (CM) {
213     if (*CM == CodeModel::Tiny)
214       report_fatal_error("Target does not support the tiny CodeModel", false);
215     return *CM;
216   }
217   if (JIT)
218     return Is64Bit ? CodeModel::Large : CodeModel::Small;
219   return CodeModel::Small;
220 }
221 
222 /// Create an X86 target.
223 ///
224 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
225                                    StringRef CPU, StringRef FS,
226                                    const TargetOptions &Options,
227                                    std::optional<Reloc::Model> RM,
228                                    std::optional<CodeModel::Model> CM,
229                                    CodeGenOpt::Level OL, bool JIT)
230     : LLVMTargetMachine(
231           T, computeDataLayout(TT), TT, CPU, FS, Options,
232           getEffectiveRelocModel(TT, JIT, RM),
233           getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64),
234           OL),
235       TLOF(createTLOF(getTargetTriple())), IsJIT(JIT) {
236   // On PS4/PS5, the "return address" of a 'noreturn' call must still be within
237   // the calling function, and TrapUnreachable is an easy way to get that.
238   if (TT.isPS() || TT.isOSBinFormatMachO()) {
239     this->Options.TrapUnreachable = true;
240     this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
241   }
242 
243   setMachineOutliner(true);
244 
245   // x86 supports the debug entry values.
246   setSupportsDebugEntryValues(true);
247 
248   initAsmInfo();
249 }
250 
251 X86TargetMachine::~X86TargetMachine() = default;
252 
253 const X86Subtarget *
254 X86TargetMachine::getSubtargetImpl(const Function &F) const {
255   Attribute CPUAttr = F.getFnAttribute("target-cpu");
256   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
257   Attribute FSAttr = F.getFnAttribute("target-features");
258 
259   StringRef CPU =
260       CPUAttr.isValid() ? CPUAttr.getValueAsString() : (StringRef)TargetCPU;
261   // "x86-64" is a default target setting for many front ends. In these cases,
262   // they actually request for "generic" tuning unless the "tune-cpu" was
263   // specified.
264   StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString()
265                       : CPU == "x86-64"  ? "generic"
266                                          : (StringRef)CPU;
267   StringRef FS =
268       FSAttr.isValid() ? FSAttr.getValueAsString() : (StringRef)TargetFS;
269 
270   SmallString<512> Key;
271   // The additions here are ordered so that the definitely short strings are
272   // added first so we won't exceed the small size. We append the
273   // much longer FS string at the end so that we only heap allocate at most
274   // one time.
275 
276   // Extract prefer-vector-width attribute.
277   unsigned PreferVectorWidthOverride = 0;
278   Attribute PreferVecWidthAttr = F.getFnAttribute("prefer-vector-width");
279   if (PreferVecWidthAttr.isValid()) {
280     StringRef Val = PreferVecWidthAttr.getValueAsString();
281     unsigned Width;
282     if (!Val.getAsInteger(0, Width)) {
283       Key += 'p';
284       Key += Val;
285       PreferVectorWidthOverride = Width;
286     }
287   }
288 
289   // Extract min-legal-vector-width attribute.
290   unsigned RequiredVectorWidth = UINT32_MAX;
291   Attribute MinLegalVecWidthAttr = F.getFnAttribute("min-legal-vector-width");
292   if (MinLegalVecWidthAttr.isValid()) {
293     StringRef Val = MinLegalVecWidthAttr.getValueAsString();
294     unsigned Width;
295     if (!Val.getAsInteger(0, Width)) {
296       Key += 'm';
297       Key += Val;
298       RequiredVectorWidth = Width;
299     }
300   }
301 
302   // Add CPU to the Key.
303   Key += CPU;
304 
305   // Add tune CPU to the Key.
306   Key += TuneCPU;
307 
308   // Keep track of the start of the feature portion of the string.
309   unsigned FSStart = Key.size();
310 
311   // FIXME: This is related to the code below to reset the target options,
312   // we need to know whether or not the soft float flag is set on the
313   // function before we can generate a subtarget. We also need to use
314   // it as a key for the subtarget since that can be the only difference
315   // between two functions.
316   bool SoftFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
317   // If the soft float attribute is set on the function turn on the soft float
318   // subtarget feature.
319   if (SoftFloat)
320     Key += FS.empty() ? "+soft-float" : "+soft-float,";
321 
322   Key += FS;
323 
324   // We may have added +soft-float to the features so move the StringRef to
325   // point to the full string in the Key.
326   FS = Key.substr(FSStart);
327 
328   auto &I = SubtargetMap[Key];
329   if (!I) {
330     // This needs to be done before we create a new subtarget since any
331     // creation will depend on the TM and the code generation flags on the
332     // function that reside in TargetOptions.
333     resetTargetOptions(F);
334     I = std::make_unique<X86Subtarget>(
335         TargetTriple, CPU, TuneCPU, FS, *this,
336         MaybeAlign(F.getParent()->getOverrideStackAlignment()),
337         PreferVectorWidthOverride, RequiredVectorWidth);
338   }
339   return I.get();
340 }
341 
342 bool X86TargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
343                                            unsigned DestAS) const {
344   assert(SrcAS != DestAS && "Expected different address spaces!");
345   if (getPointerSize(SrcAS) != getPointerSize(DestAS))
346     return false;
347   return SrcAS < 256 && DestAS < 256;
348 }
349 
350 //===----------------------------------------------------------------------===//
351 // X86 TTI query.
352 //===----------------------------------------------------------------------===//
353 
354 TargetTransformInfo
355 X86TargetMachine::getTargetTransformInfo(const Function &F) const {
356   return TargetTransformInfo(X86TTIImpl(this, F));
357 }
358 
359 //===----------------------------------------------------------------------===//
360 // Pass Pipeline Configuration
361 //===----------------------------------------------------------------------===//
362 
363 namespace {
364 
365 /// X86 Code Generator Pass Configuration Options.
366 class X86PassConfig : public TargetPassConfig {
367 public:
368   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
369     : TargetPassConfig(TM, PM) {}
370 
371   X86TargetMachine &getX86TargetMachine() const {
372     return getTM<X86TargetMachine>();
373   }
374 
375   ScheduleDAGInstrs *
376   createMachineScheduler(MachineSchedContext *C) const override {
377     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
378     DAG->addMutation(createX86MacroFusionDAGMutation());
379     return DAG;
380   }
381 
382   ScheduleDAGInstrs *
383   createPostMachineScheduler(MachineSchedContext *C) const override {
384     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
385     DAG->addMutation(createX86MacroFusionDAGMutation());
386     return DAG;
387   }
388 
389   void addIRPasses() override;
390   bool addInstSelector() override;
391   bool addIRTranslator() override;
392   bool addLegalizeMachineIR() override;
393   bool addRegBankSelect() override;
394   bool addGlobalInstructionSelect() override;
395   bool addILPOpts() override;
396   bool addPreISel() override;
397   void addMachineSSAOptimization() override;
398   void addPreRegAlloc() override;
399   bool addPostFastRegAllocRewrite() override;
400   void addPostRegAlloc() override;
401   void addPreEmitPass() override;
402   void addPreEmitPass2() override;
403   void addPreSched2() override;
404   bool addRegAssignAndRewriteOptimized() override;
405 
406   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
407 };
408 
409 class X86ExecutionDomainFix : public ExecutionDomainFix {
410 public:
411   static char ID;
412   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
413   StringRef getPassName() const override {
414     return "X86 Execution Dependency Fix";
415   }
416 };
417 char X86ExecutionDomainFix::ID;
418 
419 } // end anonymous namespace
420 
421 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
422   "X86 Execution Domain Fix", false, false)
423 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
424 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
425   "X86 Execution Domain Fix", false, false)
426 
427 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
428   return new X86PassConfig(*this, PM);
429 }
430 
431 MachineFunctionInfo *X86TargetMachine::createMachineFunctionInfo(
432     BumpPtrAllocator &Allocator, const Function &F,
433     const TargetSubtargetInfo *STI) const {
434   return X86MachineFunctionInfo::create<X86MachineFunctionInfo>(Allocator, F,
435                                                                 STI);
436 }
437 
438 void X86PassConfig::addIRPasses() {
439   addPass(createAtomicExpandPass());
440 
441   // We add both pass anyway and when these two passes run, we skip the pass
442   // based on the option level and option attribute.
443   addPass(createX86LowerAMXIntrinsicsPass());
444   addPass(createX86LowerAMXTypePass());
445 
446   TargetPassConfig::addIRPasses();
447 
448   if (TM->getOptLevel() != CodeGenOpt::None) {
449     addPass(createInterleavedAccessPass());
450     addPass(createX86PartialReductionPass());
451   }
452 
453   // Add passes that handle indirect branch removal and insertion of a retpoline
454   // thunk. These will be a no-op unless a function subtarget has the retpoline
455   // feature enabled.
456   addPass(createIndirectBrExpandPass());
457 
458   // Add Control Flow Guard checks.
459   const Triple &TT = TM->getTargetTriple();
460   if (TT.isOSWindows()) {
461     if (TT.getArch() == Triple::x86_64) {
462       addPass(createCFGuardDispatchPass());
463     } else {
464       addPass(createCFGuardCheckPass());
465     }
466   }
467 
468   if (TM->Options.JMCInstrument)
469     addPass(createJMCInstrumenterPass());
470 }
471 
472 bool X86PassConfig::addInstSelector() {
473   // Install an instruction selector.
474   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
475 
476   // For ELF, cleanup any local-dynamic TLS accesses.
477   if (TM->getTargetTriple().isOSBinFormatELF() &&
478       getOptLevel() != CodeGenOpt::None)
479     addPass(createCleanupLocalDynamicTLSPass());
480 
481   addPass(createX86GlobalBaseRegPass());
482   addPass(createX86ArgumentStackSlotPass());
483   return false;
484 }
485 
486 bool X86PassConfig::addIRTranslator() {
487   addPass(new IRTranslator(getOptLevel()));
488   return false;
489 }
490 
491 bool X86PassConfig::addLegalizeMachineIR() {
492   addPass(new Legalizer());
493   return false;
494 }
495 
496 bool X86PassConfig::addRegBankSelect() {
497   addPass(new RegBankSelect());
498   return false;
499 }
500 
501 bool X86PassConfig::addGlobalInstructionSelect() {
502   addPass(new InstructionSelect(getOptLevel()));
503   return false;
504 }
505 
506 bool X86PassConfig::addILPOpts() {
507   addPass(&EarlyIfConverterID);
508   if (EnableMachineCombinerPass)
509     addPass(&MachineCombinerID);
510   addPass(createX86CmovConverterPass());
511   return true;
512 }
513 
514 bool X86PassConfig::addPreISel() {
515   // Only add this pass for 32-bit x86 Windows.
516   const Triple &TT = TM->getTargetTriple();
517   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
518     addPass(createX86WinEHStatePass());
519   return true;
520 }
521 
522 void X86PassConfig::addPreRegAlloc() {
523   if (getOptLevel() != CodeGenOpt::None) {
524     addPass(&LiveRangeShrinkID);
525     addPass(createX86FixupSetCC());
526     addPass(createX86OptimizeLEAs());
527     addPass(createX86CallFrameOptimization());
528     addPass(createX86AvoidStoreForwardingBlocks());
529   }
530 
531   addPass(createX86SpeculativeLoadHardeningPass());
532   addPass(createX86FlagsCopyLoweringPass());
533   addPass(createX86DynAllocaExpander());
534 
535   if (getOptLevel() != CodeGenOpt::None)
536     addPass(createX86PreTileConfigPass());
537   else
538     addPass(createX86FastPreTileConfigPass());
539 }
540 
541 void X86PassConfig::addMachineSSAOptimization() {
542   addPass(createX86DomainReassignmentPass());
543   TargetPassConfig::addMachineSSAOptimization();
544 }
545 
546 void X86PassConfig::addPostRegAlloc() {
547   addPass(createX86LowerTileCopyPass());
548   addPass(createX86FloatingPointStackifierPass());
549   // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
550   // to using the Speculative Execution Side Effect Suppression pass for
551   // mitigation. This is to prevent slow downs due to
552   // analyses needed by the LVIHardening pass when compiling at -O0.
553   if (getOptLevel() != CodeGenOpt::None)
554     addPass(createX86LoadValueInjectionLoadHardeningPass());
555 }
556 
557 void X86PassConfig::addPreSched2() {
558   addPass(createX86ExpandPseudoPass());
559   addPass(createKCFIPass());
560 }
561 
562 void X86PassConfig::addPreEmitPass() {
563   if (getOptLevel() != CodeGenOpt::None) {
564     addPass(new X86ExecutionDomainFix());
565     addPass(createBreakFalseDeps());
566   }
567 
568   addPass(createX86IndirectBranchTrackingPass());
569 
570   addPass(createX86IssueVZeroUpperPass());
571 
572   if (getOptLevel() != CodeGenOpt::None) {
573     addPass(createX86FixupBWInsts());
574     addPass(createX86PadShortFunctions());
575     addPass(createX86FixupLEAs());
576     addPass(createX86FixupInstTuning());
577     addPass(createX86FixupVectorConstants());
578   }
579   addPass(createX86EvexToVexInsts());
580   addPass(createX86DiscriminateMemOpsPass());
581   addPass(createX86InsertPrefetchPass());
582   addPass(createX86InsertX87waitPass());
583 }
584 
585 void X86PassConfig::addPreEmitPass2() {
586   const Triple &TT = TM->getTargetTriple();
587   const MCAsmInfo *MAI = TM->getMCAsmInfo();
588 
589   // The X86 Speculative Execution Pass must run after all control
590   // flow graph modifying passes. As a result it was listed to run right before
591   // the X86 Retpoline Thunks pass. The reason it must run after control flow
592   // graph modifications is that the model of LFENCE in LLVM has to be updated
593   // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
594   // placement of this pass was hand checked to ensure that the subsequent
595   // passes don't move the code around the LFENCEs in a way that will hurt the
596   // correctness of this pass. This placement has been shown to work based on
597   // hand inspection of the codegen output.
598   addPass(createX86SpeculativeExecutionSideEffectSuppression());
599   addPass(createX86IndirectThunksPass());
600   addPass(createX86ReturnThunksPass());
601 
602   // Insert extra int3 instructions after trailing call instructions to avoid
603   // issues in the unwinder.
604   if (TT.isOSWindows() && TT.getArch() == Triple::x86_64)
605     addPass(createX86AvoidTrailingCallPass());
606 
607   // Verify basic block incoming and outgoing cfa offset and register values and
608   // correct CFA calculation rule where needed by inserting appropriate CFI
609   // instructions.
610   if (!TT.isOSDarwin() &&
611       (!TT.isOSWindows() ||
612        MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
613     addPass(createCFIInstrInserter());
614 
615   if (TT.isOSWindows()) {
616     // Identify valid longjmp targets for Windows Control Flow Guard.
617     addPass(createCFGuardLongjmpPass());
618     // Identify valid eh continuation targets for Windows EHCont Guard.
619     addPass(createEHContGuardCatchretPass());
620   }
621   addPass(createX86LoadValueInjectionRetHardeningPass());
622 
623   // Insert pseudo probe annotation for callsite profiling
624   addPass(createPseudoProbeInserter());
625 
626   // KCFI indirect call checks are lowered to a bundle, and on Darwin platforms,
627   // also CALL_RVMARKER.
628   addPass(createUnpackMachineBundles([&TT](const MachineFunction &MF) {
629     // Only run bundle expansion if the module uses kcfi, or there are relevant
630     // ObjC runtime functions present in the module.
631     const Function &F = MF.getFunction();
632     const Module *M = F.getParent();
633     return M->getModuleFlag("kcfi") ||
634            (TT.isOSDarwin() &&
635             (M->getFunction("objc_retainAutoreleasedReturnValue") ||
636              M->getFunction("objc_unsafeClaimAutoreleasedReturnValue")));
637   }));
638 }
639 
640 bool X86PassConfig::addPostFastRegAllocRewrite() {
641   addPass(createX86FastTileConfigPass());
642   return true;
643 }
644 
645 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
646   return getStandardCSEConfigForOpt(TM->getOptLevel());
647 }
648 
649 static bool onlyAllocateTileRegisters(const TargetRegisterInfo &TRI,
650                                       const TargetRegisterClass &RC) {
651   return static_cast<const X86RegisterInfo &>(TRI).isTileRegisterClass(&RC);
652 }
653 
654 bool X86PassConfig::addRegAssignAndRewriteOptimized() {
655   // Don't support tile RA when RA is specified by command line "-regalloc".
656   if (!isCustomizedRegAlloc() && EnableTileRAPass) {
657     // Allocate tile register first.
658     addPass(createGreedyRegisterAllocator(onlyAllocateTileRegisters));
659     addPass(createX86TileConfigPass());
660   }
661   return TargetPassConfig::addRegAssignAndRewriteOptimized();
662 }
663