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