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 "ARMLatencyMutations.h"
15#include "ARMMachineFunctionInfo.h"
16#include "ARMMacroFusion.h"
17#include "ARMSubtarget.h"
18#include "ARMTargetObjectFile.h"
19#include "ARMTargetTransformInfo.h"
20#include "MCTargetDesc/ARMMCTargetDesc.h"
21#include "TargetInfo/ARMTargetInfo.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/CodeGen/ExecutionDomainFix.h"
25#include "llvm/CodeGen/GlobalISel/CSEInfo.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/Legalizer.h"
30#include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
31#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
32#include "llvm/CodeGen/MIRParser/MIParser.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/CallingConv.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DiagnosticInfo.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/InstIterator.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Module.h"
45#include "llvm/MC/TargetRegistry.h"
46#include "llvm/Pass.h"
47#include "llvm/Passes/PassBuilder.h"
48#include "llvm/Support/CodeGen.h"
49#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Target/TargetLoweringObjectFile.h"
53#include "llvm/Target/TargetOptions.h"
54#include "llvm/TargetParser/ARMTargetParser.h"
55#include "llvm/TargetParser/TargetParser.h"
56#include "llvm/TargetParser/Triple.h"
57#include "llvm/Transforms/CFGuard.h"
58#include "llvm/Transforms/IPO.h"
59#include "llvm/Transforms/Scalar.h"
60#include <cassert>
61#include <memory>
62#include <optional>
63#include <string>
64
65using namespace llvm;
66
67static cl::opt<bool>
68DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
69 cl::desc("Inhibit optimization of S->D register accesses on A15"),
70 cl::init(Val: false));
71
72static cl::opt<bool>
73EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
74 cl::desc("Run SimplifyCFG after expanding atomic operations"
75 " to make use of cmpxchg flow-based information"),
76 cl::init(Val: true));
77
78static cl::opt<bool>
79EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
80 cl::desc("Enable ARM load/store optimization pass"),
81 cl::init(Val: true));
82
83// FIXME: Unify control over GlobalMerge.
84static cl::opt<cl::boolOrDefault>
85EnableGlobalMerge("arm-global-merge", cl::Hidden,
86 cl::desc("Enable the global merge pass"));
87
88namespace llvm {
89 void initializeARMExecutionDomainFixPass(PassRegistry&);
90}
91
92extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMTarget() {
93 // Register the target.
94 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
95 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget());
96 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
97 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget());
98
99 PassRegistry &Registry = *PassRegistry::getPassRegistry();
100 initializeGlobalISel(Registry);
101 initializeARMAsmPrinterPass(Registry);
102 initializeARMLoadStoreOptLegacyPass(Registry);
103 initializeARMPreAllocLoadStoreOptLegacyPass(Registry);
104 initializeARMParallelDSPPass(Registry);
105 initializeARMBranchTargetsPass(Registry);
106 initializeARMConstantIslandsPass(Registry);
107 initializeARMExecutionDomainFixPass(Registry);
108 initializeARMExpandPseudoPass(Registry);
109 initializeThumb2SizeReducePass(Registry);
110 initializeMVEVPTBlockPass(Registry);
111 initializeMVETPAndVPTOptimisationsPass(Registry);
112 initializeMVETailPredicationPass(Registry);
113 initializeARMLowOverheadLoopsPass(Registry);
114 initializeARMBlockPlacementPass(Registry);
115 initializeMVEGatherScatterLoweringPass(Registry);
116 initializeARMSLSHardeningPass(Registry);
117 initializeMVELaneInterleavingPass(Registry);
118 initializeARMFixCortexA57AES1742098Pass(Registry);
119 initializeARMDAGToDAGISelLegacyPass(Registry);
120 initializeMachineKCFILegacyPass(Registry);
121}
122
123static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
124 if (TT.isOSBinFormatMachO())
125 return std::make_unique<TargetLoweringObjectFileMachO>();
126 if (TT.isOSWindows())
127 return std::make_unique<TargetLoweringObjectFileCOFF>();
128 return std::make_unique<ARMElfTargetObjectFile>();
129}
130
131static Reloc::Model getEffectiveRelocModel(const Triple &TT,
132 std::optional<Reloc::Model> RM) {
133 if (!RM)
134 // Default relocation model on Darwin is PIC.
135 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
136
137 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
138 assert(TT.isOSBinFormatELF() &&
139 "ROPI/RWPI currently only supported for ELF");
140
141 // DynamicNoPIC is only used on darwin.
142 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
143 return Reloc::Static;
144
145 return *RM;
146}
147
148/// Create an ARM architecture model.
149///
150ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
151 StringRef CPU, StringRef FS,
152 const TargetOptions &Options,
153 std::optional<Reloc::Model> RM,
154 std::optional<CodeModel::Model> CM,
155 CodeGenOptLevel OL)
156 : CodeGenTargetMachineImpl(
157 T, TT.computeDataLayout(ABIName: Options.MCOptions.ABIName), TT, CPU, FS,
158 Options, getEffectiveRelocModel(TT, RM),
159 getEffectiveCodeModel(CM, Default: CodeModel::Small), OL),
160 TargetABI(ARM::computeTargetABI(TT, ABIName: Options.MCOptions.ABIName)),
161 TLOF(createTLOF(TT: getTargetTriple())), isLittle(TT.isLittleEndian()) {
162
163 // Default to triple-appropriate EABI
164 if (Options.EABIVersion == EABI::Default ||
165 Options.EABIVersion == EABI::Unknown) {
166 // musl is compatible with glibc with regard to EABI version
167 if ((TargetTriple.getEnvironment() == Triple::GNUEABI ||
168 TargetTriple.getEnvironment() == Triple::GNUEABIT64 ||
169 TargetTriple.getEnvironment() == Triple::GNUEABIHF ||
170 TargetTriple.getEnvironment() == Triple::GNUEABIHFT64 ||
171 TargetTriple.getEnvironment() == Triple::MuslEABI ||
172 TargetTriple.getEnvironment() == Triple::MuslEABIHF ||
173 TargetTriple.getEnvironment() == Triple::OpenHOS) &&
174 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin()))
175 this->Options.EABIVersion = EABI::GNU;
176 else
177 this->Options.EABIVersion = EABI::EABI5;
178 }
179
180 if (TT.isOSBinFormatMachO()) {
181 this->Options.TrapUnreachable = true;
182 this->Options.NoTrapAfterNoreturn = true;
183 }
184
185 // ARM supports the debug entry values.
186 setSupportsDebugEntryValues(true);
187
188 initAsmInfo();
189
190 // ARM supports the MachineOutliner.
191 setMachineOutliner(true);
192 setSupportsDefaultOutlining(true);
193}
194
195ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
196
197MachineFunctionInfo *ARMBaseTargetMachine::createMachineFunctionInfo(
198 BumpPtrAllocator &Allocator, const Function &F,
199 const TargetSubtargetInfo *STI) const {
200 const auto *ARMSTI = static_cast<const ARMSubtarget *>(STI);
201 bool FPRegsUnavailable = !ARMSTI->hasFPRegs() || ARMSTI->isThumb1Only();
202 if (FPRegsUnavailable) {
203 const StringRef FPRegsUnavailableMsg =
204 ", but floating-point registers are unavailable";
205 const ARMTargetLowering *TLI = ARMSTI->getTargetLowering();
206
207 if (TLI->getEffectiveCallingConv(CC: F.getCallingConv(), isVarArg: F.isVarArg()) ==
208 CallingConv::ARM_AAPCS_VFP) {
209 F.getContext().diagnose(DI: DiagnosticInfoUnsupported(
210 F, Twine("calling convention is hard-float") + FPRegsUnavailableMsg,
211 DiagnosticLocation(F.getSubprogram())));
212 } else {
213 for (const Instruction &I : instructions(F)) {
214 const auto *CB = dyn_cast<CallBase>(Val: &I);
215 if (!CB || CB->isInlineAsm() ||
216 (CB->getCalledFunction() && CB->getCalledFunction()->isIntrinsic()))
217 continue;
218 if (TLI->getEffectiveCallingConv(CC: CB->getCallingConv(),
219 isVarArg: CB->getFunctionType()->isVarArg()) ==
220 CallingConv::ARM_AAPCS_VFP) {
221 const Function *Callee = CB->getCalledFunction();
222 F.getContext().diagnose(DI: DiagnosticInfoUnsupported(
223 F,
224 (Callee ? Twine("call to '") + Callee->getName() + "'"
225 : Twine("indirect call")) +
226 " expects a hard-float calling convention" +
227 FPRegsUnavailableMsg,
228 CB->getDebugLoc()));
229 }
230 }
231 }
232 }
233 return ARMFunctionInfo::create<ARMFunctionInfo>(Allocator, F, STI: ARMSTI);
234}
235
236FloatABI::ABIType ARMBaseTargetMachine::getFloatABI(const Module &M) const {
237 // An explicit "float-abi" module flag always wins, even for AAPCS16.
238 if (auto *Val = dyn_cast_or_null<MDString>(Val: M.getModuleFlag(Key: "float-abi")))
239 return *FloatABI::parseABIType(S: Val->getString());
240
241 // With no explicit ABI, an explicit -target-abi=aapcs16 forces hard float
242 // even on triples whose default float ABI is soft (the triple default only
243 // detects AAPCS16 when it is the triple's own default ABI).
244 if (TargetABI == ARM::ARM_ABI_AAPCS16)
245 return FloatABI::Hard;
246 // Otherwise fall back to the ABI implied by the target triple.
247 return M.getTargetTriple().getDefaultFloatABI();
248}
249
250ARM::ARMABI ARMBaseTargetMachine::getEffectiveABI(const Module &M) const {
251 // Consistency of "target-abi" and -target-abi is validated elsewhere.
252 if (const auto *MD = cast_or_null<MDString>(Val: M.getModuleFlag(Key: "target-abi")))
253 return ARM::computeTargetABI(TT: TargetTriple, ABIName: MD->getString());
254 return TargetABI;
255}
256
257const ARMSubtarget *
258ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
259 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
260 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
261
262 std::string CPU =
263 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
264 std::string FS =
265 FSAttr.isValid() ? FSAttr.getValueAsString().str() : 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 = F.getFnAttribute(Kind: "use-soft-float").getValueAsBool();
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 DenormalMode DM = F.getDenormalFPEnv().DefaultMode;
285 if (DM != DenormalMode::getIEEE())
286 Key += "denormal-fp-math=" + DM.str();
287
288 FloatABI::ABIType FloatABI = getFloatABI(M: *F.getParent());
289 // It is legal to have FloatABI::Hard with +soft-float for targets with SIMD
290 // registers, but no floating-point hardware (mve+nofp)
291 Key += FloatABI == FloatABI::Hard ? "+hard-float-abi" : "+soft-float-abi";
292
293 ARM::ARMABI ABI = getEffectiveABI(M: *F.getParent());
294 Key += "+abi=" + std::to_string(val: (int)ABI);
295
296 auto &I = SubtargetMap[Key];
297 if (!I) {
298 I = std::make_unique<ARMSubtarget>(args: TargetTriple, args&: CPU, args&: FS, args: *this, args: isLittle,
299 args&: FloatABI, args&: ABI, args: F.hasMinSize(), args&: DM);
300
301 if (!I->isThumb() && !I->hasARMOps())
302 F.getContext().emitError(ErrorStr: "Function '" + F.getName() + "' uses ARM "
303 "instructions, but the target does not support ARM mode execution.");
304 }
305
306 return I.get();
307}
308
309TargetTransformInfo
310ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) const {
311 return TargetTransformInfo(std::make_unique<ARMTTIImpl>(args: this, args: F));
312}
313
314ScheduleDAGInstrs *
315ARMBaseTargetMachine::createMachineScheduler(MachineSchedContext *C) const {
316 ScheduleDAGMILive *DAG = createSchedLive(C);
317 // add DAG Mutations here.
318 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
319 if (ST.hasFusion())
320 DAG->addMutation(Mutation: createARMMacroFusionDAGMutation());
321 return DAG;
322}
323
324ScheduleDAGInstrs *
325ARMBaseTargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
326 ScheduleDAGMI *DAG = createSchedPostRA(C);
327 // add DAG Mutations here.
328 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
329 if (ST.hasFusion())
330 DAG->addMutation(Mutation: createARMMacroFusionDAGMutation());
331 if (auto Mutation = createARMLatencyMutations(ST, AA: C->AA))
332 DAG->addMutation(Mutation: std::move(Mutation));
333 return DAG;
334}
335
336ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
337 StringRef CPU, StringRef FS,
338 const TargetOptions &Options,
339 std::optional<Reloc::Model> RM,
340 std::optional<CodeModel::Model> CM,
341 CodeGenOptLevel OL, bool JIT)
342 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
343
344ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
345 StringRef CPU, StringRef FS,
346 const TargetOptions &Options,
347 std::optional<Reloc::Model> RM,
348 std::optional<CodeModel::Model> CM,
349 CodeGenOptLevel OL, bool JIT)
350 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
351
352namespace {
353
354/// ARM Code Generator Pass Configuration Options.
355class ARMPassConfig : public TargetPassConfig {
356public:
357 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
358 : TargetPassConfig(TM, PM) {}
359
360 ARMBaseTargetMachine &getARMTargetMachine() const {
361 return getTM<ARMBaseTargetMachine>();
362 }
363
364 void addIRPasses() override;
365 void addCodeGenPrepare() override;
366 bool addPreISel() override;
367 bool addInstSelector() override;
368 bool addIRTranslator() override;
369 bool addLegalizeMachineIR() override;
370 bool addRegBankSelect() override;
371 bool addGlobalInstructionSelect() override;
372 void addPreRegAlloc() override;
373 void addPreSched2() override;
374 void addPreEmitPass() override;
375 void addPreEmitPass2() override;
376
377 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
378};
379
380class ARMExecutionDomainFix : public ExecutionDomainFix {
381public:
382 static char ID;
383 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {}
384 StringRef getPassName() const override {
385 return "ARM Execution Domain Fix";
386 }
387};
388char ARMExecutionDomainFix::ID;
389
390} // end anonymous namespace
391
392INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix",
393 "ARM Execution Domain Fix", false, false)
394INITIALIZE_PASS_DEPENDENCY(ReachingDefInfoWrapperPass)
395INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix",
396 "ARM Execution Domain Fix", false, false)
397
398void ARMBaseTargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
399#define GET_PASS_REGISTRY "ARMPassRegistry.def"
400#include "llvm/Passes/TargetPassRegistry.inc"
401}
402
403TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
404 return new ARMPassConfig(*this, PM);
405}
406
407std::unique_ptr<CSEConfigBase> ARMPassConfig::getCSEConfig() const {
408 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
409}
410
411void ARMPassConfig::addIRPasses() {
412 if (TM->Options.ThreadModel == ThreadModel::Single)
413 addPass(P: createLowerAtomicPass());
414 else
415 addPass(P: createAtomicExpandLegacyPass());
416
417 // Cmpxchg instructions are often used with a subsequent comparison to
418 // determine whether it succeeded. We can exploit existing control-flow in
419 // ldrex/strex loops to simplify this, but it needs tidying up.
420 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAtomicTidy)
421 addPass(P: createCFGSimplificationPass(
422 Options: SimplifyCFGOptions().hoistCommonInsts(B: true).sinkCommonInsts(B: true),
423 Ftor: [this](const Function &F) {
424 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
425 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
426 }));
427
428 addPass(P: createMVEGatherScatterLoweringPass());
429 addPass(P: createMVELaneInterleavingPass());
430
431 TargetPassConfig::addIRPasses();
432
433 // Run the parallel DSP pass.
434 if (getOptLevel() == CodeGenOptLevel::Aggressive)
435 addPass(P: createARMParallelDSPPass());
436
437 // Match complex arithmetic patterns
438 if (TM->getOptLevel() >= CodeGenOptLevel::Default)
439 addPass(P: createComplexDeinterleavingPass(TM));
440
441 // Match interleaved memory accesses to ldN/stN intrinsics.
442 if (TM->getOptLevel() != CodeGenOptLevel::None)
443 addPass(P: createInterleavedAccessPass());
444
445 // Add Control Flow Guard checks.
446 if (TM->getTargetTriple().isOSWindows())
447 addPass(P: createCFGuardPass());
448
449 if (TM->Options.JMCInstrument)
450 addPass(P: createJMCInstrumenterPass());
451}
452
453void ARMPassConfig::addCodeGenPrepare() {
454 if (getOptLevel() != CodeGenOptLevel::None)
455 addPass(P: createTypePromotionLegacyPass());
456 TargetPassConfig::addCodeGenPrepare();
457}
458
459bool ARMPassConfig::addPreISel() {
460 if ((TM->getOptLevel() != CodeGenOptLevel::None &&
461 EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET) ||
462 EnableGlobalMerge == cl::boolOrDefault::BOU_TRUE) {
463 // FIXME: This is using the thumb1 only constant value for
464 // maximal global offset for merging globals. We may want
465 // to look into using the old value for non-thumb1 code of
466 // 4095 based on the TargetMachine, but this starts to become
467 // tricky when doing code gen per function.
468 bool OnlyOptimizeForSize =
469 (TM->getOptLevel() < CodeGenOptLevel::Aggressive) &&
470 (EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET);
471 // Merging of extern globals is enabled by default on non-Mach-O as we
472 // expect it to be generally either beneficial or harmless. On Mach-O it
473 // is disabled as we emit the .subsections_via_symbols directive which
474 // means that merging extern globals is not safe.
475 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
476 addPass(P: createGlobalMergePass(TM, MaximalOffset: 127, OnlyOptimizeForSize,
477 MergeExternalByDefault));
478 }
479
480 if (TM->getOptLevel() != CodeGenOptLevel::None) {
481 addPass(P: createHardwareLoopsLegacyPass());
482 addPass(P: createMVETailPredicationPass());
483 // FIXME: IR passes can delete address-taken basic blocks, deleting
484 // corresponding blockaddresses. ARMConstantPoolConstant holds references to
485 // address-taken basic blocks which can be invalidated if the function
486 // containing the blockaddress has already been codegen'd and the basic
487 // block is removed. Work around this by forcing all IR passes to run before
488 // any ISel takes place. We should have a more principled way of handling
489 // this. See D99707 for more details.
490 addPass(P: createBarrierNoopPass());
491 }
492
493 return false;
494}
495
496bool ARMPassConfig::addInstSelector() {
497 addPass(P: createARMISelDag(TM&: getARMTargetMachine(), OptLevel: getOptLevel()));
498 return false;
499}
500
501bool ARMPassConfig::addIRTranslator() {
502 addPass(P: new IRTranslatorLegacy(getOptLevel()));
503 return false;
504}
505
506bool ARMPassConfig::addLegalizeMachineIR() {
507 addPass(P: new LegalizerLegacy());
508 return false;
509}
510
511bool ARMPassConfig::addRegBankSelect() {
512 addPass(P: new RegBankSelectLegacy());
513 return false;
514}
515
516bool ARMPassConfig::addGlobalInstructionSelect() {
517 addPass(P: new InstructionSelectLegacy(getOptLevel()));
518 return false;
519}
520
521void ARMPassConfig::addPreRegAlloc() {
522 if (getOptLevel() != CodeGenOptLevel::None) {
523 if (getOptLevel() == CodeGenOptLevel::Aggressive)
524 addPass(PassID: &MachinePipelinerID);
525
526 addPass(P: createMVETPAndVPTOptimisationsPass());
527
528 addPass(P: createMLxExpansionPass());
529
530 if (EnableARMLoadStoreOpt)
531 addPass(P: createARMLoadStoreOptLegacyPass(/* pre-register alloc */ PreAlloc: true));
532
533 if (!DisableA15SDOptimization)
534 addPass(P: createA15SDOptimizerPass());
535 }
536}
537
538void ARMPassConfig::addPreSched2() {
539 if (getOptLevel() != CodeGenOptLevel::None) {
540 if (EnableARMLoadStoreOpt)
541 addPass(P: createARMLoadStoreOptLegacyPass());
542
543 addPass(P: new ARMExecutionDomainFix());
544 addPass(P: createBreakFalseDepsLegacyPass());
545 }
546
547 // Expand some pseudo instructions into multiple instructions to allow
548 // proper scheduling.
549 addPass(P: createARMExpandPseudoPass());
550
551 // Emit KCFI checks for indirect calls.
552 addPass(P: createKCFIPass());
553
554 if (getOptLevel() != CodeGenOptLevel::None) {
555 // When optimising for size, always run the Thumb2SizeReduction pass before
556 // IfConversion. Otherwise, check whether IT blocks are restricted
557 // (e.g. in v8, IfConversion depends on Thumb instruction widths)
558 addPass(P: createThumb2SizeReductionPass(Ftor: [this](const Function &F) {
559 return this->TM->getSubtarget<ARMSubtarget>(F).hasMinSize() ||
560 this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
561 }));
562
563 addPass(P: createIfConverter(Ftor: [](const MachineFunction &MF) {
564 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
565 }));
566 }
567 addPass(P: createThumb2ITBlockPass());
568
569 // Add both scheduling passes to give the subtarget an opportunity to pick
570 // between them.
571 if (getOptLevel() != CodeGenOptLevel::None) {
572 addPass(PassID: &PostMachineSchedulerID);
573 addPass(PassID: &PostRASchedulerID);
574 }
575
576 addPass(P: createMVEVPTBlockPass());
577 addPass(P: createARMIndirectThunks());
578 addPass(P: createARMSLSHardeningPass());
579}
580
581void ARMPassConfig::addPreEmitPass() {
582 addPass(P: createThumb2SizeReductionPass());
583
584 // Unpack bundles for:
585 // - Thumb2: Constant island pass requires unbundled instructions
586 // - KCFI: KCFI_CHECK pseudo instructions need to be unbundled for AsmPrinter
587 addPass(P: createUnpackMachineBundlesLegacy(Ftor: [](const MachineFunction &MF) {
588 return MF.getSubtarget<ARMSubtarget>().isThumb2() ||
589 MF.getFunction().getParent()->getModuleFlag(Key: "kcfi");
590 }));
591
592 // Don't optimize barriers or block placement at -O0.
593 if (getOptLevel() != CodeGenOptLevel::None) {
594 addPass(P: createARMBlockPlacementPass());
595 addPass(P: createARMOptimizeBarriersPass());
596 }
597}
598
599void ARMPassConfig::addPreEmitPass2() {
600
601 // Inserts fixup instructions before unsafe AES operations. Instructions may
602 // be inserted at the start of blocks and at within blocks so this pass has to
603 // come before those below.
604 addPass(P: createARMFixCortexA57AES1742098Pass());
605 // Inserts BTIs at the start of functions and indirectly-called basic blocks,
606 // so passes cannot add to the start of basic blocks once this has run.
607 addPass(P: createARMBranchTargetsPass());
608 // Inserts Constant Islands. Block sizes cannot be increased after this point,
609 // as this may push the branch ranges and load offsets of accessing constant
610 // pools out of range..
611 addPass(P: createARMConstantIslandPass());
612 // Finalises Low-Overhead Loops. This replaces pseudo instructions with real
613 // instructions, but the pseudos all have conservative sizes so that block
614 // sizes will only be decreased by this pass.
615 addPass(P: createARMLowOverheadLoopsPass());
616
617 if (TM->getTargetTriple().isOSWindows()) {
618 // Identify valid longjmp targets for Windows Control Flow Guard.
619 addPass(P: createCFGuardLongjmpPass());
620 // Identify valid eh continuation targets for Windows EHCont Guard.
621 addPass(P: createEHContGuardTargetsLegacy());
622 }
623}
624
625yaml::MachineFunctionInfo *
626ARMBaseTargetMachine::createDefaultFuncInfoYAML() const {
627 return new yaml::ARMFunctionInfo();
628}
629
630yaml::MachineFunctionInfo *
631ARMBaseTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
632 const auto *MFI = MF.getInfo<ARMFunctionInfo>();
633 return new yaml::ARMFunctionInfo(*MFI);
634}
635
636bool ARMBaseTargetMachine::parseMachineFunctionInfo(
637 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
638 SMDiagnostic &Error, SMRange &SourceRange) const {
639 const auto &YamlMFI = static_cast<const yaml::ARMFunctionInfo &>(MFI);
640 MachineFunction &MF = PFS.MF;
641 MF.getInfo<ARMFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
642 return false;
643}
644
645void ARMBaseTargetMachine::reset() { SubtargetMap.clear(); }
646