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/ExecutionDepsFix.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/TargetLoweringObjectFile.h" 38 #include "llvm/CodeGen/TargetPassConfig.h" 39 #include "llvm/IR/Attributes.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/Function.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/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 namespace llvm { 58 59 void initializeWinEHStatePassPass(PassRegistry &); 60 void initializeFixupLEAPassPass(PassRegistry &); 61 void initializeX86CallFrameOptimizationPass(PassRegistry &); 62 void initializeX86CmovConverterPassPass(PassRegistry &); 63 void initializeX86ExecutionDepsFixPass(PassRegistry &); 64 void initializeX86DomainReassignmentPass(PassRegistry &); 65 66 } // end namespace llvm 67 68 extern "C" void LLVMInitializeX86Target() { 69 // Register the target. 70 RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target()); 71 RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target()); 72 73 PassRegistry &PR = *PassRegistry::getPassRegistry(); 74 initializeGlobalISel(PR); 75 initializeWinEHStatePassPass(PR); 76 initializeFixupBWInstPassPass(PR); 77 initializeEvexToVexInstPassPass(PR); 78 initializeFixupLEAPassPass(PR); 79 initializeX86CallFrameOptimizationPass(PR); 80 initializeX86CmovConverterPassPass(PR); 81 initializeX86ExecutionDepsFixPass(PR); 82 initializeX86DomainReassignmentPass(PR); 83 } 84 85 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 86 if (TT.isOSBinFormatMachO()) { 87 if (TT.getArch() == Triple::x86_64) 88 return llvm::make_unique<X86_64MachoTargetObjectFile>(); 89 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 90 } 91 92 if (TT.isOSFreeBSD()) 93 return llvm::make_unique<X86FreeBSDTargetObjectFile>(); 94 if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU()) 95 return llvm::make_unique<X86LinuxNaClTargetObjectFile>(); 96 if (TT.isOSSolaris()) 97 return llvm::make_unique<X86SolarisTargetObjectFile>(); 98 if (TT.isOSFuchsia()) 99 return llvm::make_unique<X86FuchsiaTargetObjectFile>(); 100 if (TT.isOSBinFormatELF()) 101 return llvm::make_unique<X86ELFTargetObjectFile>(); 102 if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment()) 103 return llvm::make_unique<X86WindowsTargetObjectFile>(); 104 if (TT.isOSBinFormatCOFF()) 105 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 106 llvm_unreachable("unknown subtarget type"); 107 } 108 109 static std::string computeDataLayout(const Triple &TT) { 110 // X86 is little endian 111 std::string Ret = "e"; 112 113 Ret += DataLayout::getManglingComponent(TT); 114 // X86 and x32 have 32 bit pointers. 115 if ((TT.isArch64Bit() && 116 (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) || 117 !TT.isArch64Bit()) 118 Ret += "-p:32:32"; 119 120 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32. 121 if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl()) 122 Ret += "-i64:64"; 123 else if (TT.isOSIAMCU()) 124 Ret += "-i64:32-f64:32"; 125 else 126 Ret += "-f64:32:64"; 127 128 // Some ABIs align long double to 128 bits, others to 32. 129 if (TT.isOSNaCl() || TT.isOSIAMCU()) 130 ; // No f80 131 else if (TT.isArch64Bit() || TT.isOSDarwin()) 132 Ret += "-f80:128"; 133 else 134 Ret += "-f80:32"; 135 136 if (TT.isOSIAMCU()) 137 Ret += "-f128:32"; 138 139 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits. 140 if (TT.isArch64Bit()) 141 Ret += "-n8:16:32:64"; 142 else 143 Ret += "-n8:16:32"; 144 145 // The stack is aligned to 32 bits on some ABIs and 128 bits on others. 146 if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU()) 147 Ret += "-a:0:32-S32"; 148 else 149 Ret += "-S128"; 150 151 return Ret; 152 } 153 154 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 155 Optional<Reloc::Model> RM) { 156 bool is64Bit = TT.getArch() == Triple::x86_64; 157 if (!RM.hasValue()) { 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 getEffectiveCodeModel(Optional<CodeModel::Model> CM, 191 bool JIT, bool Is64Bit) { 192 if (CM) 193 return *CM; 194 if (JIT) 195 return Is64Bit ? CodeModel::Large : CodeModel::Small; 196 return CodeModel::Small; 197 } 198 199 /// Create an X86 target. 200 /// 201 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT, 202 StringRef CPU, StringRef FS, 203 const TargetOptions &Options, 204 Optional<Reloc::Model> RM, 205 Optional<CodeModel::Model> CM, 206 CodeGenOpt::Level OL, bool JIT) 207 : LLVMTargetMachine( 208 T, computeDataLayout(TT), TT, CPU, FS, Options, 209 getEffectiveRelocModel(TT, RM), 210 getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL), 211 TLOF(createTLOF(getTargetTriple())) { 212 // Windows stack unwinder gets confused when execution flow "falls through" 213 // after a call to 'noreturn' function. 214 // To prevent that, we emit a trap for 'unreachable' IR instructions. 215 // (which on X86, happens to be the 'ud2' instruction) 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 // The check here for 64-bit windows is a bit icky, but as we're unlikely 219 // to ever want to mix 32 and 64-bit windows code in a single module 220 // this should be fine. 221 if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4()) 222 this->Options.TrapUnreachable = true; 223 224 initAsmInfo(); 225 } 226 227 X86TargetMachine::~X86TargetMachine() = default; 228 229 const X86Subtarget * 230 X86TargetMachine::getSubtargetImpl(const Function &F) const { 231 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 232 Attribute FSAttr = F.getFnAttribute("target-features"); 233 234 StringRef CPU = !CPUAttr.hasAttribute(Attribute::None) 235 ? CPUAttr.getValueAsString() 236 : (StringRef)TargetCPU; 237 StringRef FS = !FSAttr.hasAttribute(Attribute::None) 238 ? FSAttr.getValueAsString() 239 : (StringRef)TargetFS; 240 241 SmallString<512> Key; 242 Key.reserve(CPU.size() + FS.size()); 243 Key += CPU; 244 Key += FS; 245 246 // FIXME: This is related to the code below to reset the target options, 247 // we need to know whether or not the soft float flag is set on the 248 // function before we can generate a subtarget. We also need to use 249 // it as a key for the subtarget since that can be the only difference 250 // between two functions. 251 bool SoftFloat = 252 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 253 // If the soft float attribute is set on the function turn on the soft float 254 // subtarget feature. 255 if (SoftFloat) 256 Key += FS.empty() ? "+soft-float" : ",+soft-float"; 257 258 FS = Key.substr(CPU.size()); 259 260 auto &I = SubtargetMap[Key]; 261 if (!I) { 262 // This needs to be done before we create a new subtarget since any 263 // creation will depend on the TM and the code generation flags on the 264 // function that reside in TargetOptions. 265 resetTargetOptions(F); 266 I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this, 267 Options.StackAlignmentOverride); 268 } 269 return I.get(); 270 } 271 272 //===----------------------------------------------------------------------===// 273 // Command line options for x86 274 //===----------------------------------------------------------------------===// 275 static cl::opt<bool> 276 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, 277 cl::desc("Minimize AVX to SSE transition penalty"), 278 cl::init(true)); 279 280 //===----------------------------------------------------------------------===// 281 // X86 TTI query. 282 //===----------------------------------------------------------------------===// 283 284 TargetTransformInfo 285 X86TargetMachine::getTargetTransformInfo(const Function &F) { 286 return TargetTransformInfo(X86TTIImpl(this, F)); 287 } 288 289 //===----------------------------------------------------------------------===// 290 // Pass Pipeline Configuration 291 //===----------------------------------------------------------------------===// 292 293 namespace { 294 295 /// X86 Code Generator Pass Configuration Options. 296 class X86PassConfig : public TargetPassConfig { 297 public: 298 X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM) 299 : TargetPassConfig(TM, PM) {} 300 301 X86TargetMachine &getX86TargetMachine() const { 302 return getTM<X86TargetMachine>(); 303 } 304 305 ScheduleDAGInstrs * 306 createMachineScheduler(MachineSchedContext *C) const override { 307 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 308 DAG->addMutation(createX86MacroFusionDAGMutation()); 309 return DAG; 310 } 311 312 void addIRPasses() override; 313 bool addInstSelector() override; 314 bool addIRTranslator() override; 315 bool addLegalizeMachineIR() override; 316 bool addRegBankSelect() override; 317 bool addGlobalInstructionSelect() override; 318 bool addILPOpts() override; 319 bool addPreISel() override; 320 void addMachineSSAOptimization() override; 321 void addPreRegAlloc() override; 322 void addPostRegAlloc() override; 323 void addPreEmitPass() override; 324 void addPreSched2() override; 325 }; 326 327 class X86ExecutionDepsFix : public ExecutionDepsFix { 328 public: 329 static char ID; 330 X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {} 331 StringRef getPassName() const override { 332 return "X86 Execution Dependency Fix"; 333 } 334 }; 335 char X86ExecutionDepsFix::ID; 336 337 } // end anonymous namespace 338 339 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix", 340 "X86 Execution Dependency Fix", false, false) 341 342 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) { 343 return new X86PassConfig(*this, PM); 344 } 345 346 void X86PassConfig::addIRPasses() { 347 addPass(createAtomicExpandPass()); 348 349 TargetPassConfig::addIRPasses(); 350 351 if (TM->getOptLevel() != CodeGenOpt::None) 352 addPass(createInterleavedAccessPass()); 353 } 354 355 bool X86PassConfig::addInstSelector() { 356 // Install an instruction selector. 357 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel())); 358 359 // For ELF, cleanup any local-dynamic TLS accesses. 360 if (TM->getTargetTriple().isOSBinFormatELF() && 361 getOptLevel() != CodeGenOpt::None) 362 addPass(createCleanupLocalDynamicTLSPass()); 363 364 addPass(createX86GlobalBaseRegPass()); 365 return false; 366 } 367 368 bool X86PassConfig::addIRTranslator() { 369 addPass(new IRTranslator()); 370 return false; 371 } 372 373 bool X86PassConfig::addLegalizeMachineIR() { 374 addPass(new Legalizer()); 375 return false; 376 } 377 378 bool X86PassConfig::addRegBankSelect() { 379 addPass(new RegBankSelect()); 380 return false; 381 } 382 383 bool X86PassConfig::addGlobalInstructionSelect() { 384 addPass(new InstructionSelect()); 385 return false; 386 } 387 388 bool X86PassConfig::addILPOpts() { 389 addPass(&EarlyIfConverterID); 390 if (EnableMachineCombinerPass) 391 addPass(&MachineCombinerID); 392 addPass(createX86CmovConverterPass()); 393 return true; 394 } 395 396 bool X86PassConfig::addPreISel() { 397 // Only add this pass for 32-bit x86 Windows. 398 const Triple &TT = TM->getTargetTriple(); 399 if (TT.isOSWindows() && TT.getArch() == Triple::x86) 400 addPass(createX86WinEHStatePass()); 401 return true; 402 } 403 404 void X86PassConfig::addPreRegAlloc() { 405 if (getOptLevel() != CodeGenOpt::None) { 406 addPass(&LiveRangeShrinkID); 407 addPass(createX86FixupSetCC()); 408 addPass(createX86OptimizeLEAs()); 409 addPass(createX86CallFrameOptimization()); 410 } 411 412 addPass(createX86WinAllocaExpander()); 413 } 414 void X86PassConfig::addMachineSSAOptimization() { 415 addPass(createX86DomainReassignmentPass()); 416 TargetPassConfig::addMachineSSAOptimization(); 417 } 418 419 void X86PassConfig::addPostRegAlloc() { 420 addPass(createX86FloatingPointStackifierPass()); 421 } 422 423 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); } 424 425 void X86PassConfig::addPreEmitPass() { 426 if (getOptLevel() != CodeGenOpt::None) 427 addPass(new X86ExecutionDepsFix()); 428 429 addPass(createX86IndirectBranchTrackingPass()); 430 431 if (UseVZeroUpper) 432 addPass(createX86IssueVZeroUpperPass()); 433 434 if (getOptLevel() != CodeGenOpt::None) { 435 addPass(createX86FixupBWInsts()); 436 addPass(createX86PadShortFunctions()); 437 addPass(createX86FixupLEAs()); 438 addPass(createX86EvexToVexInsts()); 439 } 440 } 441