[AArch64] Match interleaved memory accesses into ldN/stN instructions.
[oota-llvm.git] / lib / Target / AArch64 / AArch64TargetMachine.cpp
1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
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 //
11 //===----------------------------------------------------------------------===//
12
13 #include "AArch64.h"
14 #include "AArch64TargetMachine.h"
15 #include "AArch64TargetObjectFile.h"
16 #include "AArch64TargetTransformInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/RegAllocRegistry.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/TargetRegistry.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/Transforms/Scalar.h"
25 using namespace llvm;
26
27 static cl::opt<bool>
28 EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
29            cl::init(true), cl::Hidden);
30
31 static cl::opt<bool> EnableMCR("aarch64-mcr",
32                                cl::desc("Enable the machine combiner pass"),
33                                cl::init(true), cl::Hidden);
34
35 static cl::opt<bool>
36 EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
37                      cl::init(true), cl::Hidden);
38
39 static cl::opt<bool>
40 EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
41                     " integer instructions"), cl::init(false), cl::Hidden);
42
43 static cl::opt<bool>
44 EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
45                       "constant pass"), cl::init(true), cl::Hidden);
46
47 static cl::opt<bool>
48 EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
49                  " linker optimization hints (LOH)"), cl::init(true),
50                  cl::Hidden);
51
52 static cl::opt<bool>
53 EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
54                               cl::desc("Enable the pass that removes dead"
55                                        " definitons and replaces stores to"
56                                        " them with stores to the zero"
57                                        " register"),
58                               cl::init(true));
59
60 static cl::opt<bool>
61 EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
62                    " optimization pass"), cl::init(true), cl::Hidden);
63
64 static cl::opt<bool>
65 EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
66                  cl::desc("Run SimplifyCFG after expanding atomic operations"
67                           " to make use of cmpxchg flow-based information"),
68                  cl::init(true));
69
70 static cl::opt<bool> AArch64InterleavedAccessOpt(
71     "aarch64-interleaved-access-opt",
72     cl::desc("Optimize interleaved memory accesses in the AArch64 backend"),
73     cl::init(false), cl::Hidden);
74
75 static cl::opt<bool>
76 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
77                         cl::desc("Run early if-conversion"),
78                         cl::init(true));
79
80 static cl::opt<bool>
81 EnableCondOpt("aarch64-condopt",
82               cl::desc("Enable the condition optimizer pass"),
83               cl::init(true), cl::Hidden);
84
85 static cl::opt<bool>
86 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
87                 cl::desc("Work around Cortex-A53 erratum 835769"),
88                 cl::init(false));
89
90 static cl::opt<bool>
91 EnableGEPOpt("aarch64-gep-opt", cl::Hidden,
92              cl::desc("Enable optimizations on complex GEPs"),
93              cl::init(false));
94
95 // FIXME: Unify control over GlobalMerge.
96 static cl::opt<cl::boolOrDefault>
97 EnableGlobalMerge("aarch64-global-merge", cl::Hidden,
98                   cl::desc("Enable the global merge pass"));
99
100 extern "C" void LLVMInitializeAArch64Target() {
101   // Register the target.
102   RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
103   RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);
104   RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target);
105 }
106
107 //===----------------------------------------------------------------------===//
108 // AArch64 Lowering public interface.
109 //===----------------------------------------------------------------------===//
110 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
111   if (TT.isOSBinFormatMachO())
112     return make_unique<AArch64_MachoTargetObjectFile>();
113
114   return make_unique<AArch64_ELFTargetObjectFile>();
115 }
116
117 // Helper function to build a DataLayout string
118 static std::string computeDataLayout(StringRef TT, bool LittleEndian) {
119   Triple Triple(TT);
120   if (Triple.isOSBinFormatMachO())
121     return "e-m:o-i64:64-i128:128-n32:64-S128";
122   if (LittleEndian)
123     return "e-m:e-i64:64-i128:128-n32:64-S128";
124   return "E-m:e-i64:64-i128:128-n32:64-S128";
125 }
126
127 /// TargetMachine ctor - Create an AArch64 architecture model.
128 ///
129 AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT,
130                                            StringRef CPU, StringRef FS,
131                                            const TargetOptions &Options,
132                                            Reloc::Model RM, CodeModel::Model CM,
133                                            CodeGenOpt::Level OL,
134                                            bool LittleEndian)
135     // This nested ternary is horrible, but DL needs to be properly
136     // initialized before TLInfo is constructed.
137     : LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS,
138                         Options, RM, CM, OL),
139       TLOF(createTLOF(Triple(getTargetTriple()))),
140       isLittle(LittleEndian) {
141   initAsmInfo();
142 }
143
144 AArch64TargetMachine::~AArch64TargetMachine() {}
145
146 const AArch64Subtarget *
147 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
148   Attribute CPUAttr = F.getFnAttribute("target-cpu");
149   Attribute FSAttr = F.getFnAttribute("target-features");
150
151   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
152                         ? CPUAttr.getValueAsString().str()
153                         : TargetCPU;
154   std::string FS = !FSAttr.hasAttribute(Attribute::None)
155                        ? FSAttr.getValueAsString().str()
156                        : TargetFS;
157
158   auto &I = SubtargetMap[CPU + FS];
159   if (!I) {
160     // This needs to be done before we create a new subtarget since any
161     // creation will depend on the TM and the code generation flags on the
162     // function that reside in TargetOptions.
163     resetTargetOptions(F);
164     I = llvm::make_unique<AArch64Subtarget>(Triple(TargetTriple), CPU, FS,
165                                             *this, isLittle);
166   }
167   return I.get();
168 }
169
170 void AArch64leTargetMachine::anchor() { }
171
172 AArch64leTargetMachine::
173 AArch64leTargetMachine(const Target &T, StringRef TT,
174                        StringRef CPU, StringRef FS, const TargetOptions &Options,
175                        Reloc::Model RM, CodeModel::Model CM,
176                        CodeGenOpt::Level OL)
177   : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
178
179 void AArch64beTargetMachine::anchor() { }
180
181 AArch64beTargetMachine::
182 AArch64beTargetMachine(const Target &T, StringRef TT,
183                        StringRef CPU, StringRef FS, const TargetOptions &Options,
184                        Reloc::Model RM, CodeModel::Model CM,
185                        CodeGenOpt::Level OL)
186   : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
187
188 namespace {
189 /// AArch64 Code Generator Pass Configuration Options.
190 class AArch64PassConfig : public TargetPassConfig {
191 public:
192   AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
193       : TargetPassConfig(TM, PM) {
194     if (TM->getOptLevel() != CodeGenOpt::None)
195       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
196   }
197
198   AArch64TargetMachine &getAArch64TargetMachine() const {
199     return getTM<AArch64TargetMachine>();
200   }
201
202   void addIRPasses()  override;
203   bool addPreISel() override;
204   bool addInstSelector() override;
205   bool addILPOpts() override;
206   void addPreRegAlloc() override;
207   void addPostRegAlloc() override;
208   void addPreSched2() override;
209   void addPreEmitPass() override;
210 };
211 } // namespace
212
213 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
214   return TargetIRAnalysis([this](Function &F) {
215     return TargetTransformInfo(AArch64TTIImpl(this, F));
216   });
217 }
218
219 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
220   return new AArch64PassConfig(this, PM);
221 }
222
223 void AArch64PassConfig::addIRPasses() {
224   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
225   // ourselves.
226   addPass(createAtomicExpandPass(TM));
227
228   // Cmpxchg instructions are often used with a subsequent comparison to
229   // determine whether it succeeded. We can exploit existing control-flow in
230   // ldrex/strex loops to simplify this, but it needs tidying up.
231   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
232     addPass(createCFGSimplificationPass());
233
234   if (TM->getOptLevel() != CodeGenOpt::None && AArch64InterleavedAccessOpt)
235     addPass(createAArch64InterleavedAccessPass());
236
237   TargetPassConfig::addIRPasses();
238
239   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
240     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
241     // and lower a GEP with multiple indices to either arithmetic operations or
242     // multiple GEPs with single index.
243     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
244     // Call EarlyCSE pass to find and remove subexpressions in the lowered
245     // result.
246     addPass(createEarlyCSEPass());
247     // Do loop invariant code motion in case part of the lowered result is
248     // invariant.
249     addPass(createLICMPass());
250   }
251 }
252
253 // Pass Pipeline Configuration
254 bool AArch64PassConfig::addPreISel() {
255   // Run promote constant before global merge, so that the promoted constants
256   // get a chance to be merged
257   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
258     addPass(createAArch64PromoteConstantPass());
259   // FIXME: On AArch64, this depends on the type.
260   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
261   // and the offset has to be a multiple of the related size in bytes.
262   if ((TM->getOptLevel() != CodeGenOpt::None &&
263        EnableGlobalMerge == cl::BOU_UNSET) ||
264       EnableGlobalMerge == cl::BOU_TRUE) {
265     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
266                                (EnableGlobalMerge == cl::BOU_UNSET);
267     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
268   }
269
270   if (TM->getOptLevel() != CodeGenOpt::None)
271     addPass(createAArch64AddressTypePromotionPass());
272
273   return false;
274 }
275
276 bool AArch64PassConfig::addInstSelector() {
277   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
278
279   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
280   // references to _TLS_MODULE_BASE_ as possible.
281   if (Triple(TM->getTargetTriple()).isOSBinFormatELF() &&
282       getOptLevel() != CodeGenOpt::None)
283     addPass(createAArch64CleanupLocalDynamicTLSPass());
284
285   return false;
286 }
287
288 bool AArch64PassConfig::addILPOpts() {
289   if (EnableCondOpt)
290     addPass(createAArch64ConditionOptimizerPass());
291   if (EnableCCMP)
292     addPass(createAArch64ConditionalCompares());
293   if (EnableMCR)
294     addPass(&MachineCombinerID);
295   if (EnableEarlyIfConversion)
296     addPass(&EarlyIfConverterID);
297   if (EnableStPairSuppress)
298     addPass(createAArch64StorePairSuppressPass());
299   return true;
300 }
301
302 void AArch64PassConfig::addPreRegAlloc() {
303   // Use AdvSIMD scalar instructions whenever profitable.
304   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
305     addPass(createAArch64AdvSIMDScalar());
306     // The AdvSIMD pass may produce copies that can be rewritten to
307     // be register coaleascer friendly.
308     addPass(&PeepholeOptimizerID);
309   }
310 }
311
312 void AArch64PassConfig::addPostRegAlloc() {
313   // Change dead register definitions to refer to the zero register.
314   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
315     addPass(createAArch64DeadRegisterDefinitions());
316   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
317     // Improve performance for some FP/SIMD code for A57.
318     addPass(createAArch64A57FPLoadBalancing());
319 }
320
321 void AArch64PassConfig::addPreSched2() {
322   // Expand some pseudo instructions to allow proper scheduling.
323   addPass(createAArch64ExpandPseudoPass());
324   // Use load/store pair instructions when possible.
325   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
326     addPass(createAArch64LoadStoreOptimizationPass());
327 }
328
329 void AArch64PassConfig::addPreEmitPass() {
330   if (EnableA53Fix835769)
331     addPass(createAArch64A53Fix835769());
332   // Relax conditional branch instructions if they're otherwise out of
333   // range of their destination.
334   addPass(createAArch64BranchRelaxation());
335   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
336       Triple(TM->getTargetTriple()).isOSBinFormatMachO())
337     addPass(createAArch64CollectLOHPass());
338 }