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 ((T.getArch() == Triple::ppc64le || T.getArch() == Triple::ppc64) && 161 (T.isOSAIX() || T.isOSLinux())) 162 Ret += "-v256:256:256-v512:512:512"; 163 164 return Ret; 165 } 166 167 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, 168 const Triple &TT) { 169 std::string FullFS = std::string(FS); 170 171 // Make sure 64-bit features are available when CPUname is generic 172 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) { 173 if (!FullFS.empty()) 174 FullFS = "+64bit," + FullFS; 175 else 176 FullFS = "+64bit"; 177 } 178 179 if (OL >= CodeGenOpt::Default) { 180 if (!FullFS.empty()) 181 FullFS = "+crbits," + FullFS; 182 else 183 FullFS = "+crbits"; 184 } 185 186 if (OL != CodeGenOpt::None) { 187 if (!FullFS.empty()) 188 FullFS = "+invariant-function-descriptors," + FullFS; 189 else 190 FullFS = "+invariant-function-descriptors"; 191 } 192 193 return FullFS; 194 } 195 196 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 197 if (TT.isOSAIX()) 198 return std::make_unique<TargetLoweringObjectFileXCOFF>(); 199 200 return std::make_unique<PPC64LinuxTargetObjectFile>(); 201 } 202 203 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT, 204 const TargetOptions &Options) { 205 if (Options.MCOptions.getABIName().startswith("elfv1")) 206 return PPCTargetMachine::PPC_ABI_ELFv1; 207 else if (Options.MCOptions.getABIName().startswith("elfv2")) 208 return PPCTargetMachine::PPC_ABI_ELFv2; 209 210 assert(Options.MCOptions.getABIName().empty() && 211 "Unknown target-abi option!"); 212 213 if (TT.isMacOSX()) 214 return PPCTargetMachine::PPC_ABI_UNKNOWN; 215 216 switch (TT.getArch()) { 217 case Triple::ppc64le: 218 return PPCTargetMachine::PPC_ABI_ELFv2; 219 case Triple::ppc64: 220 return PPCTargetMachine::PPC_ABI_ELFv1; 221 default: 222 return PPCTargetMachine::PPC_ABI_UNKNOWN; 223 } 224 } 225 226 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 227 Optional<Reloc::Model> RM) { 228 assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) && 229 "Invalid relocation model for AIX."); 230 231 if (RM.hasValue()) 232 return *RM; 233 234 // Big Endian PPC and AIX default to PIC. 235 if (TT.getArch() == Triple::ppc64 || TT.isOSAIX()) 236 return Reloc::PIC_; 237 238 // Rest are static by default. 239 return Reloc::Static; 240 } 241 242 static CodeModel::Model getEffectivePPCCodeModel(const Triple &TT, 243 Optional<CodeModel::Model> CM, 244 bool JIT) { 245 if (CM) { 246 if (*CM == CodeModel::Tiny) 247 report_fatal_error("Target does not support the tiny CodeModel", false); 248 if (*CM == CodeModel::Kernel) 249 report_fatal_error("Target does not support the kernel CodeModel", false); 250 return *CM; 251 } 252 253 if (JIT) 254 return CodeModel::Small; 255 if (TT.isOSAIX()) 256 return CodeModel::Small; 257 258 assert(TT.isOSBinFormatELF() && "All remaining PPC OSes are ELF based."); 259 260 if (TT.isArch32Bit()) 261 return CodeModel::Small; 262 263 assert(TT.isArch64Bit() && "Unsupported PPC architecture."); 264 return CodeModel::Medium; 265 } 266 267 268 static ScheduleDAGInstrs *createPPCMachineScheduler(MachineSchedContext *C) { 269 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>(); 270 ScheduleDAGMILive *DAG = 271 new ScheduleDAGMILive(C, ST.usePPCPreRASchedStrategy() ? 272 std::make_unique<PPCPreRASchedStrategy>(C) : 273 std::make_unique<GenericScheduler>(C)); 274 // add DAG Mutations here. 275 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI)); 276 if (ST.hasStoreFusion()) 277 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 278 if (ST.hasFusion()) 279 DAG->addMutation(createPowerPCMacroFusionDAGMutation()); 280 281 return DAG; 282 } 283 284 static ScheduleDAGInstrs *createPPCPostMachineScheduler( 285 MachineSchedContext *C) { 286 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>(); 287 ScheduleDAGMI *DAG = 288 new ScheduleDAGMI(C, ST.usePPCPostRASchedStrategy() ? 289 std::make_unique<PPCPostRASchedStrategy>(C) : 290 std::make_unique<PostGenericScheduler>(C), true); 291 // add DAG Mutations here. 292 if (ST.hasStoreFusion()) 293 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 294 if (ST.hasFusion()) 295 DAG->addMutation(createPowerPCMacroFusionDAGMutation()); 296 return DAG; 297 } 298 299 // The FeatureString here is a little subtle. We are modifying the feature 300 // string with what are (currently) non-function specific overrides as it goes 301 // into the LLVMTargetMachine constructor and then using the stored value in the 302 // Subtarget constructor below it. 303 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT, 304 StringRef CPU, StringRef FS, 305 const TargetOptions &Options, 306 Optional<Reloc::Model> RM, 307 Optional<CodeModel::Model> CM, 308 CodeGenOpt::Level OL, bool JIT) 309 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU, 310 computeFSAdditions(FS, OL, TT), Options, 311 getEffectiveRelocModel(TT, RM), 312 getEffectivePPCCodeModel(TT, CM, JIT), OL), 313 TLOF(createTLOF(getTargetTriple())), 314 TargetABI(computeTargetABI(TT, Options)) { 315 initAsmInfo(); 316 } 317 318 PPCTargetMachine::~PPCTargetMachine() = default; 319 320 const PPCSubtarget * 321 PPCTargetMachine::getSubtargetImpl(const Function &F) const { 322 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 323 Attribute FSAttr = F.getFnAttribute("target-features"); 324 325 std::string CPU = 326 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU; 327 std::string FS = 328 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS; 329 330 // FIXME: This is related to the code below to reset the target options, 331 // we need to know whether or not the soft float flag is set on the 332 // function before we can generate a subtarget. We also need to use 333 // it as a key for the subtarget since that can be the only difference 334 // between two functions. 335 bool SoftFloat = 336 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 337 // If the soft float attribute is set on the function turn on the soft float 338 // subtarget feature. 339 if (SoftFloat) 340 FS += FS.empty() ? "-hard-float" : ",-hard-float"; 341 342 auto &I = SubtargetMap[CPU + FS]; 343 if (!I) { 344 // This needs to be done before we create a new subtarget since any 345 // creation will depend on the TM and the code generation flags on the 346 // function that reside in TargetOptions. 347 resetTargetOptions(F); 348 I = std::make_unique<PPCSubtarget>( 349 TargetTriple, CPU, 350 // FIXME: It would be good to have the subtarget additions here 351 // not necessary. Anything that turns them on/off (overrides) ends 352 // up being put at the end of the feature string, but the defaults 353 // shouldn't require adding them. Fixing this means pulling Feature64Bit 354 // out of most of the target cpus in the .td file and making it set only 355 // as part of initialization via the TargetTriple. 356 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this); 357 } 358 return I.get(); 359 } 360 361 //===----------------------------------------------------------------------===// 362 // Pass Pipeline Configuration 363 //===----------------------------------------------------------------------===// 364 365 namespace { 366 367 /// PPC Code Generator Pass Configuration Options. 368 class PPCPassConfig : public TargetPassConfig { 369 public: 370 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM) 371 : TargetPassConfig(TM, PM) { 372 // At any optimization level above -O0 we use the Machine Scheduler and not 373 // the default Post RA List Scheduler. 374 if (TM.getOptLevel() != CodeGenOpt::None) 375 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 376 } 377 378 PPCTargetMachine &getPPCTargetMachine() const { 379 return getTM<PPCTargetMachine>(); 380 } 381 382 void addIRPasses() override; 383 bool addPreISel() override; 384 bool addILPOpts() override; 385 bool addInstSelector() override; 386 void addMachineSSAOptimization() override; 387 void addPreRegAlloc() override; 388 void addPreSched2() override; 389 void addPreEmitPass() override; 390 // GlobalISEL 391 bool addIRTranslator() override; 392 bool addLegalizeMachineIR() override; 393 bool addRegBankSelect() override; 394 bool addGlobalInstructionSelect() override; 395 396 ScheduleDAGInstrs * 397 createMachineScheduler(MachineSchedContext *C) const override { 398 return createPPCMachineScheduler(C); 399 } 400 ScheduleDAGInstrs * 401 createPostMachineScheduler(MachineSchedContext *C) const override { 402 return createPPCPostMachineScheduler(C); 403 } 404 }; 405 406 } // end anonymous namespace 407 408 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { 409 return new PPCPassConfig(*this, PM); 410 } 411 412 void PPCPassConfig::addIRPasses() { 413 if (TM->getOptLevel() != CodeGenOpt::None) 414 addPass(createPPCBoolRetToIntPass()); 415 addPass(createAtomicExpandPass()); 416 417 // Lower generic MASSV routines to PowerPC subtarget-specific entries. 418 addPass(createPPCLowerMASSVEntriesPass()); 419 420 // If explicitly requested, add explicit data prefetch intrinsics. 421 if (EnablePrefetch.getNumOccurrences() > 0) 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 522 void PPCPassConfig::addPreEmitPass() { 523 addPass(createPPCPreEmitPeepholePass()); 524 addPass(createPPCExpandISELPass()); 525 526 if (getOptLevel() != CodeGenOpt::None) 527 addPass(createPPCEarlyReturnPass()); 528 // Must run branch selection immediately preceding the asm printer. 529 addPass(createPPCBranchSelectionPass()); 530 } 531 532 TargetTransformInfo 533 PPCTargetMachine::getTargetTransformInfo(const Function &F) { 534 return TargetTransformInfo(PPCTTIImpl(this, F)); 535 } 536 537 static MachineSchedRegistry 538 PPCPreRASchedRegistry("ppc-prera", 539 "Run PowerPC PreRA specific scheduler", 540 createPPCMachineScheduler); 541 542 static MachineSchedRegistry 543 PPCPostRASchedRegistry("ppc-postra", 544 "Run PowerPC PostRA specific scheduler", 545 createPPCPostMachineScheduler); 546 547 // Global ISEL 548 bool PPCPassConfig::addIRTranslator() { 549 addPass(new IRTranslator()); 550 return false; 551 } 552 553 bool PPCPassConfig::addLegalizeMachineIR() { 554 addPass(new Legalizer()); 555 return false; 556 } 557 558 bool PPCPassConfig::addRegBankSelect() { 559 addPass(new RegBankSelect()); 560 return false; 561 } 562 563 bool PPCPassConfig::addGlobalInstructionSelect() { 564 addPass(new InstructionSelect()); 565 return false; 566 } 567