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 "ARMTargetMachine.h"
14 #include "ARM.h"
15 #include "ARMCallLowering.h"
16 #include "ARMFrameLowering.h"
17 #include "ARMInstructionSelector.h"
18 #include "ARMLegalizerInfo.h"
19 #include "ARMRegisterBankInfo.h"
20 #include "ARMTargetObjectFile.h"
21 #include "ARMTargetTransformInfo.h"
22 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
24 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
25 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/TargetParser.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
37 using namespace llvm;
38 
39 static cl::opt<bool>
40 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
41                    cl::desc("Inhibit optimization of S->D register accesses on A15"),
42                    cl::init(false));
43 
44 static cl::opt<bool>
45 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
46                  cl::desc("Run SimplifyCFG after expanding atomic operations"
47                           " to make use of cmpxchg flow-based information"),
48                  cl::init(true));
49 
50 static cl::opt<bool>
51 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
52                       cl::desc("Enable ARM load/store optimization pass"),
53                       cl::init(true));
54 
55 // FIXME: Unify control over GlobalMerge.
56 static cl::opt<cl::boolOrDefault>
57 EnableGlobalMerge("arm-global-merge", cl::Hidden,
58                   cl::desc("Enable the global merge pass"));
59 
60 extern "C" void LLVMInitializeARMTarget() {
61   // Register the target.
62   RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
63   RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
64   RegisterTargetMachine<ThumbLETargetMachine> A(getTheThumbLETarget());
65   RegisterTargetMachine<ThumbBETargetMachine> B(getTheThumbBETarget());
66 
67   PassRegistry &Registry = *PassRegistry::getPassRegistry();
68   initializeGlobalISel(Registry);
69   initializeARMLoadStoreOptPass(Registry);
70   initializeARMPreAllocLoadStoreOptPass(Registry);
71 }
72 
73 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
74   if (TT.isOSBinFormatMachO())
75     return make_unique<TargetLoweringObjectFileMachO>();
76   if (TT.isOSWindows())
77     return make_unique<TargetLoweringObjectFileCOFF>();
78   return make_unique<ARMElfTargetObjectFile>();
79 }
80 
81 static ARMBaseTargetMachine::ARMABI
82 computeTargetABI(const Triple &TT, StringRef CPU,
83                  const TargetOptions &Options) {
84   if (Options.MCOptions.getABIName() == "aapcs16")
85     return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
86   else if (Options.MCOptions.getABIName().startswith("aapcs"))
87     return ARMBaseTargetMachine::ARM_ABI_AAPCS;
88   else if (Options.MCOptions.getABIName().startswith("apcs"))
89     return ARMBaseTargetMachine::ARM_ABI_APCS;
90 
91   assert(Options.MCOptions.getABIName().empty() &&
92          "Unknown target-abi option!");
93 
94   ARMBaseTargetMachine::ARMABI TargetABI =
95       ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
96 
97   unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
98   StringRef ArchName = llvm::ARM::getArchName(ArchKind);
99   // FIXME: This is duplicated code from the front end and should be unified.
100   if (TT.isOSBinFormatMachO()) {
101     if (TT.getEnvironment() == llvm::Triple::EABI ||
102         (TT.getOS() == llvm::Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
103         llvm::ARM::parseArchProfile(ArchName) == llvm::ARM::PK_M) {
104       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
105     } else if (TT.isWatchABI()) {
106       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
107     } else {
108       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
109     }
110   } else if (TT.isOSWindows()) {
111     // FIXME: this is invalid for WindowsCE
112     TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
113   } else {
114     // Select the default based on the platform.
115     switch (TT.getEnvironment()) {
116     case llvm::Triple::Android:
117     case llvm::Triple::GNUEABI:
118     case llvm::Triple::GNUEABIHF:
119     case llvm::Triple::MuslEABI:
120     case llvm::Triple::MuslEABIHF:
121     case llvm::Triple::EABIHF:
122     case llvm::Triple::EABI:
123       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
124       break;
125     case llvm::Triple::GNU:
126       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
127       break;
128     default:
129       if (TT.isOSNetBSD())
130         TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
131       else
132         TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
133       break;
134     }
135   }
136 
137   return TargetABI;
138 }
139 
140 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
141                                      const TargetOptions &Options,
142                                      bool isLittle) {
143   auto ABI = computeTargetABI(TT, CPU, Options);
144   std::string Ret = "";
145 
146   if (isLittle)
147     // Little endian.
148     Ret += "e";
149   else
150     // Big endian.
151     Ret += "E";
152 
153   Ret += DataLayout::getManglingComponent(TT);
154 
155   // Pointers are 32 bits and aligned to 32 bits.
156   Ret += "-p:32:32";
157 
158   // ABIs other than APCS have 64 bit integers with natural alignment.
159   if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
160     Ret += "-i64:64";
161 
162   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
163   // bits, others to 64 bits. We always try to align to 64 bits.
164   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
165     Ret += "-f64:32:64";
166 
167   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
168   // to 64. We always ty to give them natural alignment.
169   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
170     Ret += "-v64:32:64-v128:32:128";
171   else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
172     Ret += "-v128:64:128";
173 
174   // Try to align aggregates to 32 bits (the default is 64 bits, which has no
175   // particular hardware support on 32-bit ARM).
176   Ret += "-a:0:32";
177 
178   // Integer registers are 32 bits.
179   Ret += "-n32";
180 
181   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
182   // aligned everywhere else.
183   if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
184     Ret += "-S128";
185   else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
186     Ret += "-S64";
187   else
188     Ret += "-S32";
189 
190   return Ret;
191 }
192 
193 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
194                                            Optional<Reloc::Model> RM) {
195   if (!RM.hasValue())
196     // Default relocation model on Darwin is PIC.
197     return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
198 
199   if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
200     assert(TT.isOSBinFormatELF() &&
201            "ROPI/RWPI currently only supported for ELF");
202 
203   // DynamicNoPIC is only used on darwin.
204   if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
205     return Reloc::Static;
206 
207   return *RM;
208 }
209 
210 /// Create an ARM architecture model.
211 ///
212 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
213                                            StringRef CPU, StringRef FS,
214                                            const TargetOptions &Options,
215                                            Optional<Reloc::Model> RM,
216                                            CodeModel::Model CM,
217                                            CodeGenOpt::Level OL, bool isLittle)
218     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
219                         CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
220                         OL),
221       TargetABI(computeTargetABI(TT, CPU, Options)),
222       TLOF(createTLOF(getTargetTriple())),
223       Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
224 
225   // Default to triple-appropriate float ABI
226   if (Options.FloatABIType == FloatABI::Default)
227     this->Options.FloatABIType =
228         Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
229 
230   // Default to triple-appropriate EABI
231   if (Options.EABIVersion == EABI::Default ||
232       Options.EABIVersion == EABI::Unknown) {
233     // musl is compatible with glibc with regard to EABI version
234     if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
235       this->Options.EABIVersion = EABI::GNU;
236     else
237       this->Options.EABIVersion = EABI::EABI5;
238   }
239 }
240 
241 ARMBaseTargetMachine::~ARMBaseTargetMachine() {}
242 
243 #ifdef LLVM_BUILD_GLOBAL_ISEL
244 namespace {
245 struct ARMGISelActualAccessor : public GISelAccessor {
246   std::unique_ptr<CallLowering> CallLoweringInfo;
247   std::unique_ptr<InstructionSelector> InstSelector;
248   std::unique_ptr<LegalizerInfo> Legalizer;
249   std::unique_ptr<RegisterBankInfo> RegBankInfo;
250   const CallLowering *getCallLowering() const override {
251     return CallLoweringInfo.get();
252   }
253   const InstructionSelector *getInstructionSelector() const override {
254     return InstSelector.get();
255   }
256   const class LegalizerInfo *getLegalizerInfo() const override {
257     return Legalizer.get();
258   }
259   const RegisterBankInfo *getRegBankInfo() const override {
260     return RegBankInfo.get();
261   }
262 };
263 } // End anonymous namespace.
264 #endif
265 
266 const ARMSubtarget *
267 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
268   Attribute CPUAttr = F.getFnAttribute("target-cpu");
269   Attribute FSAttr = F.getFnAttribute("target-features");
270 
271   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
272                         ? CPUAttr.getValueAsString().str()
273                         : TargetCPU;
274   std::string FS = !FSAttr.hasAttribute(Attribute::None)
275                        ? FSAttr.getValueAsString().str()
276                        : TargetFS;
277 
278   // FIXME: This is related to the code below to reset the target options,
279   // we need to know whether or not the soft float flag is set on the
280   // function before we can generate a subtarget. We also need to use
281   // it as a key for the subtarget since that can be the only difference
282   // between two functions.
283   bool SoftFloat =
284       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
285   // If the soft float attribute is set on the function turn on the soft float
286   // subtarget feature.
287   if (SoftFloat)
288     FS += FS.empty() ? "+soft-float" : ",+soft-float";
289 
290   auto &I = SubtargetMap[CPU + FS];
291   if (!I) {
292     // This needs to be done before we create a new subtarget since any
293     // creation will depend on the TM and the code generation flags on the
294     // function that reside in TargetOptions.
295     resetTargetOptions(F);
296     I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
297 
298 #ifndef LLVM_BUILD_GLOBAL_ISEL
299     GISelAccessor *GISel = new GISelAccessor();
300 #else
301     ARMGISelActualAccessor *GISel = new ARMGISelActualAccessor();
302     GISel->CallLoweringInfo.reset(new ARMCallLowering(*I->getTargetLowering()));
303     GISel->Legalizer.reset(new ARMLegalizerInfo());
304 
305     auto *RBI = new ARMRegisterBankInfo(*I->getRegisterInfo());
306 
307     // FIXME: At this point, we can't rely on Subtarget having RBI.
308     // It's awkward to mix passing RBI and the Subtarget; should we pass
309     // TII/TRI as well?
310     GISel->InstSelector.reset(new ARMInstructionSelector(*I, *RBI));
311 
312     GISel->RegBankInfo.reset(RBI);
313 #endif
314     I->setGISelAccessor(*GISel);
315   }
316   return I.get();
317 }
318 
319 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
320   return TargetIRAnalysis([this](const Function &F) {
321     return TargetTransformInfo(ARMTTIImpl(this, F));
322   });
323 }
324 
325 void ARMTargetMachine::anchor() {}
326 
327 ARMTargetMachine::ARMTargetMachine(const Target &T, const Triple &TT,
328                                    StringRef CPU, StringRef FS,
329                                    const TargetOptions &Options,
330                                    Optional<Reloc::Model> RM,
331                                    CodeModel::Model CM, CodeGenOpt::Level OL,
332                                    bool isLittle)
333     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
334   initAsmInfo();
335   if (!Subtarget.hasARMOps())
336     report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
337                        "support ARM mode execution!");
338 }
339 
340 void ARMLETargetMachine::anchor() {}
341 
342 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
343                                        StringRef CPU, StringRef FS,
344                                        const TargetOptions &Options,
345                                        Optional<Reloc::Model> RM,
346                                        CodeModel::Model CM,
347                                        CodeGenOpt::Level OL)
348     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
349 
350 void ARMBETargetMachine::anchor() {}
351 
352 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
353                                        StringRef CPU, StringRef FS,
354                                        const TargetOptions &Options,
355                                        Optional<Reloc::Model> RM,
356                                        CodeModel::Model CM,
357                                        CodeGenOpt::Level OL)
358     : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
359 
360 void ThumbTargetMachine::anchor() {}
361 
362 ThumbTargetMachine::ThumbTargetMachine(const Target &T, const Triple &TT,
363                                        StringRef CPU, StringRef FS,
364                                        const TargetOptions &Options,
365                                        Optional<Reloc::Model> RM,
366                                        CodeModel::Model CM,
367                                        CodeGenOpt::Level OL, bool isLittle)
368     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
369   initAsmInfo();
370 }
371 
372 void ThumbLETargetMachine::anchor() {}
373 
374 ThumbLETargetMachine::ThumbLETargetMachine(const Target &T, const Triple &TT,
375                                            StringRef CPU, StringRef FS,
376                                            const TargetOptions &Options,
377                                            Optional<Reloc::Model> RM,
378                                            CodeModel::Model CM,
379                                            CodeGenOpt::Level OL)
380     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
381 
382 void ThumbBETargetMachine::anchor() {}
383 
384 ThumbBETargetMachine::ThumbBETargetMachine(const Target &T, const Triple &TT,
385                                            StringRef CPU, StringRef FS,
386                                            const TargetOptions &Options,
387                                            Optional<Reloc::Model> RM,
388                                            CodeModel::Model CM,
389                                            CodeGenOpt::Level OL)
390     : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
391 
392 namespace {
393 /// ARM Code Generator Pass Configuration Options.
394 class ARMPassConfig : public TargetPassConfig {
395 public:
396   ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
397     : TargetPassConfig(TM, PM) {}
398 
399   ARMBaseTargetMachine &getARMTargetMachine() const {
400     return getTM<ARMBaseTargetMachine>();
401   }
402 
403   void addIRPasses() override;
404   bool addPreISel() override;
405   bool addInstSelector() override;
406 #ifdef LLVM_BUILD_GLOBAL_ISEL
407   bool addIRTranslator() override;
408   bool addLegalizeMachineIR() override;
409   bool addRegBankSelect() override;
410   bool addGlobalInstructionSelect() override;
411 #endif
412   void addPreRegAlloc() override;
413   void addPreSched2() override;
414   void addPreEmitPass() override;
415 };
416 } // namespace
417 
418 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
419   return new ARMPassConfig(this, PM);
420 }
421 
422 void ARMPassConfig::addIRPasses() {
423   if (TM->Options.ThreadModel == ThreadModel::Single)
424     addPass(createLowerAtomicPass());
425   else
426     addPass(createAtomicExpandPass(TM));
427 
428   // Cmpxchg instructions are often used with a subsequent comparison to
429   // determine whether it succeeded. We can exploit existing control-flow in
430   // ldrex/strex loops to simplify this, but it needs tidying up.
431   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
432     addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
433       const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
434       return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
435     }));
436 
437   TargetPassConfig::addIRPasses();
438 
439   // Match interleaved memory accesses to ldN/stN intrinsics.
440   if (TM->getOptLevel() != CodeGenOpt::None)
441     addPass(createInterleavedAccessPass(TM));
442 }
443 
444 bool ARMPassConfig::addPreISel() {
445   if ((TM->getOptLevel() != CodeGenOpt::None &&
446        EnableGlobalMerge == cl::BOU_UNSET) ||
447       EnableGlobalMerge == cl::BOU_TRUE) {
448     // FIXME: This is using the thumb1 only constant value for
449     // maximal global offset for merging globals. We may want
450     // to look into using the old value for non-thumb1 code of
451     // 4095 based on the TargetMachine, but this starts to become
452     // tricky when doing code gen per function.
453     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
454                                (EnableGlobalMerge == cl::BOU_UNSET);
455     // Merging of extern globals is enabled by default on non-Mach-O as we
456     // expect it to be generally either beneficial or harmless. On Mach-O it
457     // is disabled as we emit the .subsections_via_symbols directive which
458     // means that merging extern globals is not safe.
459     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
460     addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
461                                   MergeExternalByDefault));
462   }
463 
464   return false;
465 }
466 
467 bool ARMPassConfig::addInstSelector() {
468   addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
469   return false;
470 }
471 
472 #ifdef LLVM_BUILD_GLOBAL_ISEL
473 bool ARMPassConfig::addIRTranslator() {
474   addPass(new IRTranslator());
475   return false;
476 }
477 
478 bool ARMPassConfig::addLegalizeMachineIR() {
479   addPass(new Legalizer());
480   return false;
481 }
482 
483 bool ARMPassConfig::addRegBankSelect() {
484   addPass(new RegBankSelect());
485   return false;
486 }
487 
488 bool ARMPassConfig::addGlobalInstructionSelect() {
489   addPass(new InstructionSelect());
490   return false;
491 }
492 #endif
493 
494 void ARMPassConfig::addPreRegAlloc() {
495   if (getOptLevel() != CodeGenOpt::None) {
496     addPass(createMLxExpansionPass());
497 
498     if (EnableARMLoadStoreOpt)
499       addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
500 
501     if (!DisableA15SDOptimization)
502       addPass(createA15SDOptimizerPass());
503   }
504 }
505 
506 void ARMPassConfig::addPreSched2() {
507   if (getOptLevel() != CodeGenOpt::None) {
508     if (EnableARMLoadStoreOpt)
509       addPass(createARMLoadStoreOptimizationPass());
510 
511     addPass(createExecutionDependencyFixPass(&ARM::DPRRegClass));
512   }
513 
514   // Expand some pseudo instructions into multiple instructions to allow
515   // proper scheduling.
516   addPass(createARMExpandPseudoPass());
517 
518   if (getOptLevel() != CodeGenOpt::None) {
519     // in v8, IfConversion depends on Thumb instruction widths
520     addPass(createThumb2SizeReductionPass([this](const Function &F) {
521       return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
522     }));
523 
524     addPass(createIfConverter([](const MachineFunction &MF) {
525       return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
526     }));
527   }
528   addPass(createThumb2ITBlockPass());
529 }
530 
531 void ARMPassConfig::addPreEmitPass() {
532   addPass(createThumb2SizeReductionPass());
533 
534   // Constant island pass work on unbundled instructions.
535   addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
536     return MF.getSubtarget<ARMSubtarget>().isThumb2();
537   }));
538 
539   // Don't optimize barriers at -O0.
540   if (getOptLevel() != CodeGenOpt::None)
541     addPass(createARMOptimizeBarriersPass());
542 
543   addPass(createARMConstantIslandPass());
544 }
545