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