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