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