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 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86Target() { 60 // Register the target. 61 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target()); 62 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target()); 63 64 PassRegistry &PR = *PassRegistry::getPassRegistry(); 65 initializeGlobalISel(PR); 66 initializeWinEHStatePassPass(PR); 67 initializeFixupBWInstPassPass(PR); 68 initializeEvexToVexInstPassPass(PR); 69 initializeFixupLEAPassPass(PR); 70 initializeFPSPass(PR); 71 initializeX86FixupSetCCPassPass(PR); 72 initializeX86CallFrameOptimizationPass(PR); 73 initializeX86CmovConverterPassPass(PR); 74 initializeX86ExpandPseudoPass(PR); 75 initializeX86ExecutionDomainFixPass(PR); 76 initializeX86DomainReassignmentPass(PR); 77 initializeX86AvoidSFBPassPass(PR); 78 initializeX86AvoidTrailingCallPassPass(PR); 79 initializeX86SpeculativeLoadHardeningPassPass(PR); 80 initializeX86SpeculativeExecutionSideEffectSuppressionPass(PR); 81 initializeX86FlagsCopyLoweringPassPass(PR); 82 initializeX86LoadValueInjectionLoadHardeningPassPass(PR); 83 initializeX86LoadValueInjectionRetHardeningPassPass(PR); 84 initializeX86OptimizeLEAPassPass(PR); 85 initializeX86PartialReductionPass(PR); 86 initializePseudoProbeInserterPass(PR); 87 } 88 89 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 90 if (TT.isOSBinFormatMachO()) { 91 if (TT.getArch() == Triple::x86_64) 92 return std::make_unique<X86_64MachoTargetObjectFile>(); 93 return std::make_unique<TargetLoweringObjectFileMachO>(); 94 } 95 96 if (TT.isOSBinFormatCOFF()) 97 return std::make_unique<TargetLoweringObjectFileCOFF>(); 98 return std::make_unique<X86ELFTargetObjectFile>(); 99 } 100 101 static std::string computeDataLayout(const Triple &TT) { 102 // X86 is little endian 103 std::string Ret = "e"; 104 105 Ret += DataLayout::getManglingComponent(TT); 106 // X86 and x32 have 32 bit pointers. 107 if ((TT.isArch64Bit() && 108 (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || 109 !TT.isArch64Bit()) 110 Ret += "-p:32:32"; 111 112 // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers. 113 Ret += "-p270:32:32-p271:32:32-p272:64:64"; 114 115 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. 116 if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl()) 117 Ret += "-i64:64"; 118 else if (TT.isOSIAMCU()) 119 Ret += "-i64:32-f64:32"; 120 else 121 Ret += "-f64:32:64"; 122 123 // Some ABIs align long double to 128 bits, others to 32. 124 if (TT.isOSNaCl() || TT.isOSIAMCU()) 125 ; // No f80 126 else if (TT.isArch64Bit() || TT.isOSDarwin()) 127 Ret += "-f80:128"; 128 else 129 Ret += "-f80:32"; 130 131 if (TT.isOSIAMCU()) 132 Ret += "-f128:32"; 133 134 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. 135 if (TT.isArch64Bit()) 136 Ret += "-n8:16:32:64"; 137 else 138 Ret += "-n8:16:32"; 139 140 // The stack is aligned to 32 bits on some ABIs and 128 bits on others. 141 if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU()) 142 Ret += "-a:0:32-S32"; 143 else 144 Ret += "-S128"; 145 146 return Ret; 147 } 148 149 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 150 bool JIT, 151 Optional<Reloc::Model> RM) { 152 bool is64Bit = TT.getArch() == Triple::x86_64; 153 if (!RM.hasValue()) { 154 // JIT codegen should use static relocations by default, since it's 155 // typically executed in process and not relocatable. 156 if (JIT) 157 return Reloc::Static; 158 159 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode. 160 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we 161 // use static relocation model by default. 162 if (TT.isOSDarwin()) { 163 if (is64Bit) 164 return Reloc::PIC_; 165 return Reloc::DynamicNoPIC; 166 } 167 if (TT.isOSWindows() && is64Bit) 168 return Reloc::PIC_; 169 return Reloc::Static; 170 } 171 172 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC 173 // is defined as a model for code which may be used in static or dynamic 174 // executables but not necessarily a shared library. On X86-32 we just 175 // compile in -static mode, in x86-64 we use PIC. 176 if (*RM == Reloc::DynamicNoPIC) { 177 if (is64Bit) 178 return Reloc::PIC_; 179 if (!TT.isOSDarwin()) 180 return Reloc::Static; 181 } 182 183 // If we are on Darwin, disallow static relocation model in X86-64 mode, since 184 // the Mach-O file format doesn't support it. 185 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit) 186 return Reloc::PIC_; 187 188 return *RM; 189 } 190 191 static CodeModel::Model getEffectiveX86CodeModel(Optional<CodeModel::Model> CM, 192 bool JIT, bool Is64Bit) { 193 if (CM) { 194 if (*CM == CodeModel::Tiny) 195 report_fatal_error("Target does not support the tiny CodeModel", false); 196 return *CM; 197 } 198 if (JIT) 199 return Is64Bit ? CodeModel::Large : CodeModel::Small; 200 return CodeModel::Small; 201 } 202 203 /// Create an X86 target. 204 /// 205 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, 206 StringRef CPU, StringRef FS, 207 const TargetOptions &Options, 208 Optional<Reloc::Model> RM, 209 Optional<CodeModel::Model> CM, 210 CodeGenOpt::Level OL, bool JIT) 211 : LLVMTargetMachine( 212 T, computeDataLayout(TT), TT, CPU, FS, Options, 213 getEffectiveRelocModel(TT, JIT, RM), 214 getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64), 215 OL), 216 TLOF(createTLOF(getTargetTriple())), IsJIT(JIT) { 217 // On PS4, the "return address" of a 'noreturn' call must still be within 218 // the calling function, and TrapUnreachable is an easy way to get that. 219 if (TT.isPS4() || TT.isOSBinFormatMachO()) { 220 this->Options.TrapUnreachable = true; 221 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO(); 222 } 223 224 setMachineOutliner(true); 225 226 // x86 supports the debug entry values. 227 setSupportsDebugEntryValues(true); 228 229 initAsmInfo(); 230 } 231 232 X86TargetMachine::~X86TargetMachine() = default; 233 234 const X86Subtarget * 235 X86TargetMachine::getSubtargetImpl(const Function &F) const { 236 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 237 Attribute TuneAttr = F.getFnAttribute("tune-cpu"); 238 Attribute FSAttr = F.getFnAttribute("target-features"); 239 240 StringRef CPU = 241 CPUAttr.isValid() ? CPUAttr.getValueAsString() : (StringRef)TargetCPU; 242 StringRef TuneCPU = 243 TuneAttr.isValid() ? TuneAttr.getValueAsString() : (StringRef)CPU; 244 StringRef FS = 245 FSAttr.isValid() ? FSAttr.getValueAsString() : (StringRef)TargetFS; 246 247 SmallString<512> Key; 248 // The additions here are ordered so that the definitely short strings are 249 // added first so we won't exceed the small size. We append the 250 // much longer FS string at the end so that we only heap allocate at most 251 // one time. 252 253 // Extract prefer-vector-width attribute. 254 unsigned PreferVectorWidthOverride = 0; 255 Attribute PreferVecWidthAttr = F.getFnAttribute("prefer-vector-width"); 256 if (PreferVecWidthAttr.isValid()) { 257 StringRef Val = PreferVecWidthAttr.getValueAsString(); 258 unsigned Width; 259 if (!Val.getAsInteger(0, Width)) { 260 Key += "prefer-vector-width="; 261 Key += Val; 262 PreferVectorWidthOverride = Width; 263 } 264 } 265 266 // Extract min-legal-vector-width attribute. 267 unsigned RequiredVectorWidth = UINT32_MAX; 268 Attribute MinLegalVecWidthAttr = F.getFnAttribute("min-legal-vector-width"); 269 if (MinLegalVecWidthAttr.isValid()) { 270 StringRef Val = MinLegalVecWidthAttr.getValueAsString(); 271 unsigned Width; 272 if (!Val.getAsInteger(0, Width)) { 273 Key += "min-legal-vector-width="; 274 Key += Val; 275 RequiredVectorWidth = Width; 276 } 277 } 278 279 // Add CPU to the Key. 280 Key += CPU; 281 282 // Add tune CPU to the Key. 283 Key += "tune="; 284 Key += TuneCPU; 285 286 // Keep track of the start of the feature portion of the string. 287 unsigned FSStart = Key.size(); 288 289 // FIXME: This is related to the code below to reset the target options, 290 // we need to know whether or not the soft float flag is set on the 291 // function before we can generate a subtarget. We also need to use 292 // it as a key for the subtarget since that can be the only difference 293 // between two functions. 294 bool SoftFloat = 295 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 296 // If the soft float attribute is set on the function turn on the soft float 297 // subtarget feature. 298 if (SoftFloat) 299 Key += FS.empty() ? "+soft-float" : "+soft-float,"; 300 301 Key += FS; 302 303 // We may have added +soft-float to the features so move the StringRef to 304 // point to the full string in the Key. 305 FS = Key.substr(FSStart); 306 307 auto &I = SubtargetMap[Key]; 308 if (!I) { 309 // This needs to be done before we create a new subtarget since any 310 // creation will depend on the TM and the code generation flags on the 311 // function that reside in TargetOptions. 312 resetTargetOptions(F); 313 I = std::make_unique<X86Subtarget>( 314 TargetTriple, CPU, TuneCPU, FS, *this, 315 MaybeAlign(Options.StackAlignmentOverride), PreferVectorWidthOverride, 316 RequiredVectorWidth); 317 } 318 return I.get(); 319 } 320 321 bool X86TargetMachine::isNoopAddrSpaceCast(unsigned SrcAS, 322 unsigned DestAS) const { 323 assert(SrcAS != DestAS && "Expected different address spaces!"); 324 if (getPointerSize(SrcAS) != getPointerSize(DestAS)) 325 return false; 326 return SrcAS < 256 && DestAS < 256; 327 } 328 329 //===----------------------------------------------------------------------===// 330 // X86 TTI query. 331 //===----------------------------------------------------------------------===// 332 333 TargetTransformInfo 334 X86TargetMachine::getTargetTransformInfo(const Function &F) { 335 return TargetTransformInfo(X86TTIImpl(this, F)); 336 } 337 338 //===----------------------------------------------------------------------===// 339 // Pass Pipeline Configuration 340 //===----------------------------------------------------------------------===// 341 342 namespace { 343 344 /// X86 Code Generator Pass Configuration Options. 345 class X86PassConfig : public TargetPassConfig { 346 public: 347 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM) 348 : TargetPassConfig(TM, PM) {} 349 350 X86TargetMachine &getX86TargetMachine() const { 351 return getTM<X86TargetMachine>(); 352 } 353 354 ScheduleDAGInstrs * 355 createMachineScheduler(MachineSchedContext *C) const override { 356 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 357 DAG->addMutation(createX86MacroFusionDAGMutation()); 358 return DAG; 359 } 360 361 ScheduleDAGInstrs * 362 createPostMachineScheduler(MachineSchedContext *C) const override { 363 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 364 DAG->addMutation(createX86MacroFusionDAGMutation()); 365 return DAG; 366 } 367 368 void addIRPasses() override; 369 bool addInstSelector() override; 370 bool addIRTranslator() override; 371 bool addLegalizeMachineIR() override; 372 bool addRegBankSelect() override; 373 bool addGlobalInstructionSelect() override; 374 bool addILPOpts() override; 375 bool addPreISel() override; 376 void addMachineSSAOptimization() override; 377 void addPreRegAlloc() override; 378 void addPostRegAlloc() override; 379 void addPreEmitPass() override; 380 void addPreEmitPass2() override; 381 void addPreSched2() override; 382 383 std::unique_ptr<CSEConfigBase> getCSEConfig() const override; 384 }; 385 386 class X86ExecutionDomainFix : public ExecutionDomainFix { 387 public: 388 static char ID; 389 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {} 390 StringRef getPassName() const override { 391 return "X86 Execution Dependency Fix"; 392 } 393 }; 394 char X86ExecutionDomainFix::ID; 395 396 } // end anonymous namespace 397 398 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix", 399 "X86 Execution Domain Fix", false, false) 400 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 401 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix", 402 "X86 Execution Domain Fix", false, false) 403 404 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { 405 return new X86PassConfig(*this, PM); 406 } 407 408 void X86PassConfig::addIRPasses() { 409 addPass(createAtomicExpandPass()); 410 411 TargetPassConfig::addIRPasses(); 412 413 if (TM->getOptLevel() != CodeGenOpt::None) { 414 addPass(createInterleavedAccessPass()); 415 addPass(createX86PartialReductionPass()); 416 } 417 418 // Add passes that handle indirect branch removal and insertion of a retpoline 419 // thunk. These will be a no-op unless a function subtarget has the retpoline 420 // feature enabled. 421 addPass(createIndirectBrExpandPass()); 422 423 // Add Control Flow Guard checks. 424 const Triple &TT = TM->getTargetTriple(); 425 if (TT.isOSWindows()) { 426 if (TT.getArch() == Triple::x86_64) { 427 addPass(createCFGuardDispatchPass()); 428 } else { 429 addPass(createCFGuardCheckPass()); 430 } 431 } 432 } 433 434 bool X86PassConfig::addInstSelector() { 435 // Install an instruction selector. 436 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); 437 438 // For ELF, cleanup any local-dynamic TLS accesses. 439 if (TM->getTargetTriple().isOSBinFormatELF() && 440 getOptLevel() != CodeGenOpt::None) 441 addPass(createCleanupLocalDynamicTLSPass()); 442 443 addPass(createX86GlobalBaseRegPass()); 444 return false; 445 } 446 447 bool X86PassConfig::addIRTranslator() { 448 addPass(new IRTranslator(getOptLevel())); 449 return false; 450 } 451 452 bool X86PassConfig::addLegalizeMachineIR() { 453 addPass(new Legalizer()); 454 return false; 455 } 456 457 bool X86PassConfig::addRegBankSelect() { 458 addPass(new RegBankSelect()); 459 return false; 460 } 461 462 bool X86PassConfig::addGlobalInstructionSelect() { 463 addPass(new InstructionSelect()); 464 return false; 465 } 466 467 bool X86PassConfig::addILPOpts() { 468 addPass(&EarlyIfConverterID); 469 if (EnableMachineCombinerPass) 470 addPass(&MachineCombinerID); 471 addPass(createX86CmovConverterPass()); 472 return true; 473 } 474 475 bool X86PassConfig::addPreISel() { 476 // Only add this pass for 32-bit x86 Windows. 477 const Triple &TT = TM->getTargetTriple(); 478 if (TT.isOSWindows() && TT.getArch() == Triple::x86) 479 addPass(createX86WinEHStatePass()); 480 return true; 481 } 482 483 void X86PassConfig::addPreRegAlloc() { 484 if (getOptLevel() != CodeGenOpt::None) { 485 addPass(&LiveRangeShrinkID); 486 addPass(createX86FixupSetCC()); 487 addPass(createX86OptimizeLEAs()); 488 addPass(createX86CallFrameOptimization()); 489 addPass(createX86AvoidStoreForwardingBlocks()); 490 } 491 492 addPass(createX86SpeculativeLoadHardeningPass()); 493 addPass(createX86FlagsCopyLoweringPass()); 494 addPass(createX86WinAllocaExpander()); 495 } 496 void X86PassConfig::addMachineSSAOptimization() { 497 addPass(createX86DomainReassignmentPass()); 498 TargetPassConfig::addMachineSSAOptimization(); 499 } 500 501 void X86PassConfig::addPostRegAlloc() { 502 addPass(createX86FloatingPointStackifierPass()); 503 // When -O0 is enabled, the Load Value Injection Hardening pass will fall back 504 // to using the Speculative Execution Side Effect Suppression pass for 505 // mitigation. This is to prevent slow downs due to 506 // analyses needed by the LVIHardening pass when compiling at -O0. 507 if (getOptLevel() != CodeGenOpt::None) 508 addPass(createX86LoadValueInjectionLoadHardeningPass()); 509 } 510 511 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } 512 513 void X86PassConfig::addPreEmitPass() { 514 if (getOptLevel() != CodeGenOpt::None) { 515 addPass(new X86ExecutionDomainFix()); 516 addPass(createBreakFalseDeps()); 517 } 518 519 addPass(createX86IndirectBranchTrackingPass()); 520 521 addPass(createX86IssueVZeroUpperPass()); 522 523 if (getOptLevel() != CodeGenOpt::None) { 524 addPass(createX86FixupBWInsts()); 525 addPass(createX86PadShortFunctions()); 526 addPass(createX86FixupLEAs()); 527 } 528 addPass(createX86EvexToVexInsts()); 529 addPass(createX86DiscriminateMemOpsPass()); 530 addPass(createX86InsertPrefetchPass()); 531 addPass(createX86InsertX87waitPass()); 532 } 533 534 void X86PassConfig::addPreEmitPass2() { 535 const Triple &TT = TM->getTargetTriple(); 536 const MCAsmInfo *MAI = TM->getMCAsmInfo(); 537 538 // The X86 Speculative Execution Pass must run after all control 539 // flow graph modifying passes. As a result it was listed to run right before 540 // the X86 Retpoline Thunks pass. The reason it must run after control flow 541 // graph modifications is that the model of LFENCE in LLVM has to be updated 542 // (FIXME: https://bugs.llvm.org/show_bug.cgi?id=45167). Currently the 543 // placement of this pass was hand checked to ensure that the subsequent 544 // passes don't move the code around the LFENCEs in a way that will hurt the 545 // correctness of this pass. This placement has been shown to work based on 546 // hand inspection of the codegen output. 547 addPass(createX86SpeculativeExecutionSideEffectSuppression()); 548 addPass(createX86IndirectThunksPass()); 549 550 // Insert extra int3 instructions after trailing call instructions to avoid 551 // issues in the unwinder. 552 if (TT.isOSWindows() && TT.getArch() == Triple::x86_64) 553 addPass(createX86AvoidTrailingCallPass()); 554 555 // Verify basic block incoming and outgoing cfa offset and register values and 556 // correct CFA calculation rule where needed by inserting appropriate CFI 557 // instructions. 558 if (!TT.isOSDarwin() && 559 (!TT.isOSWindows() || 560 MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI)) 561 addPass(createCFIInstrInserter()); 562 // Identify valid longjmp targets for Windows Control Flow Guard. 563 if (TT.isOSWindows()) 564 addPass(createCFGuardLongjmpPass()); 565 addPass(createX86LoadValueInjectionRetHardeningPass()); 566 } 567 568 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const { 569 return getStandardCSEConfigForOpt(TM->getOptLevel()); 570 } 571