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