1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the X86 specific subclass of TargetMachine. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "X86TargetMachine.h" 15 #include "MCTargetDesc/X86MCTargetDesc.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/Pass.h" 42 #include "llvm/Support/CodeGen.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Target/TargetLoweringObjectFile.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include <memory> 49 #include <string> 50 51 using namespace llvm; 52 53 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner", 54 cl::desc("Enable the machine combiner pass"), 55 cl::init(true), cl::Hidden); 56 57 static cl::opt<bool> EnableSpeculativeLoadHardening( 58 "x86-speculative-load-hardening", 59 cl::desc("Enable speculative load hardening"), cl::init(false), cl::Hidden); 60 61 namespace llvm { 62 63 void initializeWinEHStatePassPass(PassRegistry &); 64 void initializeFixupLEAPassPass(PassRegistry &); 65 void initializeShadowCallStackPass(PassRegistry &); 66 void initializeX86CallFrameOptimizationPass(PassRegistry &); 67 void initializeX86CmovConverterPassPass(PassRegistry &); 68 void initializeX86ExecutionDomainFixPass(PassRegistry &); 69 void initializeX86DomainReassignmentPass(PassRegistry &); 70 void initializeX86AvoidSFBPassPass(PassRegistry &); 71 void initializeX86FlagsCopyLoweringPassPass(PassRegistry &); 72 73 } // end namespace llvm 74 75 extern "C" void LLVMInitializeX86Target() { 76 // Register the target. 77 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target()); 78 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target()); 79 80 PassRegistry &PR = *PassRegistry::getPassRegistry(); 81 initializeGlobalISel(PR); 82 initializeWinEHStatePassPass(PR); 83 initializeFixupBWInstPassPass(PR); 84 initializeEvexToVexInstPassPass(PR); 85 initializeFixupLEAPassPass(PR); 86 initializeShadowCallStackPass(PR); 87 initializeX86CallFrameOptimizationPass(PR); 88 initializeX86CmovConverterPassPass(PR); 89 initializeX86ExecutionDomainFixPass(PR); 90 initializeX86DomainReassignmentPass(PR); 91 initializeX86AvoidSFBPassPass(PR); 92 initializeX86FlagsCopyLoweringPassPass(PR); 93 } 94 95 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 96 if (TT.isOSBinFormatMachO()) { 97 if (TT.getArch() == Triple::x86_64) 98 return llvm::make_unique<X86_64MachoTargetObjectFile>(); 99 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 100 } 101 102 if (TT.isOSFreeBSD()) 103 return llvm::make_unique<X86FreeBSDTargetObjectFile>(); 104 if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU()) 105 return llvm::make_unique<X86LinuxNaClTargetObjectFile>(); 106 if (TT.isOSSolaris()) 107 return llvm::make_unique<X86SolarisTargetObjectFile>(); 108 if (TT.isOSFuchsia()) 109 return llvm::make_unique<X86FuchsiaTargetObjectFile>(); 110 if (TT.isOSBinFormatELF()) 111 return llvm::make_unique<X86ELFTargetObjectFile>(); 112 if (TT.isOSBinFormatCOFF()) 113 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 114 llvm_unreachable("unknown subtarget type"); 115 } 116 117 static std::string computeDataLayout(const Triple &TT) { 118 // X86 is little endian 119 std::string Ret = "e"; 120 121 Ret += DataLayout::getManglingComponent(TT); 122 // X86 and x32 have 32 bit pointers. 123 if ((TT.isArch64Bit() && 124 (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || 125 !TT.isArch64Bit()) 126 Ret += "-p:32:32"; 127 128 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. 129 if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl()) 130 Ret += "-i64:64"; 131 else if (TT.isOSIAMCU()) 132 Ret += "-i64:32-f64:32"; 133 else 134 Ret += "-f64:32:64"; 135 136 // Some ABIs align long double to 128 bits, others to 32. 137 if (TT.isOSNaCl() || TT.isOSIAMCU()) 138 ; // No f80 139 else if (TT.isArch64Bit() || TT.isOSDarwin()) 140 Ret += "-f80:128"; 141 else 142 Ret += "-f80:32"; 143 144 if (TT.isOSIAMCU()) 145 Ret += "-f128:32"; 146 147 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. 148 if (TT.isArch64Bit()) 149 Ret += "-n8:16:32:64"; 150 else 151 Ret += "-n8:16:32"; 152 153 // The stack is aligned to 32 bits on some ABIs and 128 bits on others. 154 if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU()) 155 Ret += "-a:0:32-S32"; 156 else 157 Ret += "-S128"; 158 159 return Ret; 160 } 161 162 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 163 bool JIT, 164 Optional<Reloc::Model> RM) { 165 bool is64Bit = TT.getArch() == Triple::x86_64; 166 if (!RM.hasValue()) { 167 // JIT codegen should use static relocations by default, since it's 168 // typically executed in process and not relocatable. 169 if (JIT) 170 return Reloc::Static; 171 172 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode. 173 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we 174 // use static relocation model by default. 175 if (TT.isOSDarwin()) { 176 if (is64Bit) 177 return Reloc::PIC_; 178 return Reloc::DynamicNoPIC; 179 } 180 if (TT.isOSWindows() && is64Bit) 181 return Reloc::PIC_; 182 return Reloc::Static; 183 } 184 185 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC 186 // is defined as a model for code which may be used in static or dynamic 187 // executables but not necessarily a shared library. On X86-32 we just 188 // compile in -static mode, in x86-64 we use PIC. 189 if (*RM == Reloc::DynamicNoPIC) { 190 if (is64Bit) 191 return Reloc::PIC_; 192 if (!TT.isOSDarwin()) 193 return Reloc::Static; 194 } 195 196 // If we are on Darwin, disallow static relocation model in X86-64 mode, since 197 // the Mach-O file format doesn't support it. 198 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit) 199 return Reloc::PIC_; 200 201 return *RM; 202 } 203 204 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM, 205 bool JIT, bool Is64Bit) { 206 if (CM) 207 return *CM; 208 if (JIT) 209 return Is64Bit ? CodeModel::Large : CodeModel::Small; 210 return CodeModel::Small; 211 } 212 213 /// Create an X86 target. 214 /// 215 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, 216 StringRef CPU, StringRef FS, 217 const TargetOptions &Options, 218 Optional<Reloc::Model> RM, 219 Optional<CodeModel::Model> CM, 220 CodeGenOpt::Level OL, bool JIT) 221 : LLVMTargetMachine( 222 T, computeDataLayout(TT), TT, CPU, FS, Options, 223 getEffectiveRelocModel(TT, JIT, RM), 224 getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL), 225 TLOF(createTLOF(getTargetTriple())) { 226 // Windows stack unwinder gets confused when execution flow "falls through" 227 // after a call to 'noreturn' function. 228 // To prevent that, we emit a trap for 'unreachable' IR instructions. 229 // (which on X86, happens to be the 'ud2' instruction) 230 // On PS4, the "return address" of a 'noreturn' call must still be within 231 // the calling function, and TrapUnreachable is an easy way to get that. 232 // The check here for 64-bit windows is a bit icky, but as we're unlikely 233 // to ever want to mix 32 and 64-bit windows code in a single module 234 // this should be fine. 235 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4() || 236 TT.isOSBinFormatMachO()) { 237 this->Options.TrapUnreachable = true; 238 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO(); 239 } 240 241 // Outlining is available for x86-64. 242 if (TT.getArch() == Triple::x86_64) 243 setMachineOutliner(true); 244 245 initAsmInfo(); 246 } 247 248 X86TargetMachine::~X86TargetMachine() = default; 249 250 const X86Subtarget * 251 X86TargetMachine::getSubtargetImpl(const Function &F) const { 252 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 253 Attribute FSAttr = F.getFnAttribute("target-features"); 254 255 StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) 256 ? CPUAttr.getValueAsString() 257 : (StringRef)TargetCPU; 258 StringRef FS = !FSAttr.hasAttribute(Attribute::None) 259 ? FSAttr.getValueAsString() 260 : (StringRef)TargetFS; 261 262 SmallString<512> Key; 263 Key.reserve(CPU.size() + FS.size()); 264 Key += CPU; 265 Key += FS; 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 = 273 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 274 // If the soft float attribute is set on the function turn on the soft float 275 // subtarget feature. 276 if (SoftFloat) 277 Key += FS.empty() ? "+soft-float" : ",+soft-float"; 278 279 // Keep track of the key width after all features are added so we can extract 280 // the feature string out later. 281 unsigned CPUFSWidth = Key.size(); 282 283 // Extract prefer-vector-width attribute. 284 unsigned PreferVectorWidthOverride = 0; 285 if (F.hasFnAttribute("prefer-vector-width")) { 286 StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString(); 287 unsigned Width; 288 if (!Val.getAsInteger(0, Width)) { 289 Key += ",prefer-vector-width="; 290 Key += Val; 291 PreferVectorWidthOverride = Width; 292 } 293 } 294 295 // Extract required-vector-width attribute. 296 unsigned RequiredVectorWidth = UINT32_MAX; 297 if (F.hasFnAttribute("required-vector-width")) { 298 StringRef Val = F.getFnAttribute("required-vector-width").getValueAsString(); 299 unsigned Width; 300 if (!Val.getAsInteger(0, Width)) { 301 Key += ",required-vector-width="; 302 Key += Val; 303 RequiredVectorWidth = Width; 304 } 305 } 306 307 // Extracted here so that we make sure there is backing for the StringRef. If 308 // we assigned earlier, its possible the SmallString reallocated leaving a 309 // dangling StringRef. 310 FS = Key.slice(CPU.size(), CPUFSWidth); 311 312 auto &I = SubtargetMap[Key]; 313 if (!I) { 314 // This needs to be done before we create a new subtarget since any 315 // creation will depend on the TM and the code generation flags on the 316 // function that reside in TargetOptions. 317 resetTargetOptions(F); 318 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, 319 Options.StackAlignmentOverride, 320 PreferVectorWidthOverride, 321 RequiredVectorWidth); 322 } 323 return I.get(); 324 } 325 326 //===----------------------------------------------------------------------===// 327 // Command line options for x86 328 //===----------------------------------------------------------------------===// 329 static cl::opt<bool> 330 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, 331 cl::desc("Minimize AVX to SSE transition penalty"), 332 cl::init(true)); 333 334 //===----------------------------------------------------------------------===// 335 // X86 TTI query. 336 //===----------------------------------------------------------------------===// 337 338 TargetTransformInfo 339 X86TargetMachine::getTargetTransformInfo(const Function &F) { 340 return TargetTransformInfo(X86TTIImpl(this, F)); 341 } 342 343 //===----------------------------------------------------------------------===// 344 // Pass Pipeline Configuration 345 //===----------------------------------------------------------------------===// 346 347 namespace { 348 349 /// X86 Code Generator Pass Configuration Options. 350 class X86PassConfig : public TargetPassConfig { 351 public: 352 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM) 353 : TargetPassConfig(TM, PM) {} 354 355 X86TargetMachine &getX86TargetMachine() const { 356 return getTM<X86TargetMachine>(); 357 } 358 359 ScheduleDAGInstrs * 360 createMachineScheduler(MachineSchedContext *C) const override { 361 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 362 DAG->addMutation(createX86MacroFusionDAGMutation()); 363 return DAG; 364 } 365 366 void addIRPasses() override; 367 bool addInstSelector() override; 368 bool addIRTranslator() override; 369 bool addLegalizeMachineIR() override; 370 bool addRegBankSelect() override; 371 bool addGlobalInstructionSelect() override; 372 bool addILPOpts() override; 373 bool addPreISel() override; 374 void addMachineSSAOptimization() override; 375 void addPreRegAlloc() override; 376 void addPostRegAlloc() override; 377 void addPreEmitPass() override; 378 void addPreEmitPass2() override; 379 void addPreSched2() override; 380 }; 381 382 class X86ExecutionDomainFix : public ExecutionDomainFix { 383 public: 384 static char ID; 385 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {} 386 StringRef getPassName() const override { 387 return "X86 Execution Dependency Fix"; 388 } 389 }; 390 char X86ExecutionDomainFix::ID; 391 392 } // end anonymous namespace 393 394 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix", 395 "X86 Execution Domain Fix", false, false) 396 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 397 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix", 398 "X86 Execution Domain Fix", false, false) 399 400 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { 401 return new X86PassConfig(*this, PM); 402 } 403 404 void X86PassConfig::addIRPasses() { 405 addPass(createAtomicExpandPass()); 406 407 TargetPassConfig::addIRPasses(); 408 409 if (TM->getOptLevel() != CodeGenOpt::None) 410 addPass(createInterleavedAccessPass()); 411 412 // Add passes that handle indirect branch removal and insertion of a retpoline 413 // thunk. These will be a no-op unless a function subtarget has the retpoline 414 // feature enabled. 415 addPass(createIndirectBrExpandPass()); 416 } 417 418 bool X86PassConfig::addInstSelector() { 419 // Install an instruction selector. 420 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); 421 422 // For ELF, cleanup any local-dynamic TLS accesses. 423 if (TM->getTargetTriple().isOSBinFormatELF() && 424 getOptLevel() != CodeGenOpt::None) 425 addPass(createCleanupLocalDynamicTLSPass()); 426 427 addPass(createX86GlobalBaseRegPass()); 428 return false; 429 } 430 431 bool X86PassConfig::addIRTranslator() { 432 addPass(new IRTranslator()); 433 return false; 434 } 435 436 bool X86PassConfig::addLegalizeMachineIR() { 437 addPass(new Legalizer()); 438 return false; 439 } 440 441 bool X86PassConfig::addRegBankSelect() { 442 addPass(new RegBankSelect()); 443 return false; 444 } 445 446 bool X86PassConfig::addGlobalInstructionSelect() { 447 addPass(new InstructionSelect()); 448 return false; 449 } 450 451 bool X86PassConfig::addILPOpts() { 452 addPass(&EarlyIfConverterID); 453 if (EnableMachineCombinerPass) 454 addPass(&MachineCombinerID); 455 addPass(createX86CmovConverterPass()); 456 return true; 457 } 458 459 bool X86PassConfig::addPreISel() { 460 // Only add this pass for 32-bit x86 Windows. 461 const Triple &TT = TM->getTargetTriple(); 462 if (TT.isOSWindows() && TT.getArch() == Triple::x86) 463 addPass(createX86WinEHStatePass()); 464 return true; 465 } 466 467 void X86PassConfig::addPreRegAlloc() { 468 if (getOptLevel() != CodeGenOpt::None) { 469 addPass(&LiveRangeShrinkID); 470 addPass(createX86FixupSetCC()); 471 addPass(createX86OptimizeLEAs()); 472 addPass(createX86CallFrameOptimization()); 473 addPass(createX86AvoidStoreForwardingBlocks()); 474 } 475 476 if (EnableSpeculativeLoadHardening) 477 addPass(createX86SpeculativeLoadHardeningPass()); 478 479 addPass(createX86FlagsCopyLoweringPass()); 480 addPass(createX86WinAllocaExpander()); 481 } 482 void X86PassConfig::addMachineSSAOptimization() { 483 addPass(createX86DomainReassignmentPass()); 484 TargetPassConfig::addMachineSSAOptimization(); 485 } 486 487 void X86PassConfig::addPostRegAlloc() { 488 addPass(createX86FloatingPointStackifierPass()); 489 } 490 491 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } 492 493 void X86PassConfig::addPreEmitPass() { 494 if (getOptLevel() != CodeGenOpt::None) { 495 addPass(new X86ExecutionDomainFix()); 496 addPass(createBreakFalseDeps()); 497 } 498 499 addPass(createShadowCallStackPass()); 500 addPass(createX86IndirectBranchTrackingPass()); 501 502 if (UseVZeroUpper) 503 addPass(createX86IssueVZeroUpperPass()); 504 505 if (getOptLevel() != CodeGenOpt::None) { 506 addPass(createX86FixupBWInsts()); 507 addPass(createX86PadShortFunctions()); 508 addPass(createX86FixupLEAs()); 509 addPass(createX86EvexToVexInsts()); 510 } 511 } 512 513 void X86PassConfig::addPreEmitPass2() { 514 addPass(createX86RetpolineThunksPass()); 515 // Verify basic block incoming and outgoing cfa offset and register values and 516 // correct CFA calculation rule where needed by inserting appropriate CFI 517 // instructions. 518 const Triple &TT = TM->getTargetTriple(); 519 if (!TT.isOSDarwin() && !TT.isOSWindows()) 520 addPass(createCFIInstrInserter()); 521 } 522