1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Top-level implementation for the PowerPC target.
12 //===----------------------------------------------------------------------===//
14 #include "PPCTargetMachine.h"
15 #include "MCTargetDesc/PPCMCTargetDesc.h"
17 #include "PPCSubtarget.h"
18 #include "PPCTargetObjectFile.h"
19 #include "PPCTargetTransformInfo.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/CodeGen/MachineScheduler.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CodeGen.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Transforms/Scalar.h"
46 EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden,
47 cl::desc("enable coalescing of duplicate branches for PPC"));
49 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
50 cl::desc("Disable CTR loops for PPC"));
53 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
54 cl::desc("Disable PPC loop preinc prep"));
57 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
58 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
61 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
62 cl::desc("Disable VSX Swap Removal for PPC"));
65 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
66 cl::desc("Disable QPX load splat simplification"));
69 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
70 cl::desc("Disable machine peepholes for PPC"));
73 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
74 cl::desc("Enable optimizations on complex GEPs"),
78 EnablePrefetch("enable-ppc-prefetching",
79 cl::desc("disable software prefetching on PPC"),
80 cl::init(false), cl::Hidden);
83 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
84 cl::desc("Add extra TOC register dependencies"),
85 cl::init(true), cl::Hidden);
88 EnableMachineCombinerPass("ppc-machine-combiner",
89 cl::desc("Enable the machine combiner pass"),
90 cl::init(true), cl::Hidden);
93 ReduceCRLogical("ppc-reduce-cr-logicals",
94 cl::desc("Expand eligible cr-logical binary ops to branches"),
95 cl::init(false), cl::Hidden);
96 extern "C" void LLVMInitializePowerPCTarget() {
97 // Register the targets
98 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target());
99 RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target());
100 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget());
102 PassRegistry &PR = *PassRegistry::getPassRegistry();
103 initializePPCBoolRetToIntPass(PR);
104 initializePPCExpandISELPass(PR);
105 initializePPCPreEmitPeepholePass(PR);
106 initializePPCTLSDynamicCallPass(PR);
107 initializePPCMIPeepholePass(PR);
110 /// Return the datalayout string of a subtarget.
111 static std::string getDataLayoutString(const Triple &T) {
112 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
115 // Most PPC* platforms are big endian, PPC64LE is little endian.
116 if (T.getArch() == Triple::ppc64le)
121 Ret += DataLayout::getManglingComponent(T);
123 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
125 if (!is64Bit || T.getOS() == Triple::Lv2)
128 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
129 // documentation are wrong; these are correct (i.e. "what gcc does").
130 if (is64Bit || !T.isOSDarwin())
135 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
144 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
146 std::string FullFS = FS;
148 // Make sure 64-bit features are available when CPUname is generic
149 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
151 FullFS = "+64bit," + FullFS;
156 if (OL >= CodeGenOpt::Default) {
158 FullFS = "+crbits," + FullFS;
163 if (OL != CodeGenOpt::None) {
165 FullFS = "+invariant-function-descriptors," + FullFS;
167 FullFS = "+invariant-function-descriptors";
173 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
174 // If it isn't a Mach-O file then it's going to be a linux ELF
177 return llvm::make_unique<TargetLoweringObjectFileMachO>();
179 return llvm::make_unique<PPC64LinuxTargetObjectFile>();
182 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
183 const TargetOptions &Options) {
184 if (Options.MCOptions.getABIName().startswith("elfv1"))
185 return PPCTargetMachine::PPC_ABI_ELFv1;
186 else if (Options.MCOptions.getABIName().startswith("elfv2"))
187 return PPCTargetMachine::PPC_ABI_ELFv2;
189 assert(Options.MCOptions.getABIName().empty() &&
190 "Unknown target-abi option!");
193 return PPCTargetMachine::PPC_ABI_UNKNOWN;
195 switch (TT.getArch()) {
196 case Triple::ppc64le:
197 return PPCTargetMachine::PPC_ABI_ELFv2;
199 return PPCTargetMachine::PPC_ABI_ELFv1;
201 return PPCTargetMachine::PPC_ABI_UNKNOWN;
205 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
206 Optional<Reloc::Model> RM) {
210 // Darwin defaults to dynamic-no-pic.
212 return Reloc::DynamicNoPIC;
214 // Non-darwin 64-bit platforms are PIC by default.
215 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le)
218 // 32-bit is static by default.
219 return Reloc::Static;
222 static CodeModel::Model getEffectiveCodeModel(const Triple &TT,
223 Optional<CodeModel::Model> CM,
227 if (!TT.isOSDarwin() && !JIT &&
228 (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le))
229 return CodeModel::Medium;
230 return CodeModel::Small;
233 // The FeatureString here is a little subtle. We are modifying the feature
234 // string with what are (currently) non-function specific overrides as it goes
235 // into the LLVMTargetMachine constructor and then using the stored value in the
236 // Subtarget constructor below it.
237 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
238 StringRef CPU, StringRef FS,
239 const TargetOptions &Options,
240 Optional<Reloc::Model> RM,
241 Optional<CodeModel::Model> CM,
242 CodeGenOpt::Level OL, bool JIT)
243 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
244 computeFSAdditions(FS, OL, TT), Options,
245 getEffectiveRelocModel(TT, RM),
246 getEffectiveCodeModel(TT, CM, JIT), OL),
247 TLOF(createTLOF(getTargetTriple())),
248 TargetABI(computeTargetABI(TT, Options)) {
252 PPCTargetMachine::~PPCTargetMachine() = default;
255 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
256 Attribute CPUAttr = F.getFnAttribute("target-cpu");
257 Attribute FSAttr = F.getFnAttribute("target-features");
259 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
260 ? CPUAttr.getValueAsString().str()
262 std::string FS = !FSAttr.hasAttribute(Attribute::None)
263 ? FSAttr.getValueAsString().str()
266 // FIXME: This is related to the code below to reset the target options,
267 // we need to know whether or not the soft float flag is set on the
268 // function before we can generate a subtarget. We also need to use
269 // it as a key for the subtarget since that can be the only difference
270 // between two functions.
272 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
273 // If the soft float attribute is set on the function turn on the soft float
274 // subtarget feature.
276 FS += FS.empty() ? "-hard-float" : ",-hard-float";
278 auto &I = SubtargetMap[CPU + FS];
280 // This needs to be done before we create a new subtarget since any
281 // creation will depend on the TM and the code generation flags on the
282 // function that reside in TargetOptions.
283 resetTargetOptions(F);
284 I = llvm::make_unique<PPCSubtarget>(
286 // FIXME: It would be good to have the subtarget additions here
287 // not necessary. Anything that turns them on/off (overrides) ends
288 // up being put at the end of the feature string, but the defaults
289 // shouldn't require adding them. Fixing this means pulling Feature64Bit
290 // out of most of the target cpus in the .td file and making it set only
291 // as part of initialization via the TargetTriple.
292 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
297 //===----------------------------------------------------------------------===//
298 // Pass Pipeline Configuration
299 //===----------------------------------------------------------------------===//
303 /// PPC Code Generator Pass Configuration Options.
304 class PPCPassConfig : public TargetPassConfig {
306 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM)
307 : TargetPassConfig(TM, PM) {
308 // At any optimization level above -O0 we use the Machine Scheduler and not
309 // the default Post RA List Scheduler.
310 if (TM.getOptLevel() != CodeGenOpt::None)
311 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
314 PPCTargetMachine &getPPCTargetMachine() const {
315 return getTM<PPCTargetMachine>();
318 void addIRPasses() override;
319 bool addPreISel() override;
320 bool addILPOpts() override;
321 bool addInstSelector() override;
322 void addMachineSSAOptimization() override;
323 void addPreRegAlloc() override;
324 void addPreSched2() override;
325 void addPreEmitPass() override;
328 } // end anonymous namespace
330 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
331 return new PPCPassConfig(*this, PM);
334 void PPCPassConfig::addIRPasses() {
335 if (TM->getOptLevel() != CodeGenOpt::None)
336 addPass(createPPCBoolRetToIntPass());
337 addPass(createAtomicExpandPass());
339 // For the BG/Q (or if explicitly requested), add explicit data prefetch
341 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
342 getOptLevel() != CodeGenOpt::None;
343 if (EnablePrefetch.getNumOccurrences() > 0)
344 UsePrefetching = EnablePrefetch;
346 addPass(createLoopDataPrefetchPass());
348 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
349 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
350 // and lower a GEP with multiple indices to either arithmetic operations or
351 // multiple GEPs with single index.
352 addPass(createSeparateConstOffsetFromGEPPass(true));
353 // Call EarlyCSE pass to find and remove subexpressions in the lowered
355 addPass(createEarlyCSEPass());
356 // Do loop invariant code motion in case part of the lowered result is
358 addPass(createLICMPass());
361 TargetPassConfig::addIRPasses();
364 bool PPCPassConfig::addPreISel() {
365 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
366 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
368 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
369 addPass(createPPCCTRLoops());
374 bool PPCPassConfig::addILPOpts() {
375 addPass(&EarlyIfConverterID);
377 if (EnableMachineCombinerPass)
378 addPass(&MachineCombinerID);
383 bool PPCPassConfig::addInstSelector() {
384 // Install an instruction selector.
385 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
388 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
389 addPass(createPPCCTRLoopsVerify());
392 addPass(createPPCVSXCopyPass());
396 void PPCPassConfig::addMachineSSAOptimization() {
397 // PPCBranchCoalescingPass need to be done before machine sinking
398 // since it merges empty blocks.
399 if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None)
400 addPass(createPPCBranchCoalescingPass());
401 TargetPassConfig::addMachineSSAOptimization();
402 // For little endian, remove where possible the vector swap instructions
403 // introduced at code generation to normalize vector element order.
404 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
405 !DisableVSXSwapRemoval)
406 addPass(createPPCVSXSwapRemovalPass());
407 // Reduce the number of cr-logical ops.
408 if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None)
409 addPass(createPPCReduceCRLogicalsPass());
410 // Target-specific peephole cleanups performed after instruction
412 if (!DisableMIPeephole) {
413 addPass(createPPCMIPeepholePass());
414 addPass(&DeadMachineInstructionElimID);
418 void PPCPassConfig::addPreRegAlloc() {
419 if (getOptLevel() != CodeGenOpt::None) {
420 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
421 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
425 // FIXME: We probably don't need to run these for -fPIE.
426 if (getPPCTargetMachine().isPositionIndependent()) {
427 // FIXME: LiveVariables should not be necessary here!
428 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
429 // LiveVariables. This (unnecessary) dependency has been removed now,
430 // however a stage-2 clang build fails without LiveVariables computed here.
431 addPass(&LiveVariablesID, false);
432 addPass(createPPCTLSDynamicCallPass());
434 if (EnableExtraTOCRegDeps)
435 addPass(createPPCTOCRegDepsPass());
438 void PPCPassConfig::addPreSched2() {
439 if (getOptLevel() != CodeGenOpt::None) {
440 addPass(&IfConverterID);
442 // This optimization must happen after anything that might do store-to-load
443 // forwarding. Here we're after RA (and, thus, when spills are inserted)
444 // but before post-RA scheduling.
445 if (!DisableQPXLoadSplat)
446 addPass(createPPCQPXLoadSplatPass());
450 void PPCPassConfig::addPreEmitPass() {
451 addPass(createPPCPreEmitPeepholePass());
452 addPass(createPPCExpandISELPass());
454 if (getOptLevel() != CodeGenOpt::None)
455 addPass(createPPCEarlyReturnPass(), false);
456 // Must run branch selection immediately preceding the asm printer.
457 addPass(createPPCBranchSelectionPass(), false);
461 PPCTargetMachine::getTargetTransformInfo(const Function &F) {
462 return TargetTransformInfo(PPCTTIImpl(this, F));