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 static bool isLittleEndianTriple(const Triple &T) {
130   return T.getArch() == Triple::ppc64le || T.getArch() == Triple::ppcle;
131 }
132 
133 /// Return the datalayout string of a subtarget.
134 static std::string getDataLayoutString(const Triple &T) {
135   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
136   std::string Ret;
137 
138   // Most PPC* platforms are big endian, PPC(64)LE is little endian.
139   if (isLittleEndianTriple(T))
140     Ret = "e";
141   else
142     Ret = "E";
143 
144   Ret += DataLayout::getManglingComponent(T);
145 
146   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
147   // pointers.
148   if (!is64Bit || T.getOS() == Triple::Lv2)
149     Ret += "-p:32:32";
150 
151   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
152   // documentation are wrong; these are correct (i.e. "what gcc does").
153   Ret += "-i64:64";
154 
155   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
156   if (is64Bit)
157     Ret += "-n32:64";
158   else
159     Ret += "-n32";
160 
161   // Specify the vector alignment explicitly. For v256i1 and v512i1, the
162   // calculated alignment would be 256*alignment(i1) and 512*alignment(i1),
163   // which is 256 and 512 bytes - way over aligned.
164   if (is64Bit && (T.isOSAIX() || T.isOSLinux()))
165     Ret += "-S128-v256:256:256-v512:512:512";
166 
167   return Ret;
168 }
169 
170 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
171                                       const Triple &TT) {
172   std::string FullFS = std::string(FS);
173 
174   // Make sure 64-bit features are available when CPUname is generic
175   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
176     if (!FullFS.empty())
177       FullFS = "+64bit," + FullFS;
178     else
179       FullFS = "+64bit";
180   }
181 
182   if (OL >= CodeGenOpt::Default) {
183     if (!FullFS.empty())
184       FullFS = "+crbits," + FullFS;
185     else
186       FullFS = "+crbits";
187   }
188 
189   if (OL != CodeGenOpt::None) {
190     if (!FullFS.empty())
191       FullFS = "+invariant-function-descriptors," + FullFS;
192     else
193       FullFS = "+invariant-function-descriptors";
194   }
195 
196   if (TT.isOSAIX()) {
197     if (!FullFS.empty())
198       FullFS = "+aix," + FullFS;
199     else
200       FullFS = "+aix";
201   }
202 
203   return FullFS;
204 }
205 
206 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
207   if (TT.isOSAIX())
208     return std::make_unique<TargetLoweringObjectFileXCOFF>();
209 
210   return std::make_unique<PPC64LinuxTargetObjectFile>();
211 }
212 
213 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
214                                                  const TargetOptions &Options) {
215   if (Options.MCOptions.getABIName().startswith("elfv1"))
216     return PPCTargetMachine::PPC_ABI_ELFv1;
217   else if (Options.MCOptions.getABIName().startswith("elfv2"))
218     return PPCTargetMachine::PPC_ABI_ELFv2;
219 
220   assert(Options.MCOptions.getABIName().empty() &&
221          "Unknown target-abi option!");
222 
223   if (TT.isMacOSX())
224     return PPCTargetMachine::PPC_ABI_UNKNOWN;
225 
226   switch (TT.getArch()) {
227   case Triple::ppc64le:
228     return PPCTargetMachine::PPC_ABI_ELFv2;
229   case Triple::ppc64:
230     return PPCTargetMachine::PPC_ABI_ELFv1;
231   default:
232     return PPCTargetMachine::PPC_ABI_UNKNOWN;
233   }
234 }
235 
236 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
237                                            Optional<Reloc::Model> RM) {
238   assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) &&
239          "Invalid relocation model for AIX.");
240 
241   if (RM.hasValue())
242     return *RM;
243 
244   // Big Endian PPC and AIX default to PIC.
245   if (TT.getArch() == Triple::ppc64 || TT.isOSAIX())
246     return Reloc::PIC_;
247 
248   // Rest are static by default.
249   return Reloc::Static;
250 }
251 
252 static CodeModel::Model getEffectivePPCCodeModel(const Triple &TT,
253                                                  Optional<CodeModel::Model> CM,
254                                                  bool JIT) {
255   if (CM) {
256     if (*CM == CodeModel::Tiny)
257       report_fatal_error("Target does not support the tiny CodeModel", false);
258     if (*CM == CodeModel::Kernel)
259       report_fatal_error("Target does not support the kernel CodeModel", false);
260     return *CM;
261   }
262 
263   if (JIT)
264     return CodeModel::Small;
265   if (TT.isOSAIX())
266     return CodeModel::Small;
267 
268   assert(TT.isOSBinFormatELF() && "All remaining PPC OSes are ELF based.");
269 
270   if (TT.isArch32Bit())
271     return CodeModel::Small;
272 
273   assert(TT.isArch64Bit() && "Unsupported PPC architecture.");
274   return CodeModel::Medium;
275 }
276 
277 
278 static ScheduleDAGInstrs *createPPCMachineScheduler(MachineSchedContext *C) {
279   const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
280   ScheduleDAGMILive *DAG =
281     new ScheduleDAGMILive(C, ST.usePPCPreRASchedStrategy() ?
282                           std::make_unique<PPCPreRASchedStrategy>(C) :
283                           std::make_unique<GenericScheduler>(C));
284   // add DAG Mutations here.
285   DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
286   if (ST.hasStoreFusion())
287     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
288   if (ST.hasFusion())
289     DAG->addMutation(createPowerPCMacroFusionDAGMutation());
290 
291   return DAG;
292 }
293 
294 static ScheduleDAGInstrs *createPPCPostMachineScheduler(
295   MachineSchedContext *C) {
296   const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
297   ScheduleDAGMI *DAG =
298     new ScheduleDAGMI(C, ST.usePPCPostRASchedStrategy() ?
299                       std::make_unique<PPCPostRASchedStrategy>(C) :
300                       std::make_unique<PostGenericScheduler>(C), true);
301   // add DAG Mutations here.
302   if (ST.hasStoreFusion())
303     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
304   if (ST.hasFusion())
305     DAG->addMutation(createPowerPCMacroFusionDAGMutation());
306   return DAG;
307 }
308 
309 // The FeatureString here is a little subtle. We are modifying the feature
310 // string with what are (currently) non-function specific overrides as it goes
311 // into the LLVMTargetMachine constructor and then using the stored value in the
312 // Subtarget constructor below it.
313 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
314                                    StringRef CPU, StringRef FS,
315                                    const TargetOptions &Options,
316                                    Optional<Reloc::Model> RM,
317                                    Optional<CodeModel::Model> CM,
318                                    CodeGenOpt::Level OL, bool JIT)
319     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
320                         computeFSAdditions(FS, OL, TT), Options,
321                         getEffectiveRelocModel(TT, RM),
322                         getEffectivePPCCodeModel(TT, CM, JIT), OL),
323       TLOF(createTLOF(getTargetTriple())),
324       TargetABI(computeTargetABI(TT, Options)),
325       Endianness(isLittleEndianTriple(TT) ? Endian::LITTLE : Endian::BIG) {
326   initAsmInfo();
327 }
328 
329 PPCTargetMachine::~PPCTargetMachine() = default;
330 
331 const PPCSubtarget *
332 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
333   Attribute CPUAttr = F.getFnAttribute("target-cpu");
334   Attribute FSAttr = F.getFnAttribute("target-features");
335 
336   std::string CPU =
337       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
338   std::string FS =
339       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
340 
341   // FIXME: This is related to the code below to reset the target options,
342   // we need to know whether or not the soft float flag is set on the
343   // function before we can generate a subtarget. We also need to use
344   // it as a key for the subtarget since that can be the only difference
345   // between two functions.
346   bool SoftFloat =
347       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
348   // If the soft float attribute is set on the function turn on the soft float
349   // subtarget feature.
350   if (SoftFloat)
351     FS += FS.empty() ? "-hard-float" : ",-hard-float";
352 
353   auto &I = SubtargetMap[CPU + FS];
354   if (!I) {
355     // This needs to be done before we create a new subtarget since any
356     // creation will depend on the TM and the code generation flags on the
357     // function that reside in TargetOptions.
358     resetTargetOptions(F);
359     I = std::make_unique<PPCSubtarget>(
360         TargetTriple, CPU,
361         // FIXME: It would be good to have the subtarget additions here
362         // not necessary. Anything that turns them on/off (overrides) ends
363         // up being put at the end of the feature string, but the defaults
364         // shouldn't require adding them. Fixing this means pulling Feature64Bit
365         // out of most of the target cpus in the .td file and making it set only
366         // as part of initialization via the TargetTriple.
367         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
368   }
369   return I.get();
370 }
371 
372 //===----------------------------------------------------------------------===//
373 // Pass Pipeline Configuration
374 //===----------------------------------------------------------------------===//
375 
376 namespace {
377 
378 /// PPC Code Generator Pass Configuration Options.
379 class PPCPassConfig : public TargetPassConfig {
380 public:
381   PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM)
382     : TargetPassConfig(TM, PM) {
383     // At any optimization level above -O0 we use the Machine Scheduler and not
384     // the default Post RA List Scheduler.
385     if (TM.getOptLevel() != CodeGenOpt::None)
386       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
387   }
388 
389   PPCTargetMachine &getPPCTargetMachine() const {
390     return getTM<PPCTargetMachine>();
391   }
392 
393   void addIRPasses() override;
394   bool addPreISel() override;
395   bool addILPOpts() override;
396   bool addInstSelector() override;
397   void addMachineSSAOptimization() override;
398   void addPreRegAlloc() override;
399   void addPreSched2() override;
400   void addPreEmitPass() override;
401   // GlobalISEL
402   bool addIRTranslator() override;
403   bool addLegalizeMachineIR() override;
404   bool addRegBankSelect() override;
405   bool addGlobalInstructionSelect() override;
406 
407   ScheduleDAGInstrs *
408   createMachineScheduler(MachineSchedContext *C) const override {
409     return createPPCMachineScheduler(C);
410   }
411   ScheduleDAGInstrs *
412   createPostMachineScheduler(MachineSchedContext *C) const override {
413     return createPPCPostMachineScheduler(C);
414   }
415 };
416 
417 } // end anonymous namespace
418 
419 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
420   return new PPCPassConfig(*this, PM);
421 }
422 
423 void PPCPassConfig::addIRPasses() {
424   if (TM->getOptLevel() != CodeGenOpt::None)
425     addPass(createPPCBoolRetToIntPass());
426   addPass(createAtomicExpandPass());
427 
428   // Lower generic MASSV routines to PowerPC subtarget-specific entries.
429   addPass(createPPCLowerMASSVEntriesPass());
430 
431   // If explicitly requested, add explicit data prefetch intrinsics.
432   if (EnablePrefetch.getNumOccurrences() > 0)
433     addPass(createLoopDataPrefetchPass());
434 
435   if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
436     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
437     // and lower a GEP with multiple indices to either arithmetic operations or
438     // multiple GEPs with single index.
439     addPass(createSeparateConstOffsetFromGEPPass(true));
440     // Call EarlyCSE pass to find and remove subexpressions in the lowered
441     // result.
442     addPass(createEarlyCSEPass());
443     // Do loop invariant code motion in case part of the lowered result is
444     // invariant.
445     addPass(createLICMPass());
446   }
447 
448   TargetPassConfig::addIRPasses();
449 }
450 
451 bool PPCPassConfig::addPreISel() {
452   if (!DisableInstrFormPrep && getOptLevel() != CodeGenOpt::None)
453     addPass(createPPCLoopInstrFormPrepPass(getPPCTargetMachine()));
454 
455   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
456     addPass(createHardwareLoopsPass());
457 
458   return false;
459 }
460 
461 bool PPCPassConfig::addILPOpts() {
462   addPass(&EarlyIfConverterID);
463 
464   if (EnableMachineCombinerPass)
465     addPass(&MachineCombinerID);
466 
467   return true;
468 }
469 
470 bool PPCPassConfig::addInstSelector() {
471   // Install an instruction selector.
472   addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
473 
474 #ifndef NDEBUG
475   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
476     addPass(createPPCCTRLoopsVerify());
477 #endif
478 
479   addPass(createPPCVSXCopyPass());
480   return false;
481 }
482 
483 void PPCPassConfig::addMachineSSAOptimization() {
484   // PPCBranchCoalescingPass need to be done before machine sinking
485   // since it merges empty blocks.
486   if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None)
487     addPass(createPPCBranchCoalescingPass());
488   TargetPassConfig::addMachineSSAOptimization();
489   // For little endian, remove where possible the vector swap instructions
490   // introduced at code generation to normalize vector element order.
491   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
492       !DisableVSXSwapRemoval)
493     addPass(createPPCVSXSwapRemovalPass());
494   // Reduce the number of cr-logical ops.
495   if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None)
496     addPass(createPPCReduceCRLogicalsPass());
497   // Target-specific peephole cleanups performed after instruction
498   // selection.
499   if (!DisableMIPeephole) {
500     addPass(createPPCMIPeepholePass());
501     addPass(&DeadMachineInstructionElimID);
502   }
503 }
504 
505 void PPCPassConfig::addPreRegAlloc() {
506   if (getOptLevel() != CodeGenOpt::None) {
507     initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
508     insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
509                &PPCVSXFMAMutateID);
510   }
511 
512   // FIXME: We probably don't need to run these for -fPIE.
513   if (getPPCTargetMachine().isPositionIndependent()) {
514     // FIXME: LiveVariables should not be necessary here!
515     // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
516     // LiveVariables. This (unnecessary) dependency has been removed now,
517     // however a stage-2 clang build fails without LiveVariables computed here.
518     addPass(&LiveVariablesID);
519     addPass(createPPCTLSDynamicCallPass());
520   }
521   if (EnableExtraTOCRegDeps)
522     addPass(createPPCTOCRegDepsPass());
523 
524   if (getOptLevel() != CodeGenOpt::None)
525     addPass(&MachinePipelinerID);
526 }
527 
528 void PPCPassConfig::addPreSched2() {
529   if (getOptLevel() != CodeGenOpt::None)
530     addPass(&IfConverterID);
531 }
532 
533 void PPCPassConfig::addPreEmitPass() {
534   addPass(createPPCPreEmitPeepholePass());
535   addPass(createPPCExpandISELPass());
536 
537   if (getOptLevel() != CodeGenOpt::None)
538     addPass(createPPCEarlyReturnPass());
539   // Must run branch selection immediately preceding the asm printer.
540   addPass(createPPCBranchSelectionPass());
541 }
542 
543 TargetTransformInfo
544 PPCTargetMachine::getTargetTransformInfo(const Function &F) {
545   return TargetTransformInfo(PPCTTIImpl(this, F));
546 }
547 
548 bool PPCTargetMachine::isLittleEndian() const {
549   assert(Endianness != Endian::NOT_DETECTED &&
550          "Unable to determine endianness");
551   return Endianness == Endian::LITTLE;
552 }
553 
554 static MachineSchedRegistry
555 PPCPreRASchedRegistry("ppc-prera",
556                       "Run PowerPC PreRA specific scheduler",
557                       createPPCMachineScheduler);
558 
559 static MachineSchedRegistry
560 PPCPostRASchedRegistry("ppc-postra",
561                        "Run PowerPC PostRA specific scheduler",
562                        createPPCPostMachineScheduler);
563 
564 // Global ISEL
565 bool PPCPassConfig::addIRTranslator() {
566   addPass(new IRTranslator());
567   return false;
568 }
569 
570 bool PPCPassConfig::addLegalizeMachineIR() {
571   addPass(new Legalizer());
572   return false;
573 }
574 
575 bool PPCPassConfig::addRegBankSelect() {
576   addPass(new RegBankSelect());
577   return false;
578 }
579 
580 bool PPCPassConfig::addGlobalInstructionSelect() {
581   addPass(new InstructionSelect(getOptLevel()));
582   return false;
583 }
584