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