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