dwarfdump: Use the index to find the right abbrev offset in DWP files
[oota-llvm.git] / lib / Target / PowerPC / PPCTargetMachine.cpp
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/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"
27 using namespace llvm;
28
29 static cl::
30 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
31                         cl::desc("Disable CTR loops for PPC"));
32
33 static cl::
34 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
35                             cl::desc("Disable PPC loop preinc prep"));
36
37 static cl::opt<bool>
38 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
39   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
40
41 static cl::
42 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
43                                 cl::desc("Disable VSX Swap Removal for PPC"));
44
45 static cl::
46 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
47                             cl::desc("Disable machine peepholes for PPC"));
48
49 static cl::opt<bool>
50 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
51              cl::desc("Enable optimizations on complex GEPs"),
52              cl::init(true));
53
54 static cl::opt<bool>
55 EnablePrefetch("enable-ppc-prefetching",
56                   cl::desc("disable software prefetching on PPC"),
57                   cl::init(false), cl::Hidden);
58
59 static cl::opt<bool>
60 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
61                       cl::desc("Add extra TOC register dependencies"),
62                       cl::init(true), cl::Hidden);
63
64 static cl::opt<bool>
65 EnableMachineCombinerPass("ppc-machine-combiner",
66                           cl::desc("Enable the machine combiner pass"),
67                           cl::init(true), cl::Hidden);
68
69 extern "C" void LLVMInitializePowerPCTarget() {
70   // Register the targets
71   RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
72   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
73   RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
74 }
75
76 /// Return the datalayout string of a subtarget.
77 static std::string getDataLayoutString(const Triple &T) {
78   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
79   std::string Ret;
80
81   // Most PPC* platforms are big endian, PPC64LE is little endian.
82   if (T.getArch() == Triple::ppc64le)
83     Ret = "e";
84   else
85     Ret = "E";
86
87   Ret += DataLayout::getManglingComponent(T);
88
89   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
90   // pointers.
91   if (!is64Bit || T.getOS() == Triple::Lv2)
92     Ret += "-p:32:32";
93
94   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
95   // documentation are wrong; these are correct (i.e. "what gcc does").
96   if (is64Bit || !T.isOSDarwin())
97     Ret += "-i64:64";
98   else
99     Ret += "-f64:32:64";
100
101   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
102   if (is64Bit)
103     Ret += "-n32:64";
104   else
105     Ret += "-n32";
106
107   return Ret;
108 }
109
110 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
111                                       const Triple &TT) {
112   std::string FullFS = FS;
113
114   // Make sure 64-bit features are available when CPUname is generic
115   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
116     if (!FullFS.empty())
117       FullFS = "+64bit," + FullFS;
118     else
119       FullFS = "+64bit";
120   }
121
122   if (OL >= CodeGenOpt::Default) {
123     if (!FullFS.empty())
124       FullFS = "+crbits," + FullFS;
125     else
126       FullFS = "+crbits";
127   }
128
129   if (OL != CodeGenOpt::None) {
130     if (!FullFS.empty())
131       FullFS = "+invariant-function-descriptors," + FullFS;
132     else
133       FullFS = "+invariant-function-descriptors";
134   }
135
136   return FullFS;
137 }
138
139 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
140   // If it isn't a Mach-O file then it's going to be a linux ELF
141   // object file.
142   if (TT.isOSDarwin())
143     return make_unique<TargetLoweringObjectFileMachO>();
144
145   return make_unique<PPC64LinuxTargetObjectFile>();
146 }
147
148 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
149                                                  const TargetOptions &Options) {
150   if (Options.MCOptions.getABIName().startswith("elfv1"))
151     return PPCTargetMachine::PPC_ABI_ELFv1;
152   else if (Options.MCOptions.getABIName().startswith("elfv2"))
153     return PPCTargetMachine::PPC_ABI_ELFv2;
154
155   assert(Options.MCOptions.getABIName().empty() &&
156          "Unknown target-abi option!");
157
158   if (!TT.isMacOSX()) {
159     switch (TT.getArch()) {
160     case Triple::ppc64le:
161       return PPCTargetMachine::PPC_ABI_ELFv2;
162     case Triple::ppc64:
163       return PPCTargetMachine::PPC_ABI_ELFv1;
164     default:
165       // Fallthrough.
166       ;
167     }
168   }
169   return PPCTargetMachine::PPC_ABI_UNKNOWN;
170 }
171
172 // The FeatureString here is a little subtle. We are modifying the feature
173 // string with what are (currently) non-function specific overrides as it goes
174 // into the LLVMTargetMachine constructor and then using the stored value in the
175 // Subtarget constructor below it.
176 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
177                                    StringRef CPU, StringRef FS,
178                                    const TargetOptions &Options,
179                                    Reloc::Model RM, CodeModel::Model CM,
180                                    CodeGenOpt::Level OL)
181     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
182                         computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
183       TLOF(createTLOF(getTargetTriple())),
184       TargetABI(computeTargetABI(TT, Options)),
185       Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
186
187   // For the estimates, convergence is quadratic, so we essentially double the
188   // number of digits correct after every iteration. For both FRE and FRSQRTE,
189   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
190   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
191   unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3,
192            RefinementSteps64 = RefinementSteps + 1;
193
194   this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps);
195   this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps);
196   this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps);
197   this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps);
198
199   this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64);
200   this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64);
201   this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64);
202   this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64);
203
204   initAsmInfo();
205 }
206
207 PPCTargetMachine::~PPCTargetMachine() {}
208
209 void PPC32TargetMachine::anchor() { }
210
211 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
212                                        StringRef CPU, StringRef FS,
213                                        const TargetOptions &Options,
214                                        Reloc::Model RM, CodeModel::Model CM,
215                                        CodeGenOpt::Level OL)
216     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
217
218 void PPC64TargetMachine::anchor() { }
219
220 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
221                                        StringRef CPU, StringRef FS,
222                                        const TargetOptions &Options,
223                                        Reloc::Model RM, CodeModel::Model CM,
224                                        CodeGenOpt::Level OL)
225     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
226
227 const PPCSubtarget *
228 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
229   Attribute CPUAttr = F.getFnAttribute("target-cpu");
230   Attribute FSAttr = F.getFnAttribute("target-features");
231
232   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
233                         ? CPUAttr.getValueAsString().str()
234                         : TargetCPU;
235   std::string FS = !FSAttr.hasAttribute(Attribute::None)
236                        ? FSAttr.getValueAsString().str()
237                        : TargetFS;
238
239   auto &I = SubtargetMap[CPU + FS];
240   if (!I) {
241     // This needs to be done before we create a new subtarget since any
242     // creation will depend on the TM and the code generation flags on the
243     // function that reside in TargetOptions.
244     resetTargetOptions(F);
245     I = llvm::make_unique<PPCSubtarget>(
246         TargetTriple, CPU,
247         // FIXME: It would be good to have the subtarget additions here
248         // not necessary. Anything that turns them on/off (overrides) ends
249         // up being put at the end of the feature string, but the defaults
250         // shouldn't require adding them. Fixing this means pulling Feature64Bit
251         // out of most of the target cpus in the .td file and making it set only
252         // as part of initialization via the TargetTriple.
253         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
254   }
255   return I.get();
256 }
257
258 //===----------------------------------------------------------------------===//
259 // Pass Pipeline Configuration
260 //===----------------------------------------------------------------------===//
261
262 namespace {
263 /// PPC Code Generator Pass Configuration Options.
264 class PPCPassConfig : public TargetPassConfig {
265 public:
266   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
267     : TargetPassConfig(TM, PM) {}
268
269   PPCTargetMachine &getPPCTargetMachine() const {
270     return getTM<PPCTargetMachine>();
271   }
272
273   void addIRPasses() override;
274   bool addPreISel() override;
275   bool addILPOpts() override;
276   bool addInstSelector() override;
277   void addMachineSSAOptimization() override;
278   void addPreRegAlloc() override;
279   void addPreSched2() override;
280   void addPreEmitPass() override;
281 };
282 } // namespace
283
284 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
285   return new PPCPassConfig(this, PM);
286 }
287
288 void PPCPassConfig::addIRPasses() {
289   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
290
291   // For the BG/Q (or if explicitly requested), add explicit data prefetch
292   // intrinsics.
293   bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
294                         getOptLevel() != CodeGenOpt::None;
295   if (EnablePrefetch.getNumOccurrences() > 0)
296     UsePrefetching = EnablePrefetch;
297   if (UsePrefetching)
298     addPass(createPPCLoopDataPrefetchPass());
299
300   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
301     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
302     // and lower a GEP with multiple indices to either arithmetic operations or
303     // multiple GEPs with single index.
304     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
305     // Call EarlyCSE pass to find and remove subexpressions in the lowered
306     // result.
307     addPass(createEarlyCSEPass());
308     // Do loop invariant code motion in case part of the lowered result is
309     // invariant.
310     addPass(createLICMPass());
311   }
312
313   TargetPassConfig::addIRPasses();
314 }
315
316 bool PPCPassConfig::addPreISel() {
317   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
318     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
319
320   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
321     addPass(createPPCCTRLoops(getPPCTargetMachine()));
322
323   return false;
324 }
325
326 bool PPCPassConfig::addILPOpts() {
327   addPass(&EarlyIfConverterID);
328
329   if (EnableMachineCombinerPass)
330     addPass(&MachineCombinerID);
331
332   return true;
333 }
334
335 bool PPCPassConfig::addInstSelector() {
336   // Install an instruction selector.
337   addPass(createPPCISelDag(getPPCTargetMachine()));
338
339 #ifndef NDEBUG
340   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
341     addPass(createPPCCTRLoopsVerify());
342 #endif
343
344   addPass(createPPCVSXCopyPass());
345   return false;
346 }
347
348 void PPCPassConfig::addMachineSSAOptimization() {
349   TargetPassConfig::addMachineSSAOptimization();
350   // For little endian, remove where possible the vector swap instructions
351   // introduced at code generation to normalize vector element order.
352   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
353       !DisableVSXSwapRemoval)
354     addPass(createPPCVSXSwapRemovalPass());
355   // Target-specific peephole cleanups performed after instruction
356   // selection.
357   if (!DisableMIPeephole) {
358     addPass(createPPCMIPeepholePass());
359     addPass(&DeadMachineInstructionElimID);
360   }
361 }
362
363 void PPCPassConfig::addPreRegAlloc() {
364   initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
365   insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
366              &PPCVSXFMAMutateID);
367   if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
368     addPass(createPPCTLSDynamicCallPass());
369   if (EnableExtraTOCRegDeps)
370     addPass(createPPCTOCRegDepsPass());
371 }
372
373 void PPCPassConfig::addPreSched2() {
374   if (getOptLevel() != CodeGenOpt::None)
375     addPass(&IfConverterID);
376 }
377
378 void PPCPassConfig::addPreEmitPass() {
379   if (getOptLevel() != CodeGenOpt::None)
380     addPass(createPPCEarlyReturnPass(), false);
381   // Must run branch selection immediately preceding the asm printer.
382   addPass(createPPCBranchSelectionPass(), false);
383 }
384
385 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
386   return TargetIRAnalysis([this](const Function &F) {
387     return TargetTransformInfo(PPCTTIImpl(this, F));
388   });
389 }