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