1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Top-level implementation for the PowerPC target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCTargetMachine.h"
15 #include "PPC.h"
16 #include "PPCTargetObjectFile.h"
17 #include "PPCTargetTransformInfo.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/TargetPassConfig.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FormattedStream.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Transforms/Scalar.h"
29 using namespace llvm;
30 
31 static cl::
32 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
33                         cl::desc("Disable CTR loops for PPC"));
34 
35 static cl::
36 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
37                             cl::desc("Disable PPC loop preinc prep"));
38 
39 static cl::opt<bool>
40 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
41   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
42 
43 static cl::
44 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
45                                 cl::desc("Disable VSX Swap Removal for PPC"));
46 
47 static cl::
48 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
49                               cl::desc("Disable QPX load splat simplification"));
50 
51 static cl::
52 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
53                             cl::desc("Disable machine peepholes for PPC"));
54 
55 static cl::opt<bool>
56 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
57              cl::desc("Enable optimizations on complex GEPs"),
58              cl::init(true));
59 
60 static cl::opt<bool>
61 EnablePrefetch("enable-ppc-prefetching",
62                   cl::desc("disable software prefetching on PPC"),
63                   cl::init(false), cl::Hidden);
64 
65 static cl::opt<bool>
66 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
67                       cl::desc("Add extra TOC register dependencies"),
68                       cl::init(true), cl::Hidden);
69 
70 static cl::opt<bool>
71 EnableMachineCombinerPass("ppc-machine-combiner",
72                           cl::desc("Enable the machine combiner pass"),
73                           cl::init(true), cl::Hidden);
74 
75 extern "C" void LLVMInitializePowerPCTarget() {
76   // Register the targets
77   RegisterTargetMachine<PPC32TargetMachine> A(getThePPC32Target());
78   RegisterTargetMachine<PPC64TargetMachine> B(getThePPC64Target());
79   RegisterTargetMachine<PPC64TargetMachine> C(getThePPC64LETarget());
80 
81   PassRegistry &PR = *PassRegistry::getPassRegistry();
82   initializePPCBoolRetToIntPass(PR);
83 }
84 
85 /// Return the datalayout string of a subtarget.
86 static std::string getDataLayoutString(const Triple &T) {
87   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
88   std::string Ret;
89 
90   // Most PPC* platforms are big endian, PPC64LE is little endian.
91   if (T.getArch() == Triple::ppc64le)
92     Ret = "e";
93   else
94     Ret = "E";
95 
96   Ret += DataLayout::getManglingComponent(T);
97 
98   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
99   // pointers.
100   if (!is64Bit || T.getOS() == Triple::Lv2)
101     Ret += "-p:32:32";
102 
103   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
104   // documentation are wrong; these are correct (i.e. "what gcc does").
105   if (is64Bit || !T.isOSDarwin())
106     Ret += "-i64:64";
107   else
108     Ret += "-f64:32:64";
109 
110   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
111   if (is64Bit)
112     Ret += "-n32:64";
113   else
114     Ret += "-n32";
115 
116   return Ret;
117 }
118 
119 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
120                                       const Triple &TT) {
121   std::string FullFS = FS;
122 
123   // Make sure 64-bit features are available when CPUname is generic
124   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
125     if (!FullFS.empty())
126       FullFS = "+64bit," + FullFS;
127     else
128       FullFS = "+64bit";
129   }
130 
131   if (OL >= CodeGenOpt::Default) {
132     if (!FullFS.empty())
133       FullFS = "+crbits," + FullFS;
134     else
135       FullFS = "+crbits";
136   }
137 
138   if (OL != CodeGenOpt::None) {
139     if (!FullFS.empty())
140       FullFS = "+invariant-function-descriptors," + FullFS;
141     else
142       FullFS = "+invariant-function-descriptors";
143   }
144 
145   return FullFS;
146 }
147 
148 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
149   // If it isn't a Mach-O file then it's going to be a linux ELF
150   // object file.
151   if (TT.isOSDarwin())
152     return make_unique<TargetLoweringObjectFileMachO>();
153 
154   return make_unique<PPC64LinuxTargetObjectFile>();
155 }
156 
157 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
158                                                  const TargetOptions &Options) {
159   if (Options.MCOptions.getABIName().startswith("elfv1"))
160     return PPCTargetMachine::PPC_ABI_ELFv1;
161   else if (Options.MCOptions.getABIName().startswith("elfv2"))
162     return PPCTargetMachine::PPC_ABI_ELFv2;
163 
164   assert(Options.MCOptions.getABIName().empty() &&
165          "Unknown target-abi option!");
166 
167   if (!TT.isMacOSX()) {
168     switch (TT.getArch()) {
169     case Triple::ppc64le:
170       return PPCTargetMachine::PPC_ABI_ELFv2;
171     case Triple::ppc64:
172       return PPCTargetMachine::PPC_ABI_ELFv1;
173     default:
174       // Fallthrough.
175       ;
176     }
177   }
178   return PPCTargetMachine::PPC_ABI_UNKNOWN;
179 }
180 
181 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
182                                            Optional<Reloc::Model> RM) {
183   if (!RM.hasValue()) {
184     if (TT.isOSDarwin())
185       return Reloc::DynamicNoPIC;
186     return Reloc::Static;
187   }
188   return *RM;
189 }
190 
191 // The FeatureString here is a little subtle. We are modifying the feature
192 // string with what are (currently) non-function specific overrides as it goes
193 // into the LLVMTargetMachine constructor and then using the stored value in the
194 // Subtarget constructor below it.
195 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
196                                    StringRef CPU, StringRef FS,
197                                    const TargetOptions &Options,
198                                    Optional<Reloc::Model> RM,
199                                    CodeModel::Model CM, CodeGenOpt::Level OL)
200     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
201                         computeFSAdditions(FS, OL, TT), Options,
202                         getEffectiveRelocModel(TT, RM), CM, OL),
203       TLOF(createTLOF(getTargetTriple())),
204       TargetABI(computeTargetABI(TT, Options)),
205       Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
206 
207   initAsmInfo();
208 }
209 
210 PPCTargetMachine::~PPCTargetMachine() {}
211 
212 void PPC32TargetMachine::anchor() { }
213 
214 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
215                                        StringRef CPU, StringRef FS,
216                                        const TargetOptions &Options,
217                                        Optional<Reloc::Model> RM,
218                                        CodeModel::Model CM,
219                                        CodeGenOpt::Level OL)
220     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
221 
222 void PPC64TargetMachine::anchor() { }
223 
224 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
225                                        StringRef CPU, StringRef FS,
226                                        const TargetOptions &Options,
227                                        Optional<Reloc::Model> RM,
228                                        CodeModel::Model CM,
229                                        CodeGenOpt::Level OL)
230     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
231 
232 const PPCSubtarget *
233 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
234   Attribute CPUAttr = F.getFnAttribute("target-cpu");
235   Attribute FSAttr = F.getFnAttribute("target-features");
236 
237   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
238                         ? CPUAttr.getValueAsString().str()
239                         : TargetCPU;
240   std::string FS = !FSAttr.hasAttribute(Attribute::None)
241                        ? FSAttr.getValueAsString().str()
242                        : TargetFS;
243 
244   // FIXME: This is related to the code below to reset the target options,
245   // we need to know whether or not the soft float flag is set on the
246   // function before we can generate a subtarget. We also need to use
247   // it as a key for the subtarget since that can be the only difference
248   // between two functions.
249   bool SoftFloat =
250       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
251   // If the soft float attribute is set on the function turn on the soft float
252   // subtarget feature.
253   if (SoftFloat)
254     FS += FS.empty() ? "-hard-float" : ",-hard-float";
255 
256   auto &I = SubtargetMap[CPU + FS];
257   if (!I) {
258     // This needs to be done before we create a new subtarget since any
259     // creation will depend on the TM and the code generation flags on the
260     // function that reside in TargetOptions.
261     resetTargetOptions(F);
262     I = llvm::make_unique<PPCSubtarget>(
263         TargetTriple, CPU,
264         // FIXME: It would be good to have the subtarget additions here
265         // not necessary. Anything that turns them on/off (overrides) ends
266         // up being put at the end of the feature string, but the defaults
267         // shouldn't require adding them. Fixing this means pulling Feature64Bit
268         // out of most of the target cpus in the .td file and making it set only
269         // as part of initialization via the TargetTriple.
270         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
271   }
272   return I.get();
273 }
274 
275 //===----------------------------------------------------------------------===//
276 // Pass Pipeline Configuration
277 //===----------------------------------------------------------------------===//
278 
279 namespace {
280 /// PPC Code Generator Pass Configuration Options.
281 class PPCPassConfig : public TargetPassConfig {
282 public:
283   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
284     : TargetPassConfig(TM, PM) {}
285 
286   PPCTargetMachine &getPPCTargetMachine() const {
287     return getTM<PPCTargetMachine>();
288   }
289 
290   void addIRPasses() override;
291   bool addPreISel() override;
292   bool addILPOpts() override;
293   bool addInstSelector() override;
294   void addMachineSSAOptimization() override;
295   void addPreRegAlloc() override;
296   void addPreSched2() override;
297   void addPreEmitPass() override;
298 };
299 } // namespace
300 
301 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
302   return new PPCPassConfig(this, PM);
303 }
304 
305 void PPCPassConfig::addIRPasses() {
306   if (TM->getOptLevel() != CodeGenOpt::None)
307     addPass(createPPCBoolRetToIntPass());
308   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
309 
310   // For the BG/Q (or if explicitly requested), add explicit data prefetch
311   // intrinsics.
312   bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
313                         getOptLevel() != CodeGenOpt::None;
314   if (EnablePrefetch.getNumOccurrences() > 0)
315     UsePrefetching = EnablePrefetch;
316   if (UsePrefetching)
317     addPass(createLoopDataPrefetchPass());
318 
319   if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
320     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
321     // and lower a GEP with multiple indices to either arithmetic operations or
322     // multiple GEPs with single index.
323     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
324     // Call EarlyCSE pass to find and remove subexpressions in the lowered
325     // result.
326     addPass(createEarlyCSEPass());
327     // Do loop invariant code motion in case part of the lowered result is
328     // invariant.
329     addPass(createLICMPass());
330   }
331 
332   TargetPassConfig::addIRPasses();
333 }
334 
335 bool PPCPassConfig::addPreISel() {
336   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
337     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
338 
339   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
340     addPass(createPPCCTRLoops(getPPCTargetMachine()));
341 
342   return false;
343 }
344 
345 bool PPCPassConfig::addILPOpts() {
346   addPass(&EarlyIfConverterID);
347 
348   if (EnableMachineCombinerPass)
349     addPass(&MachineCombinerID);
350 
351   return true;
352 }
353 
354 bool PPCPassConfig::addInstSelector() {
355   // Install an instruction selector.
356   addPass(createPPCISelDag(getPPCTargetMachine()));
357 
358 #ifndef NDEBUG
359   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
360     addPass(createPPCCTRLoopsVerify());
361 #endif
362 
363   addPass(createPPCVSXCopyPass());
364   return false;
365 }
366 
367 void PPCPassConfig::addMachineSSAOptimization() {
368   TargetPassConfig::addMachineSSAOptimization();
369   // For little endian, remove where possible the vector swap instructions
370   // introduced at code generation to normalize vector element order.
371   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
372       !DisableVSXSwapRemoval)
373     addPass(createPPCVSXSwapRemovalPass());
374   // Target-specific peephole cleanups performed after instruction
375   // selection.
376   if (!DisableMIPeephole) {
377     addPass(createPPCMIPeepholePass());
378     addPass(&DeadMachineInstructionElimID);
379   }
380 }
381 
382 void PPCPassConfig::addPreRegAlloc() {
383   if (getOptLevel() != CodeGenOpt::None) {
384     initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
385     insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
386                &PPCVSXFMAMutateID);
387   }
388 
389   // FIXME: We probably don't need to run these for -fPIE.
390   if (getPPCTargetMachine().isPositionIndependent()) {
391     // FIXME: LiveVariables should not be necessary here!
392     // PPCTLSDYnamicCallPass uses LiveIntervals which previously dependet on
393     // LiveVariables. This (unnecessary) dependency has been removed now,
394     // however a stage-2 clang build fails without LiveVariables computed here.
395     addPass(&LiveVariablesID, false);
396     addPass(createPPCTLSDynamicCallPass());
397   }
398   if (EnableExtraTOCRegDeps)
399     addPass(createPPCTOCRegDepsPass());
400 }
401 
402 void PPCPassConfig::addPreSched2() {
403   if (getOptLevel() != CodeGenOpt::None) {
404     addPass(&IfConverterID);
405 
406     // This optimization must happen after anything that might do store-to-load
407     // forwarding. Here we're after RA (and, thus, when spills are inserted)
408     // but before post-RA scheduling.
409     if (!DisableQPXLoadSplat)
410       addPass(createPPCQPXLoadSplatPass());
411   }
412 }
413 
414 void PPCPassConfig::addPreEmitPass() {
415   if (getOptLevel() != CodeGenOpt::None)
416     addPass(createPPCEarlyReturnPass(), false);
417   // Must run branch selection immediately preceding the asm printer.
418   addPass(createPPCBranchSelectionPass(), false);
419 }
420 
421 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
422   return TargetIRAnalysis([this](const Function &F) {
423     return TargetTransformInfo(PPCTTIImpl(this, F));
424   });
425 }
426