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