LLVM  mainline
PPCTargetMachine.cpp
Go to the documentation of this file.
00001 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Top-level implementation for the PowerPC target.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCTargetMachine.h"
00015 #include "PPC.h"
00016 #include "PPCTargetObjectFile.h"
00017 #include "PPCTargetTransformInfo.h"
00018 #include "llvm/CodeGen/Passes.h"
00019 #include "llvm/IR/Function.h"
00020 #include "llvm/IR/LegacyPassManager.h"
00021 #include "llvm/MC/MCStreamer.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/FormattedStream.h"
00024 #include "llvm/Support/TargetRegistry.h"
00025 #include "llvm/Target/TargetOptions.h"
00026 #include "llvm/Transforms/Scalar.h"
00027 using namespace llvm;
00028 
00029 static cl::
00030 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
00031                         cl::desc("Disable CTR loops for PPC"));
00032 
00033 static cl::
00034 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
00035                             cl::desc("Disable PPC loop preinc prep"));
00036 
00037 static cl::opt<bool>
00038 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
00039   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
00040 
00041 static cl::
00042 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
00043                                 cl::desc("Disable VSX Swap Removal for PPC"));
00044 
00045 static cl::opt<bool>
00046 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
00047              cl::desc("Enable optimizations on complex GEPs"),
00048              cl::init(true));
00049 
00050 static cl::opt<bool>
00051 EnablePrefetch("enable-ppc-prefetching",
00052                   cl::desc("disable software prefetching on PPC"),
00053                   cl::init(false), cl::Hidden);
00054 
00055 static cl::opt<bool>
00056 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
00057                       cl::desc("Add extra TOC register dependencies"),
00058                       cl::init(true), cl::Hidden);
00059 
00060 extern "C" void LLVMInitializePowerPCTarget() {
00061   // Register the targets
00062   RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
00063   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
00064   RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
00065 }
00066 
00067 /// Return the datalayout string of a subtarget.
00068 static std::string getDataLayoutString(const Triple &T) {
00069   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
00070   std::string Ret;
00071 
00072   // Most PPC* platforms are big endian, PPC64LE is little endian.
00073   if (T.getArch() == Triple::ppc64le)
00074     Ret = "e";
00075   else
00076     Ret = "E";
00077 
00078   Ret += DataLayout::getManglingComponent(T);
00079 
00080   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
00081   // pointers.
00082   if (!is64Bit || T.getOS() == Triple::Lv2)
00083     Ret += "-p:32:32";
00084 
00085   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
00086   // documentation are wrong; these are correct (i.e. "what gcc does").
00087   if (is64Bit || !T.isOSDarwin())
00088     Ret += "-i64:64";
00089   else
00090     Ret += "-f64:32:64";
00091 
00092   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
00093   if (is64Bit)
00094     Ret += "-n32:64";
00095   else
00096     Ret += "-n32";
00097 
00098   return Ret;
00099 }
00100 
00101 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, StringRef TT) {
00102   std::string FullFS = FS;
00103   Triple TargetTriple(TT);
00104 
00105   // Make sure 64-bit features are available when CPUname is generic
00106   if (TargetTriple.getArch() == Triple::ppc64 ||
00107       TargetTriple.getArch() == Triple::ppc64le) {
00108     if (!FullFS.empty())
00109       FullFS = "+64bit," + FullFS;
00110     else
00111       FullFS = "+64bit";
00112   }
00113 
00114   if (OL >= CodeGenOpt::Default) {
00115     if (!FullFS.empty())
00116       FullFS = "+crbits," + FullFS;
00117     else
00118       FullFS = "+crbits";
00119   }
00120 
00121   if (OL != CodeGenOpt::None) {
00122      if (!FullFS.empty())
00123       FullFS = "+invariant-function-descriptors," + FullFS;
00124     else
00125       FullFS = "+invariant-function-descriptors";
00126   }
00127 
00128   return FullFS;
00129 }
00130 
00131 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
00132   // If it isn't a Mach-O file then it's going to be a linux ELF
00133   // object file.
00134   if (TT.isOSDarwin())
00135     return make_unique<TargetLoweringObjectFileMachO>();
00136 
00137   return make_unique<PPC64LinuxTargetObjectFile>();
00138 }
00139 
00140 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
00141                                                  const TargetOptions &Options) {
00142   if (Options.MCOptions.getABIName().startswith("elfv1"))
00143     return PPCTargetMachine::PPC_ABI_ELFv1;
00144   else if (Options.MCOptions.getABIName().startswith("elfv2"))
00145     return PPCTargetMachine::PPC_ABI_ELFv2;
00146 
00147   assert(Options.MCOptions.getABIName().empty() &&
00148    "Unknown target-abi option!");
00149 
00150   if (!TT.isMacOSX()) {
00151     switch (TT.getArch()) {
00152     case Triple::ppc64le:
00153       return PPCTargetMachine::PPC_ABI_ELFv2;
00154     case Triple::ppc64:
00155       return PPCTargetMachine::PPC_ABI_ELFv1;
00156     default:
00157       // Fallthrough.
00158       ;
00159     }
00160   }
00161   return PPCTargetMachine::PPC_ABI_UNKNOWN;
00162 }
00163 
00164 // The FeatureString here is a little subtle. We are modifying the feature string
00165 // with what are (currently) non-function specific overrides as it goes into the
00166 // LLVMTargetMachine constructor and then using the stored value in the
00167 // Subtarget constructor below it.
00168 PPCTargetMachine::PPCTargetMachine(const Target &T, StringRef TT, StringRef CPU,
00169                                    StringRef FS, const TargetOptions &Options,
00170                                    Reloc::Model RM, CodeModel::Model CM,
00171                                    CodeGenOpt::Level OL)
00172     : LLVMTargetMachine(T, getDataLayoutString(Triple(TT)), TT, CPU,
00173                         computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
00174       TLOF(createTLOF(Triple(getTargetTriple()))),
00175       TargetABI(computeTargetABI(Triple(TT), Options)) {
00176   initAsmInfo();
00177 }
00178 
00179 PPCTargetMachine::~PPCTargetMachine() {}
00180 
00181 void PPC32TargetMachine::anchor() { }
00182 
00183 PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT,
00184                                        StringRef CPU, StringRef FS,
00185                                        const TargetOptions &Options,
00186                                        Reloc::Model RM, CodeModel::Model CM,
00187                                        CodeGenOpt::Level OL)
00188   : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
00189 }
00190 
00191 void PPC64TargetMachine::anchor() { }
00192 
00193 PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT,
00194                                        StringRef CPU,  StringRef FS,
00195                                        const TargetOptions &Options,
00196                                        Reloc::Model RM, CodeModel::Model CM,
00197                                        CodeGenOpt::Level OL)
00198   : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
00199 }
00200 
00201 const PPCSubtarget *
00202 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
00203   Attribute CPUAttr = F.getFnAttribute("target-cpu");
00204   Attribute FSAttr = F.getFnAttribute("target-features");
00205 
00206   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
00207                         ? CPUAttr.getValueAsString().str()
00208                         : TargetCPU;
00209   std::string FS = !FSAttr.hasAttribute(Attribute::None)
00210                        ? FSAttr.getValueAsString().str()
00211                        : TargetFS;
00212 
00213   auto &I = SubtargetMap[CPU + FS];
00214   if (!I) {
00215     // This needs to be done before we create a new subtarget since any
00216     // creation will depend on the TM and the code generation flags on the
00217     // function that reside in TargetOptions.
00218     resetTargetOptions(F);
00219     I = llvm::make_unique<PPCSubtarget>(
00220         TargetTriple, CPU,
00221         // FIXME: It would be good to have the subtarget additions here
00222         // not necessary. Anything that turns them on/off (overrides) ends
00223         // up being put at the end of the feature string, but the defaults
00224         // shouldn't require adding them. Fixing this means pulling Feature64Bit
00225         // out of most of the target cpus in the .td file and making it set only
00226         // as part of initialization via the TargetTriple.
00227         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
00228   }
00229   return I.get();
00230 }
00231 
00232 //===----------------------------------------------------------------------===//
00233 // Pass Pipeline Configuration
00234 //===----------------------------------------------------------------------===//
00235 
00236 namespace {
00237 /// PPC Code Generator Pass Configuration Options.
00238 class PPCPassConfig : public TargetPassConfig {
00239 public:
00240   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
00241     : TargetPassConfig(TM, PM) {}
00242 
00243   PPCTargetMachine &getPPCTargetMachine() const {
00244     return getTM<PPCTargetMachine>();
00245   }
00246 
00247   void addIRPasses() override;
00248   bool addPreISel() override;
00249   bool addILPOpts() override;
00250   bool addInstSelector() override;
00251   void addMachineSSAOptimization() override;
00252   void addPreRegAlloc() override;
00253   void addPreSched2() override;
00254   void addPreEmitPass() override;
00255 };
00256 } // namespace
00257 
00258 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
00259   return new PPCPassConfig(this, PM);
00260 }
00261 
00262 void PPCPassConfig::addIRPasses() {
00263   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
00264 
00265   // For the BG/Q (or if explicitly requested), add explicit data prefetch
00266   // intrinsics.
00267   bool UsePrefetching =
00268     Triple(TM->getTargetTriple()).getVendor() == Triple::BGQ &&           
00269     getOptLevel() != CodeGenOpt::None;
00270   if (EnablePrefetch.getNumOccurrences() > 0)
00271     UsePrefetching = EnablePrefetch;
00272   if (UsePrefetching)
00273     addPass(createPPCLoopDataPrefetchPass());
00274 
00275   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
00276     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
00277     // and lower a GEP with multiple indices to either arithmetic operations or
00278     // multiple GEPs with single index.
00279     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
00280     // Call EarlyCSE pass to find and remove subexpressions in the lowered
00281     // result.
00282     addPass(createEarlyCSEPass());
00283     // Do loop invariant code motion in case part of the lowered result is
00284     // invariant.
00285     addPass(createLICMPass());
00286   }
00287 
00288   TargetPassConfig::addIRPasses();
00289 }
00290 
00291 bool PPCPassConfig::addPreISel() {
00292   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
00293     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
00294 
00295   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00296     addPass(createPPCCTRLoops(getPPCTargetMachine()));
00297 
00298   return false;
00299 }
00300 
00301 bool PPCPassConfig::addILPOpts() {
00302   addPass(&EarlyIfConverterID);
00303   return true;
00304 }
00305 
00306 bool PPCPassConfig::addInstSelector() {
00307   // Install an instruction selector.
00308   addPass(createPPCISelDag(getPPCTargetMachine()));
00309 
00310 #ifndef NDEBUG
00311   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00312     addPass(createPPCCTRLoopsVerify());
00313 #endif
00314 
00315   addPass(createPPCVSXCopyPass());
00316   return false;
00317 }
00318 
00319 void PPCPassConfig::addMachineSSAOptimization() {
00320   TargetPassConfig::addMachineSSAOptimization();
00321   // For little endian, remove where possible the vector swap instructions
00322   // introduced at code generation to normalize vector element order.
00323   if (Triple(TM->getTargetTriple()).getArch() == Triple::ppc64le &&
00324       !DisableVSXSwapRemoval)
00325     addPass(createPPCVSXSwapRemovalPass());
00326 }
00327 
00328 void PPCPassConfig::addPreRegAlloc() {
00329   initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
00330   insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
00331              &PPCVSXFMAMutateID);
00332   if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
00333     addPass(createPPCTLSDynamicCallPass());
00334   if (EnableExtraTOCRegDeps)
00335     addPass(createPPCTOCRegDepsPass());
00336 }
00337 
00338 void PPCPassConfig::addPreSched2() {
00339   if (getOptLevel() != CodeGenOpt::None)
00340     addPass(&IfConverterID);
00341 }
00342 
00343 void PPCPassConfig::addPreEmitPass() {
00344   if (getOptLevel() != CodeGenOpt::None)
00345     addPass(createPPCEarlyReturnPass(), false);
00346   // Must run branch selection immediately preceding the asm printer.
00347   addPass(createPPCBranchSelectionPass(), false);
00348 }
00349 
00350 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
00351   return TargetIRAnalysis(
00352       [this](Function &F) { return TargetTransformInfo(PPCTTIImpl(this, F)); });
00353 }