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