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