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"
16 #include "PPCTargetObjectFile.h"
17 #include "PPCTargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Transforms/Scalar.h"
30 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
31 cl::desc("Disable CTR loops for PPC"));
34 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
35 cl::desc("Disable PPC loop preinc prep"));
38 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
39 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
42 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
43 cl::desc("Disable VSX Swap Removal for PPC"));
46 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
47 cl::desc("Disable machine peepholes for PPC"));
50 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
51 cl::desc("Enable optimizations on complex GEPs"),
55 EnablePrefetch("enable-ppc-prefetching",
56 cl::desc("disable software prefetching on PPC"),
57 cl::init(false), cl::Hidden);
60 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
61 cl::desc("Add extra TOC register dependencies"),
62 cl::init(true), cl::Hidden);
65 EnableMachineCombinerPass("ppc-machine-combiner",
66 cl::desc("Enable the machine combiner pass"),
67 cl::init(true), cl::Hidden);
69 extern "C" void LLVMInitializePowerPCTarget() {
70 // Register the targets
71 RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
72 RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
73 RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
75 PassRegistry &PR = *PassRegistry::getPassRegistry();
76 initializePPCBoolRetToIntPass(PR);
79 /// Return the datalayout string of a subtarget.
80 static std::string getDataLayoutString(const Triple &T) {
81 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
84 // Most PPC* platforms are big endian, PPC64LE is little endian.
85 if (T.getArch() == Triple::ppc64le)
90 Ret += DataLayout::getManglingComponent(T);
92 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
94 if (!is64Bit || T.getOS() == Triple::Lv2)
97 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
98 // documentation are wrong; these are correct (i.e. "what gcc does").
99 if (is64Bit || !T.isOSDarwin())
104 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
113 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
115 std::string FullFS = FS;
117 // Make sure 64-bit features are available when CPUname is generic
118 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
120 FullFS = "+64bit," + FullFS;
125 if (OL >= CodeGenOpt::Default) {
127 FullFS = "+crbits," + FullFS;
132 if (OL != CodeGenOpt::None) {
134 FullFS = "+invariant-function-descriptors," + FullFS;
136 FullFS = "+invariant-function-descriptors";
142 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
143 // If it isn't a Mach-O file then it's going to be a linux ELF
146 return make_unique<TargetLoweringObjectFileMachO>();
148 return make_unique<PPC64LinuxTargetObjectFile>();
151 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
152 const TargetOptions &Options) {
153 if (Options.MCOptions.getABIName().startswith("elfv1"))
154 return PPCTargetMachine::PPC_ABI_ELFv1;
155 else if (Options.MCOptions.getABIName().startswith("elfv2"))
156 return PPCTargetMachine::PPC_ABI_ELFv2;
158 assert(Options.MCOptions.getABIName().empty() &&
159 "Unknown target-abi option!");
161 if (!TT.isMacOSX()) {
162 switch (TT.getArch()) {
163 case Triple::ppc64le:
164 return PPCTargetMachine::PPC_ABI_ELFv2;
166 return PPCTargetMachine::PPC_ABI_ELFv1;
172 return PPCTargetMachine::PPC_ABI_UNKNOWN;
175 // The FeatureString here is a little subtle. We are modifying the feature
176 // string with what are (currently) non-function specific overrides as it goes
177 // into the LLVMTargetMachine constructor and then using the stored value in the
178 // Subtarget constructor below it.
179 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
180 StringRef CPU, StringRef FS,
181 const TargetOptions &Options,
182 Reloc::Model RM, CodeModel::Model CM,
183 CodeGenOpt::Level OL)
184 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
185 computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
186 TLOF(createTLOF(getTargetTriple())),
187 TargetABI(computeTargetABI(TT, Options)),
188 Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
190 // For the estimates, convergence is quadratic, so we essentially double the
191 // number of digits correct after every iteration. For both FRE and FRSQRTE,
192 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
193 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
194 unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3,
195 RefinementSteps64 = RefinementSteps + 1;
197 this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps);
198 this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps);
199 this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps);
200 this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps);
202 this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64);
203 this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64);
204 this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64);
205 this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64);
210 PPCTargetMachine::~PPCTargetMachine() {}
212 void PPC32TargetMachine::anchor() { }
214 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
215 StringRef CPU, StringRef FS,
216 const TargetOptions &Options,
217 Reloc::Model RM, CodeModel::Model CM,
218 CodeGenOpt::Level OL)
219 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
221 void PPC64TargetMachine::anchor() { }
223 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
224 StringRef CPU, StringRef FS,
225 const TargetOptions &Options,
226 Reloc::Model RM, CodeModel::Model CM,
227 CodeGenOpt::Level OL)
228 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
231 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
232 Attribute CPUAttr = F.getFnAttribute("target-cpu");
233 Attribute FSAttr = F.getFnAttribute("target-features");
235 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
236 ? CPUAttr.getValueAsString().str()
238 std::string FS = !FSAttr.hasAttribute(Attribute::None)
239 ? FSAttr.getValueAsString().str()
242 auto &I = SubtargetMap[CPU + FS];
244 // This needs to be done before we create a new subtarget since any
245 // creation will depend on the TM and the code generation flags on the
246 // function that reside in TargetOptions.
247 resetTargetOptions(F);
248 I = llvm::make_unique<PPCSubtarget>(
250 // FIXME: It would be good to have the subtarget additions here
251 // not necessary. Anything that turns them on/off (overrides) ends
252 // up being put at the end of the feature string, but the defaults
253 // shouldn't require adding them. Fixing this means pulling Feature64Bit
254 // out of most of the target cpus in the .td file and making it set only
255 // as part of initialization via the TargetTriple.
256 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
261 //===----------------------------------------------------------------------===//
262 // Pass Pipeline Configuration
263 //===----------------------------------------------------------------------===//
266 /// PPC Code Generator Pass Configuration Options.
267 class PPCPassConfig : public TargetPassConfig {
269 PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
270 : TargetPassConfig(TM, PM) {}
272 PPCTargetMachine &getPPCTargetMachine() const {
273 return getTM<PPCTargetMachine>();
276 void addIRPasses() override;
277 bool addPreISel() override;
278 bool addILPOpts() override;
279 bool addInstSelector() override;
280 void addMachineSSAOptimization() override;
281 void addPreRegAlloc() override;
282 void addPreSched2() override;
283 void addPreEmitPass() override;
287 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
288 return new PPCPassConfig(this, PM);
291 void PPCPassConfig::addIRPasses() {
292 if (TM->getOptLevel() != CodeGenOpt::None)
293 addPass(createPPCBoolRetToIntPass());
294 addPass(createAtomicExpandPass(&getPPCTargetMachine()));
296 // For the BG/Q (or if explicitly requested), add explicit data prefetch
298 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
299 getOptLevel() != CodeGenOpt::None;
300 if (EnablePrefetch.getNumOccurrences() > 0)
301 UsePrefetching = EnablePrefetch;
303 addPass(createPPCLoopDataPrefetchPass());
305 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
306 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
307 // and lower a GEP with multiple indices to either arithmetic operations or
308 // multiple GEPs with single index.
309 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
310 // Call EarlyCSE pass to find and remove subexpressions in the lowered
312 addPass(createEarlyCSEPass());
313 // Do loop invariant code motion in case part of the lowered result is
315 addPass(createLICMPass());
318 TargetPassConfig::addIRPasses();
321 bool PPCPassConfig::addPreISel() {
322 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
323 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
325 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
326 addPass(createPPCCTRLoops(getPPCTargetMachine()));
331 bool PPCPassConfig::addILPOpts() {
332 addPass(&EarlyIfConverterID);
334 if (EnableMachineCombinerPass)
335 addPass(&MachineCombinerID);
340 bool PPCPassConfig::addInstSelector() {
341 // Install an instruction selector.
342 addPass(createPPCISelDag(getPPCTargetMachine()));
345 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
346 addPass(createPPCCTRLoopsVerify());
349 addPass(createPPCVSXCopyPass());
353 void PPCPassConfig::addMachineSSAOptimization() {
354 TargetPassConfig::addMachineSSAOptimization();
355 // For little endian, remove where possible the vector swap instructions
356 // introduced at code generation to normalize vector element order.
357 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
358 !DisableVSXSwapRemoval)
359 addPass(createPPCVSXSwapRemovalPass());
360 // Target-specific peephole cleanups performed after instruction
362 if (!DisableMIPeephole) {
363 addPass(createPPCMIPeepholePass());
364 addPass(&DeadMachineInstructionElimID);
368 void PPCPassConfig::addPreRegAlloc() {
369 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
370 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
372 if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
373 addPass(createPPCTLSDynamicCallPass());
374 if (EnableExtraTOCRegDeps)
375 addPass(createPPCTOCRegDepsPass());
378 void PPCPassConfig::addPreSched2() {
379 if (getOptLevel() != CodeGenOpt::None)
380 addPass(&IfConverterID);
383 void PPCPassConfig::addPreEmitPass() {
384 if (getOptLevel() != CodeGenOpt::None)
385 addPass(createPPCEarlyReturnPass(), false);
386 // Must run branch selection immediately preceding the asm printer.
387 addPass(createPPCBranchSelectionPass(), false);
390 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
391 return TargetIRAnalysis([this](const Function &F) {
392 return TargetTransformInfo(PPCTTIImpl(this, F));