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 "X86MachineFunctionInfo.h"
18#include "X86MacroFusion.h"
19#include "X86Subtarget.h"
20#include "X86TargetObjectFile.h"
21#include "X86TargetTransformInfo.h"
22#include "llvm-c/Visibility.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/CodeGen/ExecutionDomainFix.h"
27#include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28#include "llvm/CodeGen/GlobalISel/CallLowering.h"
29#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
30#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
31#include "llvm/CodeGen/GlobalISel/Legalizer.h"
32#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
33#include "llvm/CodeGen/MIRParser/MIParser.h"
34#include "llvm/CodeGen/MIRYamlMapping.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/MC/TargetRegistry.h"
43#include "llvm/Option/LibraryOptions.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/CodeGen.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Target/TargetLoweringObjectFile.h"
48#include "llvm/Target/TargetOptions.h"
49#include "llvm/TargetParser/Triple.h"
50#include "llvm/Transforms/CFGuard.h"
51#include <memory>
52#include <optional>
53
54using namespace llvm;
55
56extern "C" LLVM_C_ABI void LLVMInitializeX86Target() {
57 // Register the target.
58 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
59 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
60 static opt::RegisterLibraryOptions<X86Options> O;
61
62 PassRegistry &PR = *PassRegistry::getPassRegistry();
63 initializeX86LowerAMXIntrinsicsLegacyPassPass(PR);
64 initializeX86LowerAMXTypeLegacyPassPass(PR);
65 initializeX86PreTileConfigLegacyPass(PR);
66 initializeGlobalISel(PR);
67 initializeWinEHStateLegacyPass(PR);
68 initializeX86FixupBWInstLegacyPass(PR);
69 initializeCompressEVEXLegacyPass(PR);
70 initializeFixupLEAsLegacyPass(PR);
71 initializeX86FPStackifierLegacyPass(PR);
72 initializeX86FixupSetCCLegacyPass(PR);
73 initializeX86CallFrameOptimizationLegacyPass(PR);
74 initializeX86CmovConversionLegacyPass(PR);
75 initializeX86TileConfigLegacyPass(PR);
76 initializeX86FastPreTileConfigLegacyPass(PR);
77 initializeX86FastTileConfigLegacyPass(PR);
78 initializeMachineKCFILegacyPass(PR);
79 initializeX86LowerTileCopyLegacyPass(PR);
80 initializeX86ExpandPseudoLegacyPass(PR);
81 initializeX86ExecutionDomainFixPass(PR);
82 initializeX86DomainReassignmentLegacyPass(PR);
83 initializeX86AvoidSFBLegacyPass(PR);
84 initializeX86AvoidTrailingCallLegacyPassPass(PR);
85 initializeX86SpeculativeLoadHardeningLegacyPass(PR);
86 initializeX86SpeculativeExecutionSideEffectSuppressionLegacyPass(PR);
87 initializeX86FlagsCopyLoweringLegacyPass(PR);
88 initializeX86LoadValueInjectionLoadHardeningLegacyPass(PR);
89 initializeX86LoadValueInjectionRetHardeningLegacyPass(PR);
90 initializeX86OptimizeLEAsLegacyPass(PR);
91 initializeX86PartialReductionLegacyPass(PR);
92 initializeX86ReturnThunksLegacyPass(PR);
93 initializeX86DAGToDAGISelLegacyPass(PR);
94 initializeX86ArgumentStackSlotLegacyPass(PR);
95 initializeX86AsmPrinterPass(PR);
96 initializeX86FixupInstTuningLegacyPass(PR);
97 initializeX86FixupVectorConstantsLegacyPass(PR);
98 initializeX86DynAllocaExpanderLegacyPass(PR);
99 initializeX86SuppressAPXForRelocationLegacyPass(PR);
100 initializeX86WinEHUnwindV2LegacyPass(PR);
101 initializeX86PreLegalizerCombinerLegacyPass(PR);
102 initializeX86PostLegalizerCombinerLegacyPass(PR);
103 initializeX86WinEHUnwindV3Pass(PR);
104}
105
106static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
107 if (TT.isOSBinFormatMachO()) {
108 if (TT.isX86_64())
109 return std::make_unique<X86_64MachoTargetObjectFile>();
110 return std::make_unique<TargetLoweringObjectFileMachO>();
111 }
112
113 if (TT.isOSBinFormatCOFF())
114 return std::make_unique<TargetLoweringObjectFileCOFF>();
115
116 if (TT.isX86_64())
117 return std::make_unique<X86_64ELFTargetObjectFile>();
118 return std::make_unique<X86ELFTargetObjectFile>();
119}
120
121static Reloc::Model getEffectiveRelocModel(const Triple &TT, bool JIT,
122 std::optional<Reloc::Model> RM) {
123 bool is64Bit = TT.isX86_64();
124 if (!RM) {
125 // JIT codegen should use static relocations by default, since it's
126 // typically executed in process and not relocatable.
127 if (JIT)
128 return Reloc::Static;
129
130 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
131 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
132 // use static relocation model by default.
133 if (TT.isOSDarwin()) {
134 if (is64Bit)
135 return Reloc::PIC_;
136 return Reloc::DynamicNoPIC;
137 }
138 if (TT.isOSWindows() && is64Bit)
139 return Reloc::PIC_;
140 return Reloc::Static;
141 }
142
143 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
144 // is defined as a model for code which may be used in static or dynamic
145 // executables but not necessarily a shared library. On X86-32 we just
146 // compile in -static mode, in x86-64 we use PIC.
147 if (*RM == Reloc::DynamicNoPIC) {
148 if (is64Bit)
149 return Reloc::PIC_;
150 if (!TT.isOSDarwin())
151 return Reloc::Static;
152 }
153
154 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
155 // the Mach-O file format doesn't support it.
156 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
157 return Reloc::PIC_;
158
159 return *RM;
160}
161
162static CodeModel::Model
163getEffectiveX86CodeModel(const Triple &TT, std::optional<CodeModel::Model> CM,
164 bool JIT) {
165 bool Is64Bit = TT.isX86_64();
166 if (CM) {
167 if (*CM == CodeModel::Tiny)
168 reportFatalUsageError(reason: "target does not support the tiny CodeModel");
169 return *CM;
170 }
171 if (JIT)
172 return Is64Bit ? CodeModel::Large : CodeModel::Small;
173 return CodeModel::Small;
174}
175
176/// Create an X86 target.
177///
178X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
179 StringRef CPU, StringRef FS,
180 const TargetOptions &Options,
181 std::optional<Reloc::Model> RM,
182 std::optional<CodeModel::Model> CM,
183 CodeGenOptLevel OL, bool JIT)
184 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
185 getEffectiveRelocModel(TT, JIT, RM),
186 getEffectiveX86CodeModel(TT, CM, JIT), OL),
187 CLOpts(X86Options::Global), TLOF(createTLOF(TT: getTargetTriple())),
188 IsJIT(JIT) {
189 // On PS4/PS5, the "return address" of a 'noreturn' call must still be within
190 // the calling function. Note that this also includes __stack_chk_fail,
191 // so there was some target-specific logic in the instruction selectors
192 // to handle that. That code has since been generalized, so the only thing
193 // needed is to set TrapUnreachable here.
194 if (TT.isPS() || TT.isOSBinFormatMachO()) {
195 this->Options.TrapUnreachable = true;
196 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
197 }
198
199 setMachineOutliner(true);
200
201 // x86 supports the debug entry values.
202 setSupportsDebugEntryValues(true);
203
204 initAsmInfo();
205}
206
207X86TargetMachine::~X86TargetMachine() = default;
208
209const X86Subtarget *
210X86TargetMachine::getSubtargetImpl(const Function &F) const {
211 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
212 Attribute TuneAttr = F.getFnAttribute(Kind: "tune-cpu");
213 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
214
215 StringRef CPU =
216 CPUAttr.isValid() ? CPUAttr.getValueAsString() : (StringRef)TargetCPU;
217 // "x86-64" is a default target setting for many front ends. In these cases,
218 // they actually request for "generic" tuning unless the "tune-cpu" was
219 // specified.
220 StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString()
221 : CPU == "x86-64" ? "generic"
222 : (StringRef)CPU;
223 StringRef FS =
224 FSAttr.isValid() ? FSAttr.getValueAsString() : (StringRef)TargetFS;
225
226 SmallString<512> Key;
227 // The additions here are ordered so that the definitely short strings are
228 // added first so we won't exceed the small size. We append the
229 // much longer FS string at the end so that we only heap allocate at most
230 // one time.
231
232 // Extract prefer-vector-width attribute.
233 unsigned PreferVectorWidthOverride = 0;
234 Attribute PreferVecWidthAttr = F.getFnAttribute(Kind: "prefer-vector-width");
235 if (PreferVecWidthAttr.isValid()) {
236 StringRef Val = PreferVecWidthAttr.getValueAsString();
237 unsigned Width;
238 if (!Val.getAsInteger(Radix: 0, Result&: Width)) {
239 Key += 'p';
240 Key += Val;
241 PreferVectorWidthOverride = Width;
242 }
243 }
244
245 // Extract min-legal-vector-width attribute.
246 unsigned RequiredVectorWidth = UINT32_MAX;
247 Attribute MinLegalVecWidthAttr = F.getFnAttribute(Kind: "min-legal-vector-width");
248 if (MinLegalVecWidthAttr.isValid()) {
249 StringRef Val = MinLegalVecWidthAttr.getValueAsString();
250 unsigned Width;
251 if (!Val.getAsInteger(Radix: 0, Result&: Width)) {
252 Key += 'm';
253 Key += Val;
254 RequiredVectorWidth = Width;
255 }
256 }
257
258 // Add CPU to the Key.
259 Key += CPU;
260
261 // Add tune CPU to the Key.
262 Key += TuneCPU;
263
264 // Keep track of the start of the feature portion of the string.
265 unsigned FSStart = Key.size();
266
267 // FIXME: This is related to the code below to reset the target options,
268 // we need to know whether or not the soft float flag is set on the
269 // function before we can generate a subtarget. We also need to use
270 // it as a key for the subtarget since that can be the only difference
271 // between two functions.
272 bool SoftFloat = F.getFnAttribute(Kind: "use-soft-float").getValueAsBool();
273 // If the soft float attribute is set on the function turn on the soft float
274 // subtarget feature.
275 if (SoftFloat)
276 Key += FS.empty() ? "+soft-float" : "+soft-float,";
277
278 Key += FS;
279
280 // We may have added +soft-float to the features so move the StringRef to
281 // point to the full string in the Key.
282 FS = Key.substr(Start: FSStart);
283
284 auto &I = SubtargetMap[Key];
285 if (!I) {
286 I = std::make_unique<X86Subtarget>(
287 args: TargetTriple, args&: CPU, args&: TuneCPU, args&: FS, args: *this,
288 args: MaybeAlign(F.getParent()->getOverrideStackAlignment()),
289 args&: PreferVectorWidthOverride, args&: RequiredVectorWidth);
290 }
291 return I.get();
292}
293
294yaml::MachineFunctionInfo *X86TargetMachine::createDefaultFuncInfoYAML() const {
295 return new yaml::X86MachineFunctionInfo();
296}
297
298yaml::MachineFunctionInfo *
299X86TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
300 const auto *MFI = MF.getInfo<X86MachineFunctionInfo>();
301 return new yaml::X86MachineFunctionInfo(*MFI);
302}
303
304bool X86TargetMachine::parseMachineFunctionInfo(
305 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
306 SMDiagnostic &Error, SMRange &SourceRange) const {
307 const auto &YamlMFI = static_cast<const yaml::X86MachineFunctionInfo &>(MFI);
308 PFS.MF.getInfo<X86MachineFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
309 return false;
310}
311
312bool X86TargetMachine::isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS,
313 unsigned DestAS) const {
314 assert(SrcAS != DestAS && "Expected different address spaces!");
315 if (DL.getPointerSize(AS: SrcAS) != DL.getPointerSize(AS: DestAS))
316 return false;
317 return SrcAS < 256 && DestAS < 256;
318}
319
320void X86TargetMachine::reset() { SubtargetMap.clear(); }
321
322ScheduleDAGInstrs *
323X86TargetMachine::createMachineScheduler(MachineSchedContext *C) const {
324 ScheduleDAGMILive *DAG = createSchedLive(C);
325 DAG->addMutation(Mutation: createX86MacroFusionDAGMutation());
326 return DAG;
327}
328
329ScheduleDAGInstrs *
330X86TargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
331 ScheduleDAGMI *DAG = createSchedPostRA(C);
332 DAG->addMutation(Mutation: createX86MacroFusionDAGMutation());
333 return DAG;
334}
335
336//===----------------------------------------------------------------------===//
337// X86 TTI query.
338//===----------------------------------------------------------------------===//
339
340TargetTransformInfo
341X86TargetMachine::getTargetTransformInfo(const Function &F) const {
342 return TargetTransformInfo(std::make_unique<X86TTIImpl>(args: this, args: F));
343}
344
345//===----------------------------------------------------------------------===//
346// Pass Pipeline Configuration
347//===----------------------------------------------------------------------===//
348
349namespace {
350
351/// X86 Code Generator Pass Configuration Options.
352class X86PassConfig : public TargetPassConfig {
353public:
354 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
355 : TargetPassConfig(TM, PM) {}
356
357 X86TargetMachine &getX86TargetMachine() const {
358 return getTM<X86TargetMachine>();
359 }
360
361 void addIRPasses() override;
362 bool addInstSelector() override;
363 bool addIRTranslator() override;
364 bool addLegalizeMachineIR() override;
365 void addPreRegBankSelect() override;
366 bool addRegBankSelect() override;
367 bool addGlobalInstructionSelect() override;
368 void addPreLegalizeMachineIR() override;
369 bool addILPOpts() override;
370 bool addPreISel() override;
371 void addMachineSSAOptimization() override;
372 void addPreRegAlloc() override;
373 bool addPostFastRegAllocRewrite() override;
374 void addPostRegAlloc() override;
375 void addPreEmitPass() override;
376 void addPreEmitPass2() override;
377 void addPreSched2() override;
378 bool addRegAssignAndRewriteOptimized() override;
379
380 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
381};
382
383class X86ExecutionDomainFix : public ExecutionDomainFix {
384public:
385 static char ID;
386 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
387 StringRef getPassName() const override {
388 return "X86 Execution Dependency Fix";
389 }
390};
391char X86ExecutionDomainFix::ID;
392
393} // end anonymous namespace
394
395INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
396 "X86 Execution Domain Fix", false, false)
397INITIALIZE_PASS_DEPENDENCY(ReachingDefInfoWrapperPass)
398INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
399 "X86 Execution Domain Fix", false, false)
400
401TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
402 return new X86PassConfig(*this, PM);
403}
404
405MachineFunctionInfo *X86TargetMachine::createMachineFunctionInfo(
406 BumpPtrAllocator &Allocator, const Function &F,
407 const TargetSubtargetInfo *STI) const {
408 return X86MachineFunctionInfo::create<X86MachineFunctionInfo>(Allocator, F,
409 STI);
410}
411
412void X86PassConfig::addIRPasses() {
413 addPass(P: createAtomicExpandLegacyPass());
414
415 // We add both pass anyway and when these two passes run, we skip the pass
416 // based on the option level and option attribute.
417 addPass(P: createX86LowerAMXIntrinsicsLegacyPass());
418 addPass(P: createX86LowerAMXTypeLegacyPass());
419
420 TargetPassConfig::addIRPasses();
421
422 if (TM->getOptLevel() != CodeGenOptLevel::None) {
423 addPass(P: createInterleavedAccessPass());
424 addPass(P: createX86PartialReductionLegacyPass());
425 }
426
427 // Add passes that handle indirect branch removal and insertion of a retpoline
428 // thunk. These will be a no-op unless a function subtarget has the retpoline
429 // feature enabled.
430 addPass(P: createIndirectBrExpandPass(OptLevel: getOptLevel()));
431
432 // Add Control Flow Guard checks.
433 const Triple &TT = TM->getTargetTriple();
434 if (TT.isOSWindows()) {
435 addPass(P: createCFGuardPass());
436 }
437
438 if (TM->Options.JMCInstrument)
439 addPass(P: createJMCInstrumenterPass());
440}
441
442bool X86PassConfig::addInstSelector() {
443 // Install an instruction selector.
444 addPass(P: createX86ISelDag(TM&: getX86TargetMachine(), OptLevel: getOptLevel()));
445
446 // For ELF, cleanup any local-dynamic TLS accesses.
447 if (TM->getTargetTriple().isOSBinFormatELF() &&
448 getOptLevel() != CodeGenOptLevel::None)
449 addPass(P: createCleanupLocalDynamicTLSLegacyPass());
450
451 addPass(P: createX86GlobalBaseRegLegacyPass());
452 addPass(P: createX86ArgumentStackSlotLegacyPass());
453 return false;
454}
455
456bool X86PassConfig::addIRTranslator() {
457 addPass(P: new IRTranslatorLegacy(getOptLevel()));
458 return false;
459}
460
461void X86PassConfig::addPreRegBankSelect() {
462 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
463 if (!IsOptNone) {
464 addPass(P: createX86PostLegalizerCombinerLegacy());
465 }
466}
467bool X86PassConfig::addLegalizeMachineIR() {
468 addPass(P: new LegalizerLegacy());
469 return false;
470}
471
472bool X86PassConfig::addRegBankSelect() {
473 addPass(P: new RegBankSelectLegacy());
474 return false;
475}
476
477bool X86PassConfig::addGlobalInstructionSelect() {
478 addPass(P: new InstructionSelectLegacy(getOptLevel()));
479 // Add GlobalBaseReg in case there is no SelectionDAG passes afterwards
480 if (isGlobalISelAbortEnabled())
481 addPass(P: createX86GlobalBaseRegLegacyPass());
482 return false;
483}
484
485void X86PassConfig::addPreLegalizeMachineIR() {
486 if (getOptLevel() != CodeGenOptLevel::None) {
487 addPass(P: createX86PreLegalizerCombinerLegacy());
488 }
489}
490
491bool X86PassConfig::addILPOpts() {
492 addPass(PassID: &EarlyIfConverterLegacyID);
493 if (getX86TargetMachine().getCLOpts().machine_combiner)
494 addPass(PassID: &MachineCombinerID);
495 addPass(P: createX86CmovConversionLegacyPass());
496 return true;
497}
498
499bool X86PassConfig::addPreISel() {
500 // Only add this pass for 32-bit x86 Windows.
501 const Triple &TT = TM->getTargetTriple();
502 if (TT.isOSWindows() && TT.isX86_32())
503 addPass(P: createX86WinEHStateLegacyPass());
504 return true;
505}
506
507void X86PassConfig::addPreRegAlloc() {
508 if (getOptLevel() != CodeGenOptLevel::None) {
509 addPass(PassID: &LiveRangeShrinkID);
510 addPass(P: createX86FixupSetCCLegacyPass());
511 addPass(P: createX86OptimizeLEAsLegacyPass());
512 addPass(P: createX86CallFrameOptimizationLegacyPass());
513 addPass(P: createX86AvoidStoreForwardingBlocksLegacyPass());
514 }
515
516 addPass(P: createX86SuppressAPXForRelocationLegacyPass());
517
518 addPass(P: createX86SpeculativeLoadHardeningLegacyPass());
519 addPass(P: createX86FlagsCopyLoweringLegacyPass());
520 addPass(P: createX86DynAllocaExpanderLegacyPass());
521
522 if (getOptLevel() != CodeGenOptLevel::None)
523 addPass(P: createX86PreTileConfigLegacyPass());
524 else
525 addPass(P: createX86FastPreTileConfigLegacyPass());
526}
527
528void X86PassConfig::addMachineSSAOptimization() {
529 addPass(P: createX86DomainReassignmentLegacyPass());
530 TargetPassConfig::addMachineSSAOptimization();
531}
532
533void X86PassConfig::addPostRegAlloc() {
534 addPass(P: createX86LowerTileCopyLegacyPass());
535 addPass(P: createX86FPStackifierLegacyPass());
536 // When -O0 is enabled, the Load Value Injection Hardening pass will fall back
537 // to using the Speculative Execution Side Effect Suppression pass for
538 // mitigation. This is to prevent slow downs due to
539 // analyses needed by the LVIHardening pass when compiling at -O0.
540 if (getOptLevel() != CodeGenOptLevel::None)
541 addPass(P: createX86LoadValueInjectionLoadHardeningLegacyPass());
542}
543
544void X86PassConfig::addPreSched2() {
545 addPass(P: createX86ExpandPseudoLegacyPass());
546 addPass(P: createKCFIPass());
547}
548
549void X86PassConfig::addPreEmitPass() {
550 if (getOptLevel() != CodeGenOptLevel::None) {
551 addPass(P: new X86ExecutionDomainFix());
552 addPass(P: createBreakFalseDepsLegacyPass());
553 }
554
555 addPass(P: createX86IndirectBranchTrackingLegacyPass());
556
557 addPass(P: createX86InsertVZeroUpperLegacyPass());
558
559 if (getOptLevel() != CodeGenOptLevel::None) {
560 addPass(P: createX86FixupBWInstsLegacyPass());
561 addPass(P: createX86PadShortFunctions());
562 addPass(P: createX86FixupLEAsLegacyPass());
563 addPass(P: createX86FixupInstTuningLegacyPass());
564 addPass(P: createX86FixupVectorConstantsLegacyPass());
565 }
566 addPass(P: createX86CompressEVEXLegacyPass());
567 addPass(P: createX86InsertX87WaitLegacyPass());
568
569 if (TM->getTargetTriple().isLFI())
570 addPass(P: createX86LFIRewritePass());
571}
572
573void X86PassConfig::addPreEmitPass2() {
574 const Triple &TT = TM->getTargetTriple();
575 const MCAsmInfo &MAI = TM->getMCAsmInfo();
576
577 // The X86 Speculative Execution Pass must run after all control
578 // flow graph modifying passes. As a result it was listed to run right before
579 // the X86 Retpoline Thunks pass. The reason it must run after control flow
580 // graph modifications is that the model of LFENCE in LLVM has to be updated
581 // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the
582 // placement of this pass was hand checked to ensure that the subsequent
583 // passes don't move the code around the LFENCEs in a way that will hurt the
584 // correctness of this pass. This placement has been shown to work based on
585 // hand inspection of the codegen output.
586 addPass(P: createX86SpeculativeExecutionSideEffectSuppressionLegacyPass());
587 addPass(P: createX86IndirectThunksPass());
588 addPass(P: createX86ReturnThunksLegacyPass());
589
590 // Insert extra int3 instructions after trailing call instructions to avoid
591 // issues in the unwinder.
592 if (TT.isOSWindows() && TT.isX86_64())
593 addPass(P: createX86AvoidTrailingCallLegacyPass());
594
595 // Verify basic block incoming and outgoing cfa offset and register values and
596 // correct CFA calculation rule where needed by inserting appropriate CFI
597 // instructions.
598 if (!TT.isOSDarwin() &&
599 (!TT.isOSWindows() ||
600 MAI.getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
601 addPass(P: createCFIInstrInserterLegacy());
602
603 if (TT.isOSWindows()) {
604 // Identify valid longjmp targets for Windows Control Flow Guard.
605 addPass(P: createCFGuardLongjmpPass());
606 // Identify valid eh continuation targets for Windows EHCont Guard.
607 addPass(P: createEHContGuardTargetsLegacy());
608 }
609 addPass(P: createX86LoadValueInjectionRetHardeningLegacyPass());
610
611 // Insert pseudo probe annotation for callsite profiling
612 addPass(P: createPseudoProbeInserter());
613
614 // KCFI indirect call checks are lowered to a bundle, and on Darwin platforms,
615 // also CALL_RVMARKER.
616 addPass(P: createUnpackMachineBundlesLegacy(Ftor: [&TT](const MachineFunction &MF) {
617 // Only run bundle expansion if the module uses kcfi, or there are relevant
618 // ObjC runtime functions present in the module.
619 const Function &F = MF.getFunction();
620 const Module *M = F.getParent();
621 return M->getModuleFlag(Key: "kcfi") ||
622 (TT.isOSDarwin() &&
623 (M->getFunction(Name: "objc_retainAutoreleasedReturnValue") ||
624 M->getFunction(Name: "objc_unsafeClaimAutoreleasedReturnValue")));
625 }));
626
627 // Analyzes and emits pseudos to support Win x64 Unwind V2. This pass must run
628 // after all real instructions have been added to the epilog.
629 if (TT.isOSWindows() && TT.isX86_64()) {
630 addPass(P: createX86WinEHUnwindV2LegacyPass());
631 addPass(P: createX86WinEHUnwindV3Pass());
632 }
633}
634
635bool X86PassConfig::addPostFastRegAllocRewrite() {
636 addPass(P: createX86FastTileConfigLegacyPass());
637 return true;
638}
639
640std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
641 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
642}
643
644static bool onlyAllocateTileRegisters(const TargetRegisterInfo &TRI,
645 const MachineRegisterInfo &MRI,
646 const Register Reg) {
647 const TargetRegisterClass *RC = MRI.getRegClass(Reg);
648 return static_cast<const X86RegisterInfo &>(TRI).isTileRegisterClass(RC);
649}
650
651bool X86PassConfig::addRegAssignAndRewriteOptimized() {
652 // Don't support tile RA when RA is specified by command line "-regalloc".
653 if (!isCustomizedRegAlloc() && getX86TargetMachine().getCLOpts().tile_ra) {
654 // Allocate tile register first.
655 addPass(P: createGreedyRegisterAllocator(F: onlyAllocateTileRegisters));
656 addPass(P: createX86TileConfigLegacyPass());
657 }
658 return TargetPassConfig::addRegAssignAndRewriteOptimized();
659}
660