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