9a5efc8d0b9e88426d3fe2504ba8e11771be7295
[oota-llvm.git] / lib / Target / ARM / ARMTargetMachine.cpp
1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
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 "ARM.h"
14 #include "ARMFrameLowering.h"
15 #include "ARMTargetMachine.h"
16 #include "ARMTargetObjectFile.h"
17 #include "ARMTargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/MC/MCAsmInfo.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::opt<bool>
30 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
31                    cl::desc("Inhibit optimization of S->D register accesses on A15"),
32                    cl::init(false));
33
34 static cl::opt<bool>
35 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
36                  cl::desc("Run SimplifyCFG after expanding atomic operations"
37                           " to make use of cmpxchg flow-based information"),
38                  cl::init(true));
39
40 static cl::opt<bool>
41 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
42                       cl::desc("Enable ARM load/store optimization pass"),
43                       cl::init(true));
44
45 // FIXME: Unify control over GlobalMerge.
46 static cl::opt<cl::boolOrDefault>
47 EnableGlobalMerge("arm-global-merge", cl::Hidden,
48                   cl::desc("Enable the global merge pass"));
49
50 extern "C" void LLVMInitializeARMTarget() {
51   // Register the target.
52   RegisterTargetMachine<ARMLETargetMachine> X(TheARMLETarget);
53   RegisterTargetMachine<ARMBETargetMachine> Y(TheARMBETarget);
54   RegisterTargetMachine<ThumbLETargetMachine> A(TheThumbLETarget);
55   RegisterTargetMachine<ThumbBETargetMachine> B(TheThumbBETarget);
56 }
57
58 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
59   if (TT.isOSBinFormatMachO())
60     return make_unique<TargetLoweringObjectFileMachO>();
61   if (TT.isOSWindows())
62     return make_unique<TargetLoweringObjectFileCOFF>();
63   return make_unique<ARMElfTargetObjectFile>();
64 }
65
66 static ARMBaseTargetMachine::ARMABI
67 computeTargetABI(const Triple &TT, StringRef CPU,
68                  const TargetOptions &Options) {
69   if (Options.MCOptions.getABIName() == "aapcs16")
70     return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
71   else if (Options.MCOptions.getABIName().startswith("aapcs"))
72     return ARMBaseTargetMachine::ARM_ABI_AAPCS;
73   else if (Options.MCOptions.getABIName().startswith("apcs"))
74     return ARMBaseTargetMachine::ARM_ABI_APCS;
75
76   assert(Options.MCOptions.getABIName().empty() &&
77          "Unknown target-abi option!");
78
79   ARMBaseTargetMachine::ARMABI TargetABI =
80       ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
81
82   // FIXME: This is duplicated code from the front end and should be unified.
83   if (TT.isOSBinFormatMachO()) {
84     if (TT.getEnvironment() == llvm::Triple::EABI ||
85         (TT.getOS() == llvm::Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
86         CPU.startswith("cortex-m")) {
87       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
88     } else if (TT.isWatchOS()) {
89       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
90     } else {
91       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
92     }
93   } else if (TT.isOSWindows()) {
94     // FIXME: this is invalid for WindowsCE
95     TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
96   } else {
97     // Select the default based on the platform.
98     switch (TT.getEnvironment()) {
99     case llvm::Triple::Android:
100     case llvm::Triple::GNUEABI:
101     case llvm::Triple::GNUEABIHF:
102     case llvm::Triple::EABIHF:
103     case llvm::Triple::EABI:
104       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
105       break;
106     case llvm::Triple::GNU:
107       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
108       break;
109     default:
110       if (TT.isOSNetBSD())
111         TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
112       else
113         TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
114       break;
115     }
116   }
117
118   return TargetABI;
119 }
120
121 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
122                                      const TargetOptions &Options,
123                                      bool isLittle) {
124   auto ABI = computeTargetABI(TT, CPU, Options);
125   std::string Ret = "";
126
127   if (isLittle)
128     // Little endian.
129     Ret += "e";
130   else
131     // Big endian.
132     Ret += "E";
133
134   Ret += DataLayout::getManglingComponent(TT);
135
136   // Pointers are 32 bits and aligned to 32 bits.
137   Ret += "-p:32:32";
138
139   // ABIs other than APCS have 64 bit integers with natural alignment.
140   if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
141     Ret += "-i64:64";
142
143   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
144   // bits, others to 64 bits. We always try to align to 64 bits.
145   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
146     Ret += "-f64:32:64";
147
148   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
149   // to 64. We always ty to give them natural alignment.
150   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
151     Ret += "-v64:32:64-v128:32:128";
152   else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
153     Ret += "-v128:64:128";
154
155   // Try to align aggregates to 32 bits (the default is 64 bits, which has no
156   // particular hardware support on 32-bit ARM).
157   Ret += "-a:0:32";
158
159   // Integer registers are 32 bits.
160   Ret += "-n32";
161
162   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
163   // aligned everywhere else.
164   if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
165     Ret += "-S128";
166   else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
167     Ret += "-S64";
168   else
169     Ret += "-S32";
170
171   return Ret;
172 }
173
174 /// TargetMachine ctor - Create an ARM architecture model.
175 ///
176 ARMBaseTargetMachine::ARMBaseTargetMachine(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, bool isLittle)
181     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
182                         CPU, FS, Options, RM, CM, OL),
183       TargetABI(computeTargetABI(TT, CPU, Options)),
184       TLOF(createTLOF(getTargetTriple())),
185       Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
186
187   // Default to triple-appropriate float ABI
188   if (Options.FloatABIType == FloatABI::Default)
189     this->Options.FloatABIType =
190         Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
191 }
192
193 ARMBaseTargetMachine::~ARMBaseTargetMachine() {}
194
195 const ARMSubtarget *
196 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
197   Attribute CPUAttr = F.getFnAttribute("target-cpu");
198   Attribute FSAttr = F.getFnAttribute("target-features");
199
200   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
201                         ? CPUAttr.getValueAsString().str()
202                         : TargetCPU;
203   std::string FS = !FSAttr.hasAttribute(Attribute::None)
204                        ? FSAttr.getValueAsString().str()
205                        : TargetFS;
206
207   // FIXME: This is related to the code below to reset the target options,
208   // we need to know whether or not the soft float flag is set on the
209   // function before we can generate a subtarget. We also need to use
210   // it as a key for the subtarget since that can be the only difference
211   // between two functions.
212   bool SoftFloat =
213       F.hasFnAttribute("use-soft-float") &&
214       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
215   // If the soft float attribute is set on the function turn on the soft float
216   // subtarget feature.
217   if (SoftFloat)
218     FS += FS.empty() ? "+soft-float" : ",+soft-float";
219
220   auto &I = SubtargetMap[CPU + FS];
221   if (!I) {
222     // This needs to be done before we create a new subtarget since any
223     // creation will depend on the TM and the code generation flags on the
224     // function that reside in TargetOptions.
225     resetTargetOptions(F);
226     I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
227   }
228   return I.get();
229 }
230
231 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
232   return TargetIRAnalysis([this](const Function &F) {
233     return TargetTransformInfo(ARMTTIImpl(this, F));
234   });
235 }
236
237 void ARMTargetMachine::anchor() {}
238
239 ARMTargetMachine::ARMTargetMachine(const Target &T, const Triple &TT,
240                                    StringRef CPU, StringRef FS,
241                                    const TargetOptions &Options,
242                                    Reloc::Model RM, CodeModel::Model CM,
243                                    CodeGenOpt::Level OL, bool isLittle)
244     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
245   initAsmInfo();
246   if (!Subtarget.hasARMOps())
247     report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
248                        "support ARM mode execution!");
249 }
250
251 void ARMLETargetMachine::anchor() {}
252
253 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
254                                        StringRef CPU, StringRef FS,
255                                        const TargetOptions &Options,
256                                        Reloc::Model RM, CodeModel::Model CM,
257                                        CodeGenOpt::Level OL)
258     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
259
260 void ARMBETargetMachine::anchor() {}
261
262 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
263                                        StringRef CPU, StringRef FS,
264                                        const TargetOptions &Options,
265                                        Reloc::Model RM, CodeModel::Model CM,
266                                        CodeGenOpt::Level OL)
267     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
268
269 void ThumbTargetMachine::anchor() {}
270
271 ThumbTargetMachine::ThumbTargetMachine(const Target &T, const Triple &TT,
272                                        StringRef CPU, StringRef FS,
273                                        const TargetOptions &Options,
274                                        Reloc::Model RM, CodeModel::Model CM,
275                                        CodeGenOpt::Level OL, bool isLittle)
276     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
277   initAsmInfo();
278 }
279
280 void ThumbLETargetMachine::anchor() {}
281
282 ThumbLETargetMachine::ThumbLETargetMachine(const Target &T, const Triple &TT,
283                                            StringRef CPU, StringRef FS,
284                                            const TargetOptions &Options,
285                                            Reloc::Model RM, CodeModel::Model CM,
286                                            CodeGenOpt::Level OL)
287     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
288
289 void ThumbBETargetMachine::anchor() {}
290
291 ThumbBETargetMachine::ThumbBETargetMachine(const Target &T, const Triple &TT,
292                                            StringRef CPU, StringRef FS,
293                                            const TargetOptions &Options,
294                                            Reloc::Model RM, CodeModel::Model CM,
295                                            CodeGenOpt::Level OL)
296     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
297
298 namespace {
299 /// ARM Code Generator Pass Configuration Options.
300 class ARMPassConfig : public TargetPassConfig {
301 public:
302   ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
303     : TargetPassConfig(TM, PM) {}
304
305   ARMBaseTargetMachine &getARMTargetMachine() const {
306     return getTM<ARMBaseTargetMachine>();
307   }
308
309   void addIRPasses() override;
310   bool addPreISel() override;
311   bool addInstSelector() override;
312   void addPreRegAlloc() override;
313   void addPreSched2() override;
314   void addPreEmitPass() override;
315 };
316 } // namespace
317
318 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
319   return new ARMPassConfig(this, PM);
320 }
321
322 void ARMPassConfig::addIRPasses() {
323   if (TM->Options.ThreadModel == ThreadModel::Single)
324     addPass(createLowerAtomicPass());
325   else
326     addPass(createAtomicExpandPass(TM));
327
328   // Cmpxchg instructions are often used with a subsequent comparison to
329   // determine whether it succeeded. We can exploit existing control-flow in
330   // ldrex/strex loops to simplify this, but it needs tidying up.
331   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
332     addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
333       const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
334       return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
335     }));
336
337   TargetPassConfig::addIRPasses();
338
339   // Match interleaved memory accesses to ldN/stN intrinsics.
340   if (TM->getOptLevel() != CodeGenOpt::None)
341     addPass(createInterleavedAccessPass(TM));
342 }
343
344 bool ARMPassConfig::addPreISel() {
345   if ((TM->getOptLevel() != CodeGenOpt::None &&
346        EnableGlobalMerge == cl::BOU_UNSET) ||
347       EnableGlobalMerge == cl::BOU_TRUE) {
348     // FIXME: This is using the thumb1 only constant value for
349     // maximal global offset for merging globals. We may want
350     // to look into using the old value for non-thumb1 code of
351     // 4095 based on the TargetMachine, but this starts to become
352     // tricky when doing code gen per function.
353     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
354                                (EnableGlobalMerge == cl::BOU_UNSET);
355     // Merging of extern globals is enabled by default on non-Mach-O as we
356     // expect it to be generally either beneficial or harmless. On Mach-O it
357     // is disabled as we emit the .subsections_via_symbols directive which
358     // means that merging extern globals is not safe.
359     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
360     addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
361                                   MergeExternalByDefault));
362   }
363
364   return false;
365 }
366
367 bool ARMPassConfig::addInstSelector() {
368   addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
369   return false;
370 }
371
372 void ARMPassConfig::addPreRegAlloc() {
373   if (getOptLevel() != CodeGenOpt::None) {
374     addPass(createMLxExpansionPass());
375
376     if (EnableARMLoadStoreOpt)
377       addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
378
379     if (!DisableA15SDOptimization)
380       addPass(createA15SDOptimizerPass());
381   }
382 }
383
384 void ARMPassConfig::addPreSched2() {
385   if (getOptLevel() != CodeGenOpt::None) {
386     if (EnableARMLoadStoreOpt)
387       addPass(createARMLoadStoreOptimizationPass());
388
389     addPass(createExecutionDependencyFixPass(&ARM::DPRRegClass));
390   }
391
392   // Expand some pseudo instructions into multiple instructions to allow
393   // proper scheduling.
394   addPass(createARMExpandPseudoPass());
395
396   if (getOptLevel() != CodeGenOpt::None) {
397     // in v8, IfConversion depends on Thumb instruction widths
398     addPass(createThumb2SizeReductionPass([this](const Function &F) {
399       return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
400     }));
401
402     addPass(createIfConverter([this](const Function &F) {
403       return !this->TM->getSubtarget<ARMSubtarget>(F).isThumb1Only();
404     }));
405   }
406   addPass(createThumb2ITBlockPass());
407 }
408
409 void ARMPassConfig::addPreEmitPass() {
410   addPass(createThumb2SizeReductionPass());
411
412   // Constant island pass work on unbundled instructions.
413   addPass(createUnpackMachineBundles([this](const Function &F) {
414     return this->TM->getSubtarget<ARMSubtarget>(F).isThumb2();
415   }));
416
417   // Don't optimize barriers at -O0.
418   if (getOptLevel() != CodeGenOpt::None)
419     addPass(createARMOptimizeBarriersPass());
420
421   addPass(createARMConstantIslandPass());
422 }