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