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 "AArch64TargetMachine.h"
14 #include "AArch64.h"
15 #include "AArch64MacroFusion.h"
16 #include "AArch64Subtarget.h"
17 #include "AArch64TargetObjectFile.h"
18 #include "AArch64TargetTransformInfo.h"
19 #include "MCTargetDesc/AArch64MCTargetDesc.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
24 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
25 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
26 #include "llvm/CodeGen/GlobalISel/Localizer.h"
27 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
28 #include "llvm/CodeGen/MachineScheduler.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/TargetPassConfig.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/MC/MCTargetOptions.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include <memory>
42 #include <string>
43 
44 using namespace llvm;
45 
46 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
47                                 cl::desc("Enable the CCMP formation pass"),
48                                 cl::init(true), cl::Hidden);
49 
50 static cl::opt<bool>
51     EnableCondBrTuning("aarch64-enable-cond-br-tune",
52                        cl::desc("Enable the conditional branch tuning pass"),
53                        cl::init(true), cl::Hidden);
54 
55 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
56                                cl::desc("Enable the machine combiner pass"),
57                                cl::init(true), cl::Hidden);
58 
59 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
60                                           cl::desc("Suppress STP for AArch64"),
61                                           cl::init(true), cl::Hidden);
62 
63 static cl::opt<bool> EnableAdvSIMDScalar(
64     "aarch64-enable-simd-scalar",
65     cl::desc("Enable use of AdvSIMD scalar integer instructions"),
66     cl::init(false), cl::Hidden);
67 
68 static cl::opt<bool>
69     EnablePromoteConstant("aarch64-enable-promote-const",
70                           cl::desc("Enable the promote constant pass"),
71                           cl::init(true), cl::Hidden);
72 
73 static cl::opt<bool> EnableCollectLOH(
74     "aarch64-enable-collect-loh",
75     cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
76     cl::init(true), cl::Hidden);
77 
78 static cl::opt<bool>
79     EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
80                                   cl::desc("Enable the pass that removes dead"
81                                            " definitons and replaces stores to"
82                                            " them with stores to the zero"
83                                            " register"),
84                                   cl::init(true));
85 
86 static cl::opt<bool> EnableRedundantCopyElimination(
87     "aarch64-enable-copyelim",
88     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
89     cl::Hidden);
90 
91 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
92                                         cl::desc("Enable the load/store pair"
93                                                  " optimization pass"),
94                                         cl::init(true), cl::Hidden);
95 
96 static cl::opt<bool> EnableAtomicTidy(
97     "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
98     cl::desc("Run SimplifyCFG after expanding atomic operations"
99              " to make use of cmpxchg flow-based information"),
100     cl::init(true));
101 
102 static cl::opt<bool>
103 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
104                         cl::desc("Run early if-conversion"),
105                         cl::init(true));
106 
107 static cl::opt<bool>
108     EnableCondOpt("aarch64-enable-condopt",
109                   cl::desc("Enable the condition optimizer pass"),
110                   cl::init(true), cl::Hidden);
111 
112 static cl::opt<bool>
113 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
114                 cl::desc("Work around Cortex-A53 erratum 835769"),
115                 cl::init(false));
116 
117 static cl::opt<bool>
118     EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
119                  cl::desc("Enable optimizations on complex GEPs"),
120                  cl::init(false));
121 
122 static cl::opt<bool>
123     BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
124                      cl::desc("Relax out of range conditional branches"));
125 
126 // FIXME: Unify control over GlobalMerge.
127 static cl::opt<cl::boolOrDefault>
128     EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
129                       cl::desc("Enable the global merge pass"));
130 
131 static cl::opt<bool>
132     EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
133                            cl::desc("Enable the loop data prefetch pass"),
134                            cl::init(true));
135 
136 static cl::opt<int> EnableGlobalISelAtO(
137     "aarch64-enable-global-isel-at-O", cl::Hidden,
138     cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
139     cl::init(-1));
140 
141 extern "C" void LLVMInitializeAArch64Target() {
142   // Register the target.
143   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
144   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
145   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
146   auto PR = PassRegistry::getPassRegistry();
147   initializeGlobalISel(*PR);
148   initializeAArch64A53Fix835769Pass(*PR);
149   initializeAArch64A57FPLoadBalancingPass(*PR);
150   initializeAArch64AdvSIMDScalarPass(*PR);
151   initializeAArch64CollectLOHPass(*PR);
152   initializeAArch64ConditionalComparesPass(*PR);
153   initializeAArch64ConditionOptimizerPass(*PR);
154   initializeAArch64DeadRegisterDefinitionsPass(*PR);
155   initializeAArch64ExpandPseudoPass(*PR);
156   initializeAArch64LoadStoreOptPass(*PR);
157   initializeAArch64VectorByElementOptPass(*PR);
158   initializeAArch64PromoteConstantPass(*PR);
159   initializeAArch64RedundantCopyEliminationPass(*PR);
160   initializeAArch64StorePairSuppressPass(*PR);
161   initializeLDTLSCleanupPass(*PR);
162 }
163 
164 //===----------------------------------------------------------------------===//
165 // AArch64 Lowering public interface.
166 //===----------------------------------------------------------------------===//
167 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
168   if (TT.isOSBinFormatMachO())
169     return llvm::make_unique<AArch64_MachoTargetObjectFile>();
170 
171   return llvm::make_unique<AArch64_ELFTargetObjectFile>();
172 }
173 
174 // Helper function to build a DataLayout string
175 static std::string computeDataLayout(const Triple &TT,
176                                      const MCTargetOptions &Options,
177                                      bool LittleEndian) {
178   if (Options.getABIName() == "ilp32")
179     return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
180   if (TT.isOSBinFormatMachO())
181     return "e-m:o-i64:64-i128:128-n32:64-S128";
182   if (LittleEndian)
183     return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
184   return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
185 }
186 
187 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
188                                            Optional<Reloc::Model> RM) {
189   // AArch64 Darwin is always PIC.
190   if (TT.isOSDarwin())
191     return Reloc::PIC_;
192   // On ELF platforms the default static relocation model has a smart enough
193   // linker to cope with referencing external symbols defined in a shared
194   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
195   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
196     return Reloc::Static;
197   return *RM;
198 }
199 
200 /// Create an AArch64 architecture model.
201 ///
202 AArch64TargetMachine::AArch64TargetMachine(
203     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
204     const TargetOptions &Options, Optional<Reloc::Model> RM,
205     CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian)
206     // This nested ternary is horrible, but DL needs to be properly
207     // initialized before TLInfo is constructed.
208     : LLVMTargetMachine(T, computeDataLayout(TT, Options.MCOptions,
209                                              LittleEndian),
210                         TT, CPU, FS, Options,
211 			getEffectiveRelocModel(TT, RM), CM, OL),
212       TLOF(createTLOF(getTargetTriple())),
213       isLittle(LittleEndian) {
214   initAsmInfo();
215 }
216 
217 AArch64TargetMachine::~AArch64TargetMachine() = default;
218 
219 const AArch64Subtarget *
220 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
221   Attribute CPUAttr = F.getFnAttribute("target-cpu");
222   Attribute FSAttr = F.getFnAttribute("target-features");
223 
224   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
225                         ? CPUAttr.getValueAsString().str()
226                         : TargetCPU;
227   std::string FS = !FSAttr.hasAttribute(Attribute::None)
228                        ? FSAttr.getValueAsString().str()
229                        : TargetFS;
230 
231   auto &I = SubtargetMap[CPU + FS];
232   if (!I) {
233     // This needs to be done before we create a new subtarget since any
234     // creation will depend on the TM and the code generation flags on the
235     // function that reside in TargetOptions.
236     resetTargetOptions(F);
237     I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
238                                             isLittle);
239   }
240   return I.get();
241 }
242 
243 void AArch64leTargetMachine::anchor() { }
244 
245 AArch64leTargetMachine::AArch64leTargetMachine(
246     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
247     const TargetOptions &Options, Optional<Reloc::Model> RM,
248     CodeModel::Model CM, CodeGenOpt::Level OL)
249     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
250 
251 void AArch64beTargetMachine::anchor() { }
252 
253 AArch64beTargetMachine::AArch64beTargetMachine(
254     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
255     const TargetOptions &Options, Optional<Reloc::Model> RM,
256     CodeModel::Model CM, CodeGenOpt::Level OL)
257     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
258 
259 namespace {
260 
261 /// AArch64 Code Generator Pass Configuration Options.
262 class AArch64PassConfig : public TargetPassConfig {
263 public:
264   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
265       : TargetPassConfig(TM, PM) {
266     if (TM.getOptLevel() != CodeGenOpt::None)
267       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
268   }
269 
270   AArch64TargetMachine &getAArch64TargetMachine() const {
271     return getTM<AArch64TargetMachine>();
272   }
273 
274   ScheduleDAGInstrs *
275   createMachineScheduler(MachineSchedContext *C) const override {
276     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
277     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
278     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
279     DAG->addMutation(createAArch64MacroFusionDAGMutation());
280     return DAG;
281   }
282 
283   ScheduleDAGInstrs *
284   createPostMachineScheduler(MachineSchedContext *C) const override {
285     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
286     if (ST.hasFuseAES() || ST.hasFuseLiterals()) {
287       // Run the Macro Fusion after RA again since literals are expanded from
288       // pseudos then (v. addPreSched2()).
289       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
290       DAG->addMutation(createAArch64MacroFusionDAGMutation());
291       return DAG;
292     }
293 
294     return nullptr;
295   }
296 
297   void addIRPasses()  override;
298   bool addPreISel() override;
299   bool addInstSelector() override;
300 #ifdef LLVM_BUILD_GLOBAL_ISEL
301   bool addIRTranslator() override;
302   bool addLegalizeMachineIR() override;
303   bool addRegBankSelect() override;
304   void addPreGlobalInstructionSelect() override;
305   bool addGlobalInstructionSelect() override;
306 #endif
307   bool addILPOpts() override;
308   void addPreRegAlloc() override;
309   void addPostRegAlloc() override;
310   void addPreSched2() override;
311   void addPreEmitPass() override;
312 
313   bool isGlobalISelEnabled() const override;
314 };
315 
316 } // end anonymous namespace
317 
318 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
319   return TargetIRAnalysis([this](const Function &F) {
320     return TargetTransformInfo(AArch64TTIImpl(this, F));
321   });
322 }
323 
324 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
325   return new AArch64PassConfig(*this, PM);
326 }
327 
328 void AArch64PassConfig::addIRPasses() {
329   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
330   // ourselves.
331   addPass(createAtomicExpandPass());
332 
333   // Cmpxchg instructions are often used with a subsequent comparison to
334   // determine whether it succeeded. We can exploit existing control-flow in
335   // ldrex/strex loops to simplify this, but it needs tidying up.
336   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
337     addPass(createCFGSimplificationPass());
338 
339   // Run LoopDataPrefetch
340   //
341   // Run this before LSR to remove the multiplies involved in computing the
342   // pointer values N iterations ahead.
343   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
344     addPass(createLoopDataPrefetchPass());
345 
346   TargetPassConfig::addIRPasses();
347 
348   // Match interleaved memory accesses to ldN/stN intrinsics.
349   if (TM->getOptLevel() != CodeGenOpt::None)
350     addPass(createInterleavedAccessPass());
351 
352   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
353     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
354     // and lower a GEP with multiple indices to either arithmetic operations or
355     // multiple GEPs with single index.
356     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
357     // Call EarlyCSE pass to find and remove subexpressions in the lowered
358     // result.
359     addPass(createEarlyCSEPass());
360     // Do loop invariant code motion in case part of the lowered result is
361     // invariant.
362     addPass(createLICMPass());
363   }
364 }
365 
366 // Pass Pipeline Configuration
367 bool AArch64PassConfig::addPreISel() {
368   // Run promote constant before global merge, so that the promoted constants
369   // get a chance to be merged
370   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
371     addPass(createAArch64PromoteConstantPass());
372   // FIXME: On AArch64, this depends on the type.
373   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
374   // and the offset has to be a multiple of the related size in bytes.
375   if ((TM->getOptLevel() != CodeGenOpt::None &&
376        EnableGlobalMerge == cl::BOU_UNSET) ||
377       EnableGlobalMerge == cl::BOU_TRUE) {
378     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
379                                (EnableGlobalMerge == cl::BOU_UNSET);
380     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
381   }
382 
383   return false;
384 }
385 
386 bool AArch64PassConfig::addInstSelector() {
387   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
388 
389   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
390   // references to _TLS_MODULE_BASE_ as possible.
391   if (TM->getTargetTriple().isOSBinFormatELF() &&
392       getOptLevel() != CodeGenOpt::None)
393     addPass(createAArch64CleanupLocalDynamicTLSPass());
394 
395   return false;
396 }
397 
398 #ifdef LLVM_BUILD_GLOBAL_ISEL
399 bool AArch64PassConfig::addIRTranslator() {
400   addPass(new IRTranslator());
401   return false;
402 }
403 
404 bool AArch64PassConfig::addLegalizeMachineIR() {
405   addPass(new Legalizer());
406   return false;
407 }
408 
409 bool AArch64PassConfig::addRegBankSelect() {
410   addPass(new RegBankSelect());
411   return false;
412 }
413 
414 void AArch64PassConfig::addPreGlobalInstructionSelect() {
415   // Workaround the deficiency of the fast register allocator.
416   if (TM->getOptLevel() == CodeGenOpt::None)
417     addPass(new Localizer());
418 }
419 
420 bool AArch64PassConfig::addGlobalInstructionSelect() {
421   addPass(new InstructionSelect());
422   return false;
423 }
424 #endif
425 
426 bool AArch64PassConfig::isGlobalISelEnabled() const {
427   return TM->getOptLevel() <= EnableGlobalISelAtO;
428 }
429 
430 bool AArch64PassConfig::addILPOpts() {
431   if (EnableCondOpt)
432     addPass(createAArch64ConditionOptimizerPass());
433   if (EnableCCMP)
434     addPass(createAArch64ConditionalCompares());
435   if (EnableMCR)
436     addPass(&MachineCombinerID);
437   if (EnableCondBrTuning)
438     addPass(createAArch64CondBrTuning());
439   if (EnableEarlyIfConversion)
440     addPass(&EarlyIfConverterID);
441   if (EnableStPairSuppress)
442     addPass(createAArch64StorePairSuppressPass());
443   addPass(createAArch64VectorByElementOptPass());
444   return true;
445 }
446 
447 void AArch64PassConfig::addPreRegAlloc() {
448   // Change dead register definitions to refer to the zero register.
449   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
450     addPass(createAArch64DeadRegisterDefinitions());
451 
452   // Use AdvSIMD scalar instructions whenever profitable.
453   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
454     addPass(createAArch64AdvSIMDScalar());
455     // The AdvSIMD pass may produce copies that can be rewritten to
456     // be register coaleascer friendly.
457     addPass(&PeepholeOptimizerID);
458   }
459 }
460 
461 void AArch64PassConfig::addPostRegAlloc() {
462   // Remove redundant copy instructions.
463   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
464     addPass(createAArch64RedundantCopyEliminationPass());
465 
466   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
467     // Improve performance for some FP/SIMD code for A57.
468     addPass(createAArch64A57FPLoadBalancing());
469 }
470 
471 void AArch64PassConfig::addPreSched2() {
472   // Expand some pseudo instructions to allow proper scheduling.
473   addPass(createAArch64ExpandPseudoPass());
474   // Use load/store pair instructions when possible.
475   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
476     addPass(createAArch64LoadStoreOptimizationPass());
477 }
478 
479 void AArch64PassConfig::addPreEmitPass() {
480   if (EnableA53Fix835769)
481     addPass(createAArch64A53Fix835769());
482   // Relax conditional branch instructions if they're otherwise out of
483   // range of their destination.
484   if (BranchRelaxation)
485     addPass(&BranchRelaxationPassID);
486 
487   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
488       TM->getTargetTriple().isOSBinFormatMachO())
489     addPass(createAArch64CollectLOHPass());
490 }
491