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