1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===// 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 // Top-level implementation for the PowerPC target. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCTargetMachine.h" 15 #include "MCTargetDesc/PPCMCTargetDesc.h" 16 #include "PPC.h" 17 #include "PPCSubtarget.h" 18 #include "PPCTargetObjectFile.h" 19 #include "PPCTargetTransformInfo.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/CodeGen/Passes.h" 26 #include "llvm/CodeGen/TargetLoweringObjectFile.h" 27 #include "llvm/CodeGen/TargetPassConfig.h" 28 #include "llvm/IR/Attributes.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CodeGen.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Target/TargetOptions.h" 36 #include "llvm/Transforms/Scalar.h" 37 #include <cassert> 38 #include <memory> 39 #include <string> 40 41 using namespace llvm; 42 43 44 static cl::opt<bool> 45 EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden, 46 cl::desc("enable coalescing of duplicate branches for PPC")); 47 static cl:: 48 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden, 49 cl::desc("Disable CTR loops for PPC")); 50 51 static cl:: 52 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden, 53 cl::desc("Disable PPC loop preinc prep")); 54 55 static cl::opt<bool> 56 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early", 57 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early")); 58 59 static cl:: 60 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden, 61 cl::desc("Disable VSX Swap Removal for PPC")); 62 63 static cl:: 64 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden, 65 cl::desc("Disable QPX load splat simplification")); 66 67 static cl:: 68 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden, 69 cl::desc("Disable machine peepholes for PPC")); 70 71 static cl::opt<bool> 72 EnableGEPOpt("ppc-gep-opt", cl::Hidden, 73 cl::desc("Enable optimizations on complex GEPs"), 74 cl::init(true)); 75 76 static cl::opt<bool> 77 EnablePrefetch("enable-ppc-prefetching", 78 cl::desc("disable software prefetching on PPC"), 79 cl::init(false), cl::Hidden); 80 81 static cl::opt<bool> 82 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps", 83 cl::desc("Add extra TOC register dependencies"), 84 cl::init(true), cl::Hidden); 85 86 static cl::opt<bool> 87 EnableMachineCombinerPass("ppc-machine-combiner", 88 cl::desc("Enable the machine combiner pass"), 89 cl::init(true), cl::Hidden); 90 91 static cl::opt<bool> 92 ReduceCRLogical("ppc-reduce-cr-logicals", 93 cl::desc("Expand eligible cr-logical binary ops to branches"), 94 cl::init(false), cl::Hidden); 95 extern "C" void LLVMInitializePowerPCTarget() { 96 // Register the targets 97 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target()); 98 RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target()); 99 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget()); 100 101 PassRegistry &PR = *PassRegistry::getPassRegistry(); 102 initializePPCBoolRetToIntPass(PR); 103 initializePPCExpandISELPass(PR); 104 initializePPCTLSDynamicCallPass(PR); 105 } 106 107 /// Return the datalayout string of a subtarget. 108 static std::string getDataLayoutString(const Triple &T) { 109 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le; 110 std::string Ret; 111 112 // Most PPC* platforms are big endian, PPC64LE is little endian. 113 if (T.getArch() == Triple::ppc64le) 114 Ret = "e"; 115 else 116 Ret = "E"; 117 118 Ret += DataLayout::getManglingComponent(T); 119 120 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit 121 // pointers. 122 if (!is64Bit || T.getOS() == Triple::Lv2) 123 Ret += "-p:32:32"; 124 125 // Note, the alignment values for f64 and i64 on ppc64 in Darwin 126 // documentation are wrong; these are correct (i.e. "what gcc does"). 127 if (is64Bit || !T.isOSDarwin()) 128 Ret += "-i64:64"; 129 else 130 Ret += "-f64:32:64"; 131 132 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones. 133 if (is64Bit) 134 Ret += "-n32:64"; 135 else 136 Ret += "-n32"; 137 138 return Ret; 139 } 140 141 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, 142 const Triple &TT) { 143 std::string FullFS = FS; 144 145 // Make sure 64-bit features are available when CPUname is generic 146 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) { 147 if (!FullFS.empty()) 148 FullFS = "+64bit," + FullFS; 149 else 150 FullFS = "+64bit"; 151 } 152 153 if (OL >= CodeGenOpt::Default) { 154 if (!FullFS.empty()) 155 FullFS = "+crbits," + FullFS; 156 else 157 FullFS = "+crbits"; 158 } 159 160 if (OL != CodeGenOpt::None) { 161 if (!FullFS.empty()) 162 FullFS = "+invariant-function-descriptors," + FullFS; 163 else 164 FullFS = "+invariant-function-descriptors"; 165 } 166 167 return FullFS; 168 } 169 170 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 171 // If it isn't a Mach-O file then it's going to be a linux ELF 172 // object file. 173 if (TT.isOSDarwin()) 174 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 175 176 return llvm::make_unique<PPC64LinuxTargetObjectFile>(); 177 } 178 179 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT, 180 const TargetOptions &Options) { 181 if (Options.MCOptions.getABIName().startswith("elfv1")) 182 return PPCTargetMachine::PPC_ABI_ELFv1; 183 else if (Options.MCOptions.getABIName().startswith("elfv2")) 184 return PPCTargetMachine::PPC_ABI_ELFv2; 185 186 assert(Options.MCOptions.getABIName().empty() && 187 "Unknown target-abi option!"); 188 189 if (TT.isMacOSX()) 190 return PPCTargetMachine::PPC_ABI_UNKNOWN; 191 192 switch (TT.getArch()) { 193 case Triple::ppc64le: 194 return PPCTargetMachine::PPC_ABI_ELFv2; 195 case Triple::ppc64: 196 return PPCTargetMachine::PPC_ABI_ELFv1; 197 default: 198 return PPCTargetMachine::PPC_ABI_UNKNOWN; 199 } 200 } 201 202 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 203 Optional<Reloc::Model> RM) { 204 if (RM.hasValue()) 205 return *RM; 206 207 // Darwin defaults to dynamic-no-pic. 208 if (TT.isOSDarwin()) 209 return Reloc::DynamicNoPIC; 210 211 // Non-darwin 64-bit platforms are PIC by default. 212 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) 213 return Reloc::PIC_; 214 215 // 32-bit is static by default. 216 return Reloc::Static; 217 } 218 219 static CodeModel::Model getEffectiveCodeModel(const Triple &TT, 220 Optional<CodeModel::Model> CM, 221 bool JIT) { 222 if (CM) 223 return *CM; 224 if (!TT.isOSDarwin() && !JIT && 225 (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le)) 226 return CodeModel::Medium; 227 return CodeModel::Small; 228 } 229 230 // The FeatureString here is a little subtle. We are modifying the feature 231 // string with what are (currently) non-function specific overrides as it goes 232 // into the LLVMTargetMachine constructor and then using the stored value in the 233 // Subtarget constructor below it. 234 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT, 235 StringRef CPU, StringRef FS, 236 const TargetOptions &Options, 237 Optional<Reloc::Model> RM, 238 Optional<CodeModel::Model> CM, 239 CodeGenOpt::Level OL, bool JIT) 240 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU, 241 computeFSAdditions(FS, OL, TT), Options, 242 getEffectiveRelocModel(TT, RM), 243 getEffectiveCodeModel(TT, CM, JIT), OL), 244 TLOF(createTLOF(getTargetTriple())), 245 TargetABI(computeTargetABI(TT, Options)) { 246 initAsmInfo(); 247 } 248 249 PPCTargetMachine::~PPCTargetMachine() = default; 250 251 const PPCSubtarget * 252 PPCTargetMachine::getSubtargetImpl(const Function &F) const { 253 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 254 Attribute FSAttr = F.getFnAttribute("target-features"); 255 256 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 257 ? CPUAttr.getValueAsString().str() 258 : TargetCPU; 259 std::string FS = !FSAttr.hasAttribute(Attribute::None) 260 ? FSAttr.getValueAsString().str() 261 : TargetFS; 262 263 // FIXME: This is related to the code below to reset the target options, 264 // we need to know whether or not the soft float flag is set on the 265 // function before we can generate a subtarget. We also need to use 266 // it as a key for the subtarget since that can be the only difference 267 // between two functions. 268 bool SoftFloat = 269 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 270 // If the soft float attribute is set on the function turn on the soft float 271 // subtarget feature. 272 if (SoftFloat) 273 FS += FS.empty() ? "-hard-float" : ",-hard-float"; 274 275 auto &I = SubtargetMap[CPU + FS]; 276 if (!I) { 277 // This needs to be done before we create a new subtarget since any 278 // creation will depend on the TM and the code generation flags on the 279 // function that reside in TargetOptions. 280 resetTargetOptions(F); 281 I = llvm::make_unique<PPCSubtarget>( 282 TargetTriple, CPU, 283 // FIXME: It would be good to have the subtarget additions here 284 // not necessary. Anything that turns them on/off (overrides) ends 285 // up being put at the end of the feature string, but the defaults 286 // shouldn't require adding them. Fixing this means pulling Feature64Bit 287 // out of most of the target cpus in the .td file and making it set only 288 // as part of initialization via the TargetTriple. 289 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this); 290 } 291 return I.get(); 292 } 293 294 //===----------------------------------------------------------------------===// 295 // Pass Pipeline Configuration 296 //===----------------------------------------------------------------------===// 297 298 namespace { 299 300 /// PPC Code Generator Pass Configuration Options. 301 class PPCPassConfig : public TargetPassConfig { 302 public: 303 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM) 304 : TargetPassConfig(TM, PM) {} 305 306 PPCTargetMachine &getPPCTargetMachine() const { 307 return getTM<PPCTargetMachine>(); 308 } 309 310 void addIRPasses() override; 311 bool addPreISel() override; 312 bool addILPOpts() override; 313 bool addInstSelector() override; 314 void addMachineSSAOptimization() override; 315 void addPreRegAlloc() override; 316 void addPreSched2() override; 317 void addPreEmitPass() override; 318 }; 319 320 } // end anonymous namespace 321 322 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { 323 return new PPCPassConfig(*this, PM); 324 } 325 326 void PPCPassConfig::addIRPasses() { 327 if (TM->getOptLevel() != CodeGenOpt::None) 328 addPass(createPPCBoolRetToIntPass()); 329 addPass(createAtomicExpandPass()); 330 331 // For the BG/Q (or if explicitly requested), add explicit data prefetch 332 // intrinsics. 333 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ && 334 getOptLevel() != CodeGenOpt::None; 335 if (EnablePrefetch.getNumOccurrences() > 0) 336 UsePrefetching = EnablePrefetch; 337 if (UsePrefetching) 338 addPass(createLoopDataPrefetchPass()); 339 340 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) { 341 // Call SeparateConstOffsetFromGEP pass to extract constants within indices 342 // and lower a GEP with multiple indices to either arithmetic operations or 343 // multiple GEPs with single index. 344 addPass(createSeparateConstOffsetFromGEPPass(TM, true)); 345 // Call EarlyCSE pass to find and remove subexpressions in the lowered 346 // result. 347 addPass(createEarlyCSEPass()); 348 // Do loop invariant code motion in case part of the lowered result is 349 // invariant. 350 addPass(createLICMPass()); 351 } 352 353 TargetPassConfig::addIRPasses(); 354 } 355 356 bool PPCPassConfig::addPreISel() { 357 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None) 358 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine())); 359 360 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 361 addPass(createPPCCTRLoops()); 362 363 return false; 364 } 365 366 bool PPCPassConfig::addILPOpts() { 367 addPass(&EarlyIfConverterID); 368 369 if (EnableMachineCombinerPass) 370 addPass(&MachineCombinerID); 371 372 return true; 373 } 374 375 bool PPCPassConfig::addInstSelector() { 376 // Install an instruction selector. 377 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel())); 378 379 #ifndef NDEBUG 380 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 381 addPass(createPPCCTRLoopsVerify()); 382 #endif 383 384 addPass(createPPCVSXCopyPass()); 385 return false; 386 } 387 388 void PPCPassConfig::addMachineSSAOptimization() { 389 // PPCBranchCoalescingPass need to be done before machine sinking 390 // since it merges empty blocks. 391 if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None) 392 addPass(createPPCBranchCoalescingPass()); 393 TargetPassConfig::addMachineSSAOptimization(); 394 // For little endian, remove where possible the vector swap instructions 395 // introduced at code generation to normalize vector element order. 396 if (TM->getTargetTriple().getArch() == Triple::ppc64le && 397 !DisableVSXSwapRemoval) 398 addPass(createPPCVSXSwapRemovalPass()); 399 // Reduce the number of cr-logical ops. 400 if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None) 401 addPass(createPPCReduceCRLogicalsPass()); 402 // Target-specific peephole cleanups performed after instruction 403 // selection. 404 if (!DisableMIPeephole) { 405 addPass(createPPCMIPeepholePass()); 406 addPass(&DeadMachineInstructionElimID); 407 } 408 } 409 410 void PPCPassConfig::addPreRegAlloc() { 411 if (getOptLevel() != CodeGenOpt::None) { 412 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry()); 413 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID, 414 &PPCVSXFMAMutateID); 415 } 416 417 // FIXME: We probably don't need to run these for -fPIE. 418 if (getPPCTargetMachine().isPositionIndependent()) { 419 // FIXME: LiveVariables should not be necessary here! 420 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on 421 // LiveVariables. This (unnecessary) dependency has been removed now, 422 // however a stage-2 clang build fails without LiveVariables computed here. 423 addPass(&LiveVariablesID, false); 424 addPass(createPPCTLSDynamicCallPass()); 425 } 426 if (EnableExtraTOCRegDeps) 427 addPass(createPPCTOCRegDepsPass()); 428 } 429 430 void PPCPassConfig::addPreSched2() { 431 if (getOptLevel() != CodeGenOpt::None) { 432 addPass(&IfConverterID); 433 434 // This optimization must happen after anything that might do store-to-load 435 // forwarding. Here we're after RA (and, thus, when spills are inserted) 436 // but before post-RA scheduling. 437 if (!DisableQPXLoadSplat) 438 addPass(createPPCQPXLoadSplatPass()); 439 } 440 } 441 442 void PPCPassConfig::addPreEmitPass() { 443 addPass(createPPCExpandISELPass()); 444 445 if (getOptLevel() != CodeGenOpt::None) 446 addPass(createPPCEarlyReturnPass(), false); 447 // Must run branch selection immediately preceding the asm printer. 448 addPass(createPPCBranchSelectionPass(), false); 449 } 450 451 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() { 452 return TargetIRAnalysis([this](const Function &F) { 453 return TargetTransformInfo(PPCTTIImpl(this, F)); 454 }); 455 } 456