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 Optional<Reloc::Model> RM) { 164 bool is64Bit = TT.getArch() == Triple::x86_64; 165 if (!RM.hasValue()) { 166 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode. 167 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we 168 // use static relocation model by default. 169 if (TT.isOSDarwin()) { 170 if (is64Bit) 171 return Reloc::PIC_; 172 return Reloc::DynamicNoPIC; 173 } 174 if (TT.isOSWindows() && is64Bit) 175 return Reloc::PIC_; 176 return Reloc::Static; 177 } 178 179 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC 180 // is defined as a model for code which may be used in static or dynamic 181 // executables but not necessarily a shared library. On X86-32 we just 182 // compile in -static mode, in x86-64 we use PIC. 183 if (*RM == Reloc::DynamicNoPIC) { 184 if (is64Bit) 185 return Reloc::PIC_; 186 if (!TT.isOSDarwin()) 187 return Reloc::Static; 188 } 189 190 // If we are on Darwin, disallow static relocation model in X86-64 mode, since 191 // the Mach-O file format doesn't support it. 192 if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit) 193 return Reloc::PIC_; 194 195 return *RM; 196 } 197 198 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM, 199 bool JIT, bool Is64Bit) { 200 if (CM) 201 return *CM; 202 if (JIT) 203 return Is64Bit ? CodeModel::Large : CodeModel::Small; 204 return CodeModel::Small; 205 } 206 207 /// Create an X86 target. 208 /// 209 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, 210 StringRef CPU, StringRef FS, 211 const TargetOptions &Options, 212 Optional<Reloc::Model> RM, 213 Optional<CodeModel::Model> CM, 214 CodeGenOpt::Level OL, bool JIT) 215 : LLVMTargetMachine( 216 T, computeDataLayout(TT), TT, CPU, FS, Options, 217 getEffectiveRelocModel(TT, RM), 218 getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL), 219 TLOF(createTLOF(getTargetTriple())) { 220 // Windows stack unwinder gets confused when execution flow "falls through" 221 // after a call to 'noreturn' function. 222 // To prevent that, we emit a trap for 'unreachable' IR instructions. 223 // (which on X86, happens to be the 'ud2' instruction) 224 // On PS4, the "return address" of a 'noreturn' call must still be within 225 // the calling function, and TrapUnreachable is an easy way to get that. 226 // The check here for 64-bit windows is a bit icky, but as we're unlikely 227 // to ever want to mix 32 and 64-bit windows code in a single module 228 // this should be fine. 229 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4() || 230 TT.isOSBinFormatMachO()) { 231 this->Options.TrapUnreachable = true; 232 this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO(); 233 } 234 235 // Outlining is available for x86-64. 236 if (TT.getArch() == Triple::x86_64) 237 setMachineOutliner(true); 238 239 initAsmInfo(); 240 } 241 242 X86TargetMachine::~X86TargetMachine() = default; 243 244 const X86Subtarget * 245 X86TargetMachine::getSubtargetImpl(const Function &F) const { 246 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 247 Attribute FSAttr = F.getFnAttribute("target-features"); 248 249 StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) 250 ? CPUAttr.getValueAsString() 251 : (StringRef)TargetCPU; 252 StringRef FS = !FSAttr.hasAttribute(Attribute::None) 253 ? FSAttr.getValueAsString() 254 : (StringRef)TargetFS; 255 256 SmallString<512> Key; 257 Key.reserve(CPU.size() + FS.size()); 258 Key += CPU; 259 Key += FS; 260 261 // FIXME: This is related to the code below to reset the target options, 262 // we need to know whether or not the soft float flag is set on the 263 // function before we can generate a subtarget. We also need to use 264 // it as a key for the subtarget since that can be the only difference 265 // between two functions. 266 bool SoftFloat = 267 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 268 // If the soft float attribute is set on the function turn on the soft float 269 // subtarget feature. 270 if (SoftFloat) 271 Key += FS.empty() ? "+soft-float" : ",+soft-float"; 272 273 // Keep track of the key width after all features are added so we can extract 274 // the feature string out later. 275 unsigned CPUFSWidth = Key.size(); 276 277 // Extract prefer-vector-width attribute. 278 unsigned PreferVectorWidthOverride = 0; 279 if (F.hasFnAttribute("prefer-vector-width")) { 280 StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString(); 281 unsigned Width; 282 if (!Val.getAsInteger(0, Width)) { 283 Key += ",prefer-vector-width="; 284 Key += Val; 285 PreferVectorWidthOverride = Width; 286 } 287 } 288 289 // Extract required-vector-width attribute. 290 unsigned RequiredVectorWidth = UINT32_MAX; 291 if (F.hasFnAttribute("required-vector-width")) { 292 StringRef Val = F.getFnAttribute("required-vector-width").getValueAsString(); 293 unsigned Width; 294 if (!Val.getAsInteger(0, Width)) { 295 Key += ",required-vector-width="; 296 Key += Val; 297 RequiredVectorWidth = Width; 298 } 299 } 300 301 // Extracted here so that we make sure there is backing for the StringRef. If 302 // we assigned earlier, its possible the SmallString reallocated leaving a 303 // dangling StringRef. 304 FS = Key.slice(CPU.size(), CPUFSWidth); 305 306 auto &I = SubtargetMap[Key]; 307 if (!I) { 308 // This needs to be done before we create a new subtarget since any 309 // creation will depend on the TM and the code generation flags on the 310 // function that reside in TargetOptions. 311 resetTargetOptions(F); 312 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, 313 Options.StackAlignmentOverride, 314 PreferVectorWidthOverride, 315 RequiredVectorWidth); 316 } 317 return I.get(); 318 } 319 320 //===----------------------------------------------------------------------===// 321 // Command line options for x86 322 //===----------------------------------------------------------------------===// 323 static cl::opt<bool> 324 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, 325 cl::desc("Minimize AVX to SSE transition penalty"), 326 cl::init(true)); 327 328 //===----------------------------------------------------------------------===// 329 // X86 TTI query. 330 //===----------------------------------------------------------------------===// 331 332 TargetTransformInfo 333 X86TargetMachine::getTargetTransformInfo(const Function &F) { 334 return TargetTransformInfo(X86TTIImpl(this, F)); 335 } 336 337 //===----------------------------------------------------------------------===// 338 // Pass Pipeline Configuration 339 //===----------------------------------------------------------------------===// 340 341 namespace { 342 343 /// X86 Code Generator Pass Configuration Options. 344 class X86PassConfig : public TargetPassConfig { 345 public: 346 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM) 347 : TargetPassConfig(TM, PM) {} 348 349 X86TargetMachine &getX86TargetMachine() const { 350 return getTM<X86TargetMachine>(); 351 } 352 353 ScheduleDAGInstrs * 354 createMachineScheduler(MachineSchedContext *C) const override { 355 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 356 DAG->addMutation(createX86MacroFusionDAGMutation()); 357 return DAG; 358 } 359 360 void addIRPasses() override; 361 bool addInstSelector() override; 362 bool addIRTranslator() override; 363 bool addLegalizeMachineIR() override; 364 bool addRegBankSelect() override; 365 bool addGlobalInstructionSelect() override; 366 bool addILPOpts() override; 367 bool addPreISel() override; 368 void addMachineSSAOptimization() override; 369 void addPreRegAlloc() override; 370 void addPostRegAlloc() override; 371 void addPreEmitPass() override; 372 void addPreEmitPass2() override; 373 void addPreSched2() override; 374 }; 375 376 class X86ExecutionDomainFix : public ExecutionDomainFix { 377 public: 378 static char ID; 379 X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {} 380 StringRef getPassName() const override { 381 return "X86 Execution Dependency Fix"; 382 } 383 }; 384 char X86ExecutionDomainFix::ID; 385 386 } // end anonymous namespace 387 388 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix", 389 "X86 Execution Domain Fix", false, false) 390 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 391 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix", 392 "X86 Execution Domain Fix", false, false) 393 394 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { 395 return new X86PassConfig(*this, PM); 396 } 397 398 void X86PassConfig::addIRPasses() { 399 addPass(createAtomicExpandPass()); 400 401 TargetPassConfig::addIRPasses(); 402 403 if (TM->getOptLevel() != CodeGenOpt::None) 404 addPass(createInterleavedAccessPass()); 405 406 // Add passes that handle indirect branch removal and insertion of a retpoline 407 // thunk. These will be a no-op unless a function subtarget has the retpoline 408 // feature enabled. 409 addPass(createIndirectBrExpandPass()); 410 } 411 412 bool X86PassConfig::addInstSelector() { 413 // Install an instruction selector. 414 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); 415 416 // For ELF, cleanup any local-dynamic TLS accesses. 417 if (TM->getTargetTriple().isOSBinFormatELF() && 418 getOptLevel() != CodeGenOpt::None) 419 addPass(createCleanupLocalDynamicTLSPass()); 420 421 addPass(createX86GlobalBaseRegPass()); 422 return false; 423 } 424 425 bool X86PassConfig::addIRTranslator() { 426 addPass(new IRTranslator()); 427 return false; 428 } 429 430 bool X86PassConfig::addLegalizeMachineIR() { 431 addPass(new Legalizer()); 432 return false; 433 } 434 435 bool X86PassConfig::addRegBankSelect() { 436 addPass(new RegBankSelect()); 437 return false; 438 } 439 440 bool X86PassConfig::addGlobalInstructionSelect() { 441 addPass(new InstructionSelect()); 442 return false; 443 } 444 445 bool X86PassConfig::addILPOpts() { 446 addPass(&EarlyIfConverterID); 447 if (EnableMachineCombinerPass) 448 addPass(&MachineCombinerID); 449 addPass(createX86CmovConverterPass()); 450 return true; 451 } 452 453 bool X86PassConfig::addPreISel() { 454 // Only add this pass for 32-bit x86 Windows. 455 const Triple &TT = TM->getTargetTriple(); 456 if (TT.isOSWindows() && TT.getArch() == Triple::x86) 457 addPass(createX86WinEHStatePass()); 458 return true; 459 } 460 461 void X86PassConfig::addPreRegAlloc() { 462 if (getOptLevel() != CodeGenOpt::None) { 463 addPass(&LiveRangeShrinkID); 464 addPass(createX86FixupSetCC()); 465 addPass(createX86OptimizeLEAs()); 466 addPass(createX86CallFrameOptimization()); 467 addPass(createX86AvoidStoreForwardingBlocks()); 468 } 469 470 if (EnableSpeculativeLoadHardening) 471 addPass(createX86SpeculativeLoadHardeningPass()); 472 473 addPass(createX86FlagsCopyLoweringPass()); 474 addPass(createX86WinAllocaExpander()); 475 } 476 void X86PassConfig::addMachineSSAOptimization() { 477 addPass(createX86DomainReassignmentPass()); 478 TargetPassConfig::addMachineSSAOptimization(); 479 } 480 481 void X86PassConfig::addPostRegAlloc() { 482 addPass(createX86FloatingPointStackifierPass()); 483 } 484 485 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } 486 487 void X86PassConfig::addPreEmitPass() { 488 if (getOptLevel() != CodeGenOpt::None) { 489 addPass(new X86ExecutionDomainFix()); 490 addPass(createBreakFalseDeps()); 491 } 492 493 addPass(createShadowCallStackPass()); 494 addPass(createX86IndirectBranchTrackingPass()); 495 496 if (UseVZeroUpper) 497 addPass(createX86IssueVZeroUpperPass()); 498 499 if (getOptLevel() != CodeGenOpt::None) { 500 addPass(createX86FixupBWInsts()); 501 addPass(createX86PadShortFunctions()); 502 addPass(createX86FixupLEAs()); 503 addPass(createX86EvexToVexInsts()); 504 } 505 } 506 507 void X86PassConfig::addPreEmitPass2() { 508 addPass(createX86RetpolineThunksPass()); 509 // Verify basic block incoming and outgoing cfa offset and register values and 510 // correct CFA calculation rule where needed by inserting appropriate CFI 511 // instructions. 512 const Triple &TT = TM->getTargetTriple(); 513 if (!TT.isOSDarwin() && !TT.isOSWindows()) 514 addPass(createCFIInstrInserter()); 515 } 516