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