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