2041e682dc245d6a964fa5df6378a32513a8e267
[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 "llvm/CodeGen/Passes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/TargetRegistry.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Transforms/Scalar.h"
26 using namespace llvm;
27
28 static cl::opt<bool>
29 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
30                    cl::desc("Inhibit optimization of S->D register accesses on A15"),
31                    cl::init(false));
32
33 static cl::opt<bool>
34 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
35                  cl::desc("Run SimplifyCFG after expanding atomic operations"
36                           " to make use of cmpxchg flow-based information"),
37                  cl::init(true));
38
39 extern "C" void LLVMInitializeARMTarget() {
40   // Register the target.
41   RegisterTargetMachine<ARMLETargetMachine> X(TheARMLETarget);
42   RegisterTargetMachine<ARMBETargetMachine> Y(TheARMBETarget);
43   RegisterTargetMachine<ThumbLETargetMachine> A(TheThumbLETarget);
44   RegisterTargetMachine<ThumbBETargetMachine> B(TheThumbBETarget);
45 }
46
47 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
48   if (TT.isOSBinFormatMachO())
49     return make_unique<TargetLoweringObjectFileMachO>();
50   if (TT.isOSWindows())
51     return make_unique<TargetLoweringObjectFileCOFF>();
52   return make_unique<ARMElfTargetObjectFile>();
53 }
54
55 static ARMBaseTargetMachine::ARMABI
56 computeTargetABI(const Triple &TT, StringRef CPU,
57                  const TargetOptions &Options) {
58   if (Options.MCOptions.getABIName().startswith("aapcs"))
59     return ARMBaseTargetMachine::ARM_ABI_AAPCS;
60   else if (Options.MCOptions.getABIName().startswith("apcs"))
61     return ARMBaseTargetMachine::ARM_ABI_APCS;
62
63   assert(Options.MCOptions.getABIName().empty() &&
64          "Unknown target-abi option!");
65
66   ARMBaseTargetMachine::ARMABI TargetABI =
67       ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
68
69   // FIXME: This is duplicated code from the front end and should be unified.
70   if (TT.isOSBinFormatMachO()) {
71     if (TT.getEnvironment() == llvm::Triple::EABI ||
72         (TT.getOS() == llvm::Triple::UnknownOS &&
73          TT.getObjectFormat() == llvm::Triple::MachO) ||
74         CPU.startswith("cortex-m")) {
75       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
76     } else {
77       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
78     }
79   } else if (TT.isOSWindows()) {
80     // FIXME: this is invalid for WindowsCE
81     TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
82   } else {
83     // Select the default based on the platform.
84     switch (TT.getEnvironment()) {
85     case llvm::Triple::Android:
86     case llvm::Triple::GNUEABI:
87     case llvm::Triple::GNUEABIHF:
88     case llvm::Triple::EABIHF:
89     case llvm::Triple::EABI:
90       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
91       break;
92     case llvm::Triple::GNU:
93       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
94       break;
95     default:
96       if (TT.getOS() == llvm::Triple::NetBSD)
97         TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
98       else
99         TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
100       break;
101     }
102   }
103
104   return TargetABI;
105 }
106
107 static std::string computeDataLayout(const Triple &TT,
108                                      ARMBaseTargetMachine::ARMABI ABI,
109                                      bool isLittle) {
110   std::string Ret = "";
111
112   if (isLittle)
113     // Little endian.
114     Ret += "e";
115   else
116     // Big endian.
117     Ret += "E";
118
119   Ret += DataLayout::getManglingComponent(TT);
120
121   // Pointers are 32 bits and aligned to 32 bits.
122   Ret += "-p:32:32";
123
124   // ABIs other than APCS have 64 bit integers with natural alignment.
125   if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
126     Ret += "-i64:64";
127
128   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
129   // bits, others to 64 bits. We always try to align to 64 bits.
130   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
131     Ret += "-f64:32:64";
132
133   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
134   // to 64. We always ty to give them natural alignment.
135   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
136     Ret += "-v64:32:64-v128:32:128";
137   else
138     Ret += "-v128:64:128";
139
140   // Try to align aggregates to 32 bits (the default is 64 bits, which has no
141   // particular hardware support on 32-bit ARM).
142   Ret += "-a:0:32";
143
144   // Integer registers are 32 bits.
145   Ret += "-n32";
146
147   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
148   // aligned everywhere else.
149   if (TT.isOSNaCl())
150     Ret += "-S128";
151   else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
152     Ret += "-S64";
153   else
154     Ret += "-S32";
155
156   return Ret;
157 }
158
159 /// TargetMachine ctor - Create an ARM architecture model.
160 ///
161 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, StringRef TT,
162                                            StringRef CPU, StringRef FS,
163                                            const TargetOptions &Options,
164                                            Reloc::Model RM, CodeModel::Model CM,
165                                            CodeGenOpt::Level OL, bool isLittle)
166     : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
167       TargetABI(computeTargetABI(Triple(TT), CPU, Options)),
168       DL(computeDataLayout(Triple(TT), TargetABI, isLittle)),
169       TLOF(createTLOF(Triple(getTargetTriple()))),
170       Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
171
172   // Default to triple-appropriate float ABI
173   if (Options.FloatABIType == FloatABI::Default)
174     this->Options.FloatABIType =
175         Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
176 }
177
178 ARMBaseTargetMachine::~ARMBaseTargetMachine() {}
179
180 const ARMSubtarget *
181 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
182   AttributeSet FnAttrs = F.getAttributes();
183   Attribute CPUAttr =
184       FnAttrs.getAttribute(AttributeSet::FunctionIndex, "target-cpu");
185   Attribute FSAttr =
186       FnAttrs.getAttribute(AttributeSet::FunctionIndex, "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 =
201       FnAttrs.getAttribute(AttributeSet::FunctionIndex, "use-soft-float");
202   bool SoftFloat = !SFAttr.hasAttribute(Attribute::None)
203                        ? SFAttr.getValueAsString() == "true"
204                        : Options.UseSoftFloat;
205
206   auto &I = SubtargetMap[CPU + FS + (SoftFloat ? "use-soft-float=true"
207                                                : "use-soft-float=false")];
208   if (!I) {
209     // This needs to be done before we create a new subtarget since any
210     // creation will depend on the TM and the code generation flags on the
211     // function that reside in TargetOptions.
212     resetTargetOptions(F);
213     I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
214   }
215   return I.get();
216 }
217
218 void ARMBaseTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
219   // Add first the target-independent BasicTTI pass, then our ARM pass. This
220   // allows the ARM pass to delegate to the target independent layer when
221   // appropriate.
222   PM.add(createBasicTargetTransformInfoPass(this));
223   PM.add(createARMTargetTransformInfoPass(this));
224 }
225
226
227 void ARMTargetMachine::anchor() { }
228
229 ARMTargetMachine::ARMTargetMachine(const Target &T, StringRef TT, StringRef CPU,
230                                    StringRef FS, const TargetOptions &Options,
231                                    Reloc::Model RM, CodeModel::Model CM,
232                                    CodeGenOpt::Level OL, bool isLittle)
233     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
234   initAsmInfo();
235   if (!Subtarget.hasARMOps())
236     report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
237                        "support ARM mode execution!");
238 }
239
240 void ARMLETargetMachine::anchor() { }
241
242 ARMLETargetMachine::ARMLETargetMachine(const Target &T, StringRef TT,
243                                        StringRef CPU, StringRef FS,
244                                        const TargetOptions &Options,
245                                        Reloc::Model RM, CodeModel::Model CM,
246                                        CodeGenOpt::Level OL)
247     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
248
249 void ARMBETargetMachine::anchor() { }
250
251 ARMBETargetMachine::ARMBETargetMachine(const Target &T, StringRef TT,
252                                        StringRef CPU, StringRef FS,
253                                        const TargetOptions &Options,
254                                        Reloc::Model RM, CodeModel::Model CM,
255                                        CodeGenOpt::Level OL)
256     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
257
258 void ThumbTargetMachine::anchor() { }
259
260 ThumbTargetMachine::ThumbTargetMachine(const Target &T, StringRef TT,
261                                        StringRef CPU, StringRef FS,
262                                        const TargetOptions &Options,
263                                        Reloc::Model RM, CodeModel::Model CM,
264                                        CodeGenOpt::Level OL, bool isLittle)
265     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL,
266                            isLittle) {
267   initAsmInfo();
268 }
269
270 void ThumbLETargetMachine::anchor() { }
271
272 ThumbLETargetMachine::ThumbLETargetMachine(const Target &T, StringRef TT,
273                                            StringRef CPU, StringRef FS,
274                                            const TargetOptions &Options,
275                                            Reloc::Model RM, CodeModel::Model CM,
276                                            CodeGenOpt::Level OL)
277     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
278
279 void ThumbBETargetMachine::anchor() { }
280
281 ThumbBETargetMachine::ThumbBETargetMachine(const Target &T, StringRef TT,
282                                            StringRef CPU, StringRef FS,
283                                            const TargetOptions &Options,
284                                            Reloc::Model RM, CodeModel::Model CM,
285                                            CodeGenOpt::Level OL)
286     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
287
288 namespace {
289 /// ARM Code Generator Pass Configuration Options.
290 class ARMPassConfig : public TargetPassConfig {
291 public:
292   ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
293     : TargetPassConfig(TM, PM) {}
294
295   ARMBaseTargetMachine &getARMTargetMachine() const {
296     return getTM<ARMBaseTargetMachine>();
297   }
298
299   const ARMSubtarget &getARMSubtarget() const {
300     return *getARMTargetMachine().getSubtargetImpl();
301   }
302
303   void addIRPasses() override;
304   bool addPreISel() override;
305   bool addInstSelector() override;
306   void addPreRegAlloc() override;
307   void addPreSched2() override;
308   void addPreEmitPass() override;
309 };
310 } // namespace
311
312 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
313   return new ARMPassConfig(this, PM);
314 }
315
316 void ARMPassConfig::addIRPasses() {
317   if (TM->Options.ThreadModel == ThreadModel::Single)
318     addPass(createLowerAtomicPass());
319   else
320     addPass(createAtomicExpandPass(TM));
321
322   // Cmpxchg instructions are often used with a subsequent comparison to
323   // determine whether it succeeded. We can exploit existing control-flow in
324   // ldrex/strex loops to simplify this, but it needs tidying up.
325   const ARMSubtarget *Subtarget = &getARMSubtarget();
326   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only())
327     if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
328       addPass(createCFGSimplificationPass());
329
330   TargetPassConfig::addIRPasses();
331 }
332
333 bool ARMPassConfig::addPreISel() {
334   if (TM->getOptLevel() != CodeGenOpt::None)
335     addPass(createGlobalMergePass(TM));
336
337   return false;
338 }
339
340 bool ARMPassConfig::addInstSelector() {
341   addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
342
343   const ARMSubtarget *Subtarget = &getARMSubtarget();
344   if (Subtarget->isTargetELF() && !Subtarget->isThumb1Only() &&
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 && getARMSubtarget().isCortexA9())
354     addPass(createMLxExpansionPass());
355   // Since the A15SDOptimizer pass can insert VDUP instructions, it can only be
356   // enabled when NEON is available.
357   if (getOptLevel() != CodeGenOpt::None && getARMSubtarget().isCortexA15() &&
358     getARMSubtarget().hasNEON() && !DisableA15SDOptimization) {
359     addPass(createA15SDOptimizerPass());
360   }
361 }
362
363 void ARMPassConfig::addPreSched2() {
364   if (getOptLevel() != CodeGenOpt::None) {
365     addPass(createARMLoadStoreOptimizationPass());
366
367     if (getARMSubtarget().hasNEON())
368       addPass(createExecutionDependencyFixPass(&ARM::DPRRegClass));
369   }
370
371   // Expand some pseudo instructions into multiple instructions to allow
372   // proper scheduling.
373   addPass(createARMExpandPseudoPass());
374
375   if (getOptLevel() != CodeGenOpt::None) {
376     if (!getARMSubtarget().isThumb1Only()) {
377       // in v8, IfConversion depends on Thumb instruction widths
378       if (getARMSubtarget().restrictIT() &&
379           !getARMSubtarget().prefers32BitThumb())
380         addPass(createThumb2SizeReductionPass());
381       addPass(&IfConverterID);
382     }
383   }
384   if (getARMSubtarget().isThumb2())
385     addPass(createThumb2ITBlockPass());
386 }
387
388 void ARMPassConfig::addPreEmitPass() {
389   if (getARMSubtarget().isThumb2()) {
390     if (!getARMSubtarget().prefers32BitThumb())
391       addPass(createThumb2SizeReductionPass());
392
393     // Constant island pass work on unbundled instructions.
394     addPass(&UnpackMachineBundlesID);
395   }
396
397   addPass(createARMOptimizeBarriersPass());
398   addPass(createARMConstantIslandPass());
399 }