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