1//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
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 "AArch64TargetMachine.h"
13#include "AArch64.h"
14#include "AArch64AsmPrinter.h"
15#include "AArch64MachineFunctionInfo.h"
16#include "AArch64MachineScheduler.h"
17#include "AArch64MacroFusion.h"
18#include "AArch64Subtarget.h"
19#include "AArch64TargetObjectFile.h"
20#include "AArch64TargetTransformInfo.h"
21#include "MCTargetDesc/AArch64MCTargetDesc.h"
22#include "TargetInfo/AArch64TargetInfo.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/CodeGen/CSEConfigBase.h"
27#include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
29#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
30#include "llvm/CodeGen/GlobalISel/Legalizer.h"
31#include "llvm/CodeGen/GlobalISel/LoadStoreOpt.h"
32#include "llvm/CodeGen/GlobalISel/Localizer.h"
33#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
34#include "llvm/CodeGen/MIRParser/MIParser.h"
35#include "llvm/CodeGen/MachineScheduler.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/CodeGen/TargetInstrInfo.h"
38#include "llvm/CodeGen/TargetPassConfig.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/Function.h"
41#include "llvm/InitializePasses.h"
42#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/MCTargetOptions.h"
44#include "llvm/MC/TargetRegistry.h"
45#include "llvm/Pass.h"
46#include "llvm/Passes/PassBuilder.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Target/TargetLoweringObjectFile.h"
51#include "llvm/Target/TargetOptions.h"
52#include "llvm/TargetParser/Triple.h"
53#include "llvm/Transforms/CFGuard.h"
54#include "llvm/Transforms/Scalar.h"
55#include "llvm/Transforms/Utils/LowerIFunc.h"
56#include "llvm/Transforms/Vectorize/LoopIdiomVectorize.h"
57#include <memory>
58
59using namespace llvm;
60
61static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
62 cl::desc("Enable the CCMP formation pass"),
63 cl::init(Val: true), cl::Hidden);
64
65static cl::opt<bool>
66 EnableCondBrTuning("aarch64-enable-cond-br-tune",
67 cl::desc("Enable the conditional branch tuning pass"),
68 cl::init(Val: true), cl::Hidden);
69
70static cl::opt<bool> EnableAArch64CopyPropagation(
71 "aarch64-enable-copy-propagation",
72 cl::desc("Enable the copy propagation with AArch64 copy instr"),
73 cl::init(Val: true), cl::Hidden);
74
75static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
76 cl::desc("Enable the machine combiner pass"),
77 cl::init(Val: true), cl::Hidden);
78
79static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
80 cl::desc("Suppress STP for AArch64"),
81 cl::init(Val: true), cl::Hidden);
82
83static cl::opt<bool> EnableAdvSIMDScalar(
84 "aarch64-enable-simd-scalar",
85 cl::desc("Enable use of AdvSIMD scalar integer instructions"),
86 cl::init(Val: false), cl::Hidden);
87
88static cl::opt<bool>
89 EnablePromoteConstant("aarch64-enable-promote-const",
90 cl::desc("Enable the promote constant pass"),
91 cl::init(Val: true), cl::Hidden);
92
93static cl::opt<bool> EnableCollectLOH(
94 "aarch64-enable-collect-loh",
95 cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
96 cl::init(Val: true), cl::Hidden);
97
98static cl::opt<bool>
99 EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
100 cl::desc("Enable the pass that removes dead"
101 " definitions and replaces stores to"
102 " them with stores to the zero"
103 " register"),
104 cl::init(Val: true));
105
106static cl::opt<bool> EnableRedundantCopyElimination(
107 "aarch64-enable-copyelim",
108 cl::desc("Enable the redundant copy elimination pass"), cl::init(Val: true),
109 cl::Hidden);
110
111static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
112 cl::desc("Enable the load/store pair"
113 " optimization pass"),
114 cl::init(Val: true), cl::Hidden);
115
116static cl::opt<bool> EnableAtomicTidy(
117 "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
118 cl::desc("Run SimplifyCFG after expanding atomic operations"
119 " to make use of cmpxchg flow-based information"),
120 cl::init(Val: true));
121
122static cl::opt<bool>
123EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
124 cl::desc("Run early if-conversion"),
125 cl::init(Val: true));
126
127static cl::opt<bool>
128 EnableCondOpt("aarch64-enable-condopt",
129 cl::desc("Enable the condition optimizer pass"),
130 cl::init(Val: true), cl::Hidden);
131
132static cl::opt<bool>
133 EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
134 cl::desc("Enable optimizations on complex GEPs"),
135 cl::init(Val: false));
136
137static cl::opt<bool>
138 EnableSelectOpt("aarch64-select-opt", cl::Hidden,
139 cl::desc("Enable select to branch optimizations"),
140 cl::init(Val: true));
141
142static cl::opt<bool>
143 BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(Val: true),
144 cl::desc("Relax out of range conditional branches"));
145
146static cl::opt<bool> EnableCompressJumpTables(
147 "aarch64-enable-compress-jump-tables", cl::Hidden, cl::init(Val: true),
148 cl::desc("Use smallest entry possible for jump tables"));
149
150// FIXME: Unify control over GlobalMerge.
151static cl::opt<cl::boolOrDefault>
152 EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
153 cl::desc("Enable the global merge pass"));
154
155static cl::opt<bool>
156 EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
157 cl::desc("Enable the loop data prefetch pass"),
158 cl::init(Val: true));
159
160static cl::opt<int> EnableGlobalISelAtO(
161 "aarch64-enable-global-isel-at-O", cl::Hidden,
162 cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
163 cl::init(Val: 0));
164
165static cl::opt<bool>
166 EnableSMEPeepholeOpt("enable-aarch64-sme-peephole-opt", cl::init(Val: true),
167 cl::Hidden,
168 cl::desc("Perform SME peephole optimization"));
169
170static cl::opt<bool> EnableFalkorHWPFFix("aarch64-enable-falkor-hwpf-fix",
171 cl::init(Val: true), cl::Hidden);
172
173static cl::opt<bool>
174 EnableBranchTargets("aarch64-enable-branch-targets", cl::Hidden,
175 cl::desc("Enable the AArch64 branch target pass"),
176 cl::init(Val: true));
177
178static cl::opt<unsigned> SVEVectorBitsMaxOpt(
179 "aarch64-sve-vector-bits-max",
180 cl::desc("Assume SVE vector registers are at most this big, "
181 "with zero meaning no maximum size is assumed."),
182 cl::init(Val: 0), cl::Hidden);
183
184static cl::opt<unsigned> SVEVectorBitsMinOpt(
185 "aarch64-sve-vector-bits-min",
186 cl::desc("Assume SVE vector registers are at least this big, "
187 "with zero meaning no minimum size is assumed."),
188 cl::init(Val: 0), cl::Hidden);
189
190static cl::opt<bool> ForceStreaming(
191 "force-streaming",
192 cl::desc("Force the use of streaming code for all functions"),
193 cl::init(Val: false), cl::Hidden);
194
195static cl::opt<bool> ForceStreamingCompatible(
196 "force-streaming-compatible",
197 cl::desc("Force the use of streaming-compatible code for all functions"),
198 cl::init(Val: false), cl::Hidden);
199
200extern cl::opt<bool> EnableHomogeneousPrologEpilog;
201
202static cl::opt<bool> EnableGISelLoadStoreOptPreLegal(
203 "aarch64-enable-gisel-ldst-prelegal",
204 cl::desc("Enable GlobalISel's pre-legalizer load/store optimization pass"),
205 cl::init(Val: true), cl::Hidden);
206
207static cl::opt<bool> EnableGISelLoadStoreOptPostLegal(
208 "aarch64-enable-gisel-ldst-postlegal",
209 cl::desc("Enable GlobalISel's post-legalizer load/store optimization pass"),
210 cl::init(Val: false), cl::Hidden);
211
212static cl::opt<bool>
213 EnableSinkFold("aarch64-enable-sink-fold",
214 cl::desc("Enable sinking and folding of instruction copies"),
215 cl::init(Val: true), cl::Hidden);
216
217static cl::opt<bool>
218 EnableMachinePipeliner("aarch64-enable-pipeliner",
219 cl::desc("Enable Machine Pipeliner for AArch64"),
220 cl::init(Val: false), cl::Hidden);
221
222static cl::opt<bool> EnableSRLTSubregToRegMitigation(
223 "aarch64-srlt-mitigate-sr2r",
224 cl::desc("Enable SUBREG_TO_REG mitigation by adding 'implicit-def' for "
225 "super-regs when using Subreg Liveness Tracking"),
226 cl::init(Val: true), cl::Hidden);
227
228static cl::opt<bool> EnableSVEShuffleOpt(
229 "aarch64-enable-sve-shuffle-opts",
230 cl::desc("Enable pattern matching of shuffles that could make use of SVE "
231 "instructions like tbl or the bottom/top variants"),
232 cl::init(Val: true), cl::Hidden);
233
234extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
235LLVMInitializeAArch64Target() {
236 // Register the target.
237 RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
238 RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
239 RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
240 RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
241 RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
242 auto &PR = *PassRegistry::getPassRegistry();
243 initializeGlobalISel(PR);
244 initializeAArch64A53Fix835769LegacyPass(PR);
245 initializeAArch64A57FPLoadBalancingLegacyPass(PR);
246 initializeAArch64CodeLayoutOptPass(PR);
247 initializeAArch64AdvSIMDScalarLegacyPass(PR);
248 initializeAArch64AsmPrinterPass(PR);
249 initializeAArch64BranchTargetsLegacyPass(PR);
250 initializeAArch64CollectLOHLegacyPass(PR);
251 initializeAArch64CompressJumpTablesLegacyPass(PR);
252 initializeAArch64ConditionalComparesLegacyPass(PR);
253 initializeAArch64ConditionOptimizerLegacyPass(PR);
254 initializeAArch64DeadRegisterDefinitionsLegacyPass(PR);
255 initializeAArch64ExpandPseudoLegacyPass(PR);
256 initializeAArch64LoadStoreOptLegacyPass(PR);
257 initializeAArch64MIPeepholeOptLegacyPass(PR);
258 initializeAArch64PTrueCoalescingLegacyPass(PR);
259 initializeAArch64SIMDInstrOptLegacyPass(PR);
260 initializeAArch64O0PreLegalizerCombinerLegacyPass(PR);
261 initializeAArch64PreLegalizerCombinerLegacyPass(PR);
262 initializeAArch64PointerAuthLegacyPass(PR);
263 initializeAArch64PostCoalescerLegacyPass(PR);
264 initializeAArch64PostLegalizerCombinerLegacyPass(PR);
265 initializeAArch64PostSelectOptimizeLegacyPass(PR);
266 initializeAArch64PostLegalizerLoweringLegacyPass(PR);
267 initializeAArch64PromoteConstantPass(PR);
268 initializeAArch64RedundantCopyEliminationLegacyPass(PR);
269 initializeAArch64RedundantCondBranchLegacyPass(PR);
270 initializeAArch64StorePairSuppressPass(PR);
271 initializeFalkorHWPFFixPass(PR);
272 initializeFalkorMarkStridedAccessesLegacyPass(PR);
273 initializeLDTLSCleanupPass(PR);
274 initializeMachineKCFILegacyPass(PR);
275 initializeMachineSMEABIPass(PR);
276 initializeAArch64SRLTDefineSuperRegsLegacyPass(PR);
277 initializeSMEPeepholeOptPass(PR);
278 initializeAArch64SpeculationHardeningPass(PR);
279 initializeAArch64SLSHardeningLegacyPass(PR);
280 initializeAArch64StackTaggingPass(PR);
281 initializeAArch64StackTaggingPreRALegacyPass(PR);
282 initializeAArch64LowerHomogeneousPrologEpilogLegacyPass(PR);
283 initializeAArch64DAGToDAGISelLegacyPass(PR);
284 initializeAArch64CondBrTuningPass(PR);
285 initializeAArch64Arm64ECCallLoweringPass(PR);
286 initializeSVEShuffleOptsPass(PR);
287}
288
289bool AArch64TargetMachine::isGlobalISelOptNone() const {
290 const bool GlobalISelFlag = getCGPassBuilderOption().EnableGlobalISelOption ==
291 cl::boolOrDefault::BOU_TRUE;
292
293 return getOptLevel() == CodeGenOptLevel::None ||
294 (static_cast<unsigned>(getOptLevel()) >
295 static_cast<unsigned>(EnableGlobalISelAtO) &&
296 !GlobalISelFlag);
297}
298
299void AArch64TargetMachine::reset() { SubtargetMap.clear(); }
300
301//===----------------------------------------------------------------------===//
302// AArch64 Lowering public interface.
303//===----------------------------------------------------------------------===//
304static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
305 if (TT.isOSBinFormatMachO())
306 return std::make_unique<AArch64_MachoTargetObjectFile>();
307 if (TT.isOSBinFormatCOFF())
308 return std::make_unique<AArch64_COFFTargetObjectFile>();
309
310 return std::make_unique<AArch64_ELFTargetObjectFile>();
311}
312
313static StringRef computeDefaultCPU(const Triple &TT, StringRef CPU) {
314 if (CPU.empty() && TT.isArm64e())
315 return "apple-a12";
316 return CPU;
317}
318
319static Reloc::Model getEffectiveRelocModel(const Triple &TT,
320 std::optional<Reloc::Model> RM) {
321 // AArch64 Darwin and Windows are always PIC.
322 if (TT.isOSDarwin() || TT.isOSWindows())
323 return Reloc::PIC_;
324 // On ELF platforms the default static relocation model has a smart enough
325 // linker to cope with referencing external symbols defined in a shared
326 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
327 if (!RM || *RM == Reloc::DynamicNoPIC)
328 return Reloc::Static;
329 return *RM;
330}
331
332static CodeModel::Model
333getEffectiveAArch64CodeModel(const Triple &TT,
334 std::optional<CodeModel::Model> CM, bool JIT) {
335 if (CM) {
336 if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
337 *CM != CodeModel::Large) {
338 report_fatal_error(
339 reason: "Only small, tiny and large code models are allowed on AArch64");
340 } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF()) {
341 report_fatal_error(reason: "tiny code model is only supported on ELF");
342 }
343 return *CM;
344 }
345 // The default MCJIT memory managers make no guarantees about where they can
346 // find an executable page; JITed code needs to be able to refer to globals
347 // no matter how far away they are.
348 // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
349 // since with large code model LLVM generating 4 MOV instructions, and
350 // Windows doesn't support relocating these long branch (4 MOVs).
351 if (JIT && !TT.isOSWindows())
352 return CodeModel::Large;
353 return CodeModel::Small;
354}
355
356/// Create an AArch64 architecture model.
357///
358AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
359 StringRef CPU, StringRef FS,
360 const TargetOptions &Options,
361 std::optional<Reloc::Model> RM,
362 std::optional<CodeModel::Model> CM,
363 CodeGenOptLevel OL, bool JIT,
364 bool LittleEndian)
365 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT,
366 computeDefaultCPU(TT, CPU), FS, Options,
367 getEffectiveRelocModel(TT, RM),
368 getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
369 TLOF(createTLOF(TT: getTargetTriple())), isLittle(LittleEndian) {
370 initAsmInfo();
371
372 if (TT.isOSBinFormatMachO()) {
373 this->Options.TrapUnreachable = true;
374 this->Options.NoTrapAfterNoreturn = true;
375 }
376
377 if (getMCAsmInfo().usesWindowsCFI()) {
378 // Unwinding can get confused if the last instruction in an
379 // exception-handling region (function, funclet, try block, etc.)
380 // is a call.
381 //
382 // FIXME: We could elide the trap if the next instruction would be in
383 // the same region anyway.
384 this->Options.TrapUnreachable = true;
385 }
386
387 if (this->Options.TLSSize == 0) // default
388 this->Options.TLSSize = 24;
389 if ((getCodeModel() == CodeModel::Small ||
390 getCodeModel() == CodeModel::Kernel) &&
391 this->Options.TLSSize > 32)
392 // for the small (and kernel) code model, the maximum TLS size is 4GiB
393 this->Options.TLSSize = 32;
394 else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
395 // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
396 this->Options.TLSSize = 24;
397
398 const bool TargetSupportsGISel =
399 TT.getArch() != Triple::aarch64_32 &&
400 TT.getEnvironment() != Triple::GNUILP32 &&
401 !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO());
402
403 const bool GlobalISelFlag = getCGPassBuilderOption().EnableGlobalISelOption ==
404 cl::boolOrDefault::BOU_TRUE;
405
406 // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
407 // MachO/CodeModel::Large, which GlobalISel does not support.
408 if (TargetSupportsGISel && EnableGlobalISelAtO != -1 &&
409 (static_cast<int>(getOptLevel()) <= EnableGlobalISelAtO ||
410 (!GlobalISelFlag && !Options.EnableGlobalISel))) {
411 setGlobalISel(true);
412 setGlobalISelAbort(GlobalISelAbortMode::Disable);
413 }
414
415 LLT::setUseExtended(true);
416
417 // AArch64 supports the MachineOutliner.
418 setMachineOutliner(true);
419
420 // AArch64 supports default outlining behaviour.
421 setSupportsDefaultOutlining(true);
422
423 // AArch64 supports the debug entry values.
424 setSupportsDebugEntryValues(true);
425
426 // AArch64 supports fixing up the DWARF unwind information.
427 if (!getMCAsmInfo().usesWindowsCFI())
428 setCFIFixup(true);
429}
430
431unsigned AArch64TargetMachine::getEnableGlobalISelAtO() const {
432 return EnableGlobalISelAtO;
433}
434
435AArch64TargetMachine::~AArch64TargetMachine() = default;
436
437const AArch64Subtarget *
438AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
439 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
440 Attribute TuneAttr = F.getFnAttribute(Kind: "tune-cpu");
441 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
442
443 StringRef CPU = CPUAttr.isValid() ? CPUAttr.getValueAsString() : TargetCPU;
444 StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString() : CPU;
445 StringRef FS = FSAttr.isValid() ? FSAttr.getValueAsString() : TargetFS;
446 bool HasMinSize = F.hasMinSize();
447
448 bool IsStreaming = ForceStreaming ||
449 F.hasFnAttribute(Kind: "aarch64_pstate_sm_enabled") ||
450 F.hasFnAttribute(Kind: "aarch64_pstate_sm_body");
451 bool IsStreamingCompatible = ForceStreamingCompatible ||
452 F.hasFnAttribute(Kind: "aarch64_pstate_sm_compatible");
453
454 unsigned MinSVEVectorSize = 0;
455 unsigned MaxSVEVectorSize = 0;
456 if (F.hasFnAttribute(Kind: Attribute::VScaleRange)) {
457 ConstantRange CR = getVScaleRange(F: &F, BitWidth: 64);
458 MinSVEVectorSize = CR.getUnsignedMin().getZExtValue() * 128;
459 MaxSVEVectorSize = CR.getUnsignedMax().getZExtValue() * 128;
460 } else {
461 MinSVEVectorSize = SVEVectorBitsMinOpt;
462 MaxSVEVectorSize = SVEVectorBitsMaxOpt;
463 }
464
465 assert(MinSVEVectorSize % 128 == 0 &&
466 "SVE requires vector length in multiples of 128!");
467 assert(MaxSVEVectorSize % 128 == 0 &&
468 "SVE requires vector length in multiples of 128!");
469 assert((MaxSVEVectorSize >= MinSVEVectorSize || MaxSVEVectorSize == 0) &&
470 "Minimum SVE vector size should not be larger than its maximum!");
471
472 // Sanitize user input in case of no asserts
473 if (MaxSVEVectorSize != 0) {
474 MinSVEVectorSize = std::min(a: MinSVEVectorSize, b: MaxSVEVectorSize);
475 MaxSVEVectorSize = std::max(a: MinSVEVectorSize, b: MaxSVEVectorSize);
476 }
477
478 SmallString<512> Key;
479 // This lookup is hot during repeated TTI queries, so build the key directly
480 // instead of formatting through raw_svector_ostream.
481 Key += "SVEMin";
482 Key += utostr(X: MinSVEVectorSize);
483 Key += "SVEMax";
484 Key += utostr(X: MaxSVEVectorSize);
485 Key += "IsStreaming=";
486 Key += utostr(X: IsStreaming);
487 Key += "IsStreamingCompatible=";
488 Key += utostr(X: IsStreamingCompatible);
489 Key += CPU;
490 Key += TuneCPU;
491 Key += FS;
492 Key += "HasMinSize=";
493 Key += utostr(X: HasMinSize);
494
495 auto &I = SubtargetMap[Key];
496 if (!I) {
497 I = std::make_unique<AArch64Subtarget>(
498 args: TargetTriple, args&: CPU, args&: TuneCPU, args&: FS, args: *this, args: isLittle, args&: MinSVEVectorSize,
499 args&: MaxSVEVectorSize, args&: IsStreaming, args&: IsStreamingCompatible, args&: HasMinSize,
500 args&: EnableSRLTSubregToRegMitigation);
501 }
502
503 if (IsStreaming && !I->hasSME())
504 reportFatalUsageError(reason: "streaming SVE functions require SME");
505
506 return I.get();
507}
508
509// Encourage placing FORM_TRANSPOSED_REG immediately before the instruction that
510// uses/consumes it. This ensures its def has a short live range, which means
511// we're more likely to allocate registers its operands first (which works best
512// for the hints in AArch64RegisterInfo::getRegAllocationHints).
513static bool scheduleFormTransposedTupleAdjacentToUsers(
514 const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI,
515 const MachineInstr *FirstMI, const MachineInstr &SecondMI,
516 const SDep *Dep) {
517 if (isNonDataDep(Dep))
518 return false;
519 return !FirstMI ||
520 FirstMI->getOpcode() == AArch64::FORM_TRANSPOSED_REG_TUPLE_X2_PSEUDO ||
521 FirstMI->getOpcode() == AArch64::FORM_TRANSPOSED_REG_TUPLE_X4_PSEUDO;
522}
523
524ScheduleDAGInstrs *
525AArch64TargetMachine::createMachineScheduler(MachineSchedContext *C) const {
526 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
527 ScheduleDAGMILive *DAG = createSchedLive(C);
528 DAG->addMutation(Mutation: createLoadClusterDAGMutation(TII: DAG->TII, TRI: DAG->TRI));
529 DAG->addMutation(Mutation: createStoreClusterDAGMutation(TII: DAG->TII, TRI: DAG->TRI));
530 if (ST.hasFusion())
531 DAG->addMutation(Mutation: createAArch64MacroFusionDAGMutation());
532 if (ST.hasSME() && ST.isStreaming())
533 DAG->addMutation(Mutation: createMacroFusionDAGMutation(
534 Predicates: scheduleFormTransposedTupleAdjacentToUsers));
535 return DAG;
536}
537
538ScheduleDAGInstrs *
539AArch64TargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
540 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
541 ScheduleDAGMI *DAG = createSchedPostRA<AArch64PostRASchedStrategy>(C);
542 if (ST.hasFusion()) {
543 // Run the Macro Fusion after RA again since literals are expanded from
544 // pseudos then (v. addPreSched2()).
545 DAG->addMutation(Mutation: createAArch64MacroFusionDAGMutation());
546 return DAG;
547 }
548
549 return DAG;
550}
551
552size_t AArch64TargetMachine::clearLinkerOptimizationHints(
553 const SmallPtrSetImpl<MachineInstr *> &MIs) const {
554 if (MIs.empty())
555 return 0;
556 auto *MI = *MIs.begin();
557 auto *FuncInfo = MI->getMF()->getInfo<AArch64FunctionInfo>();
558 return FuncInfo->clearLinkerOptimizationHints(MIs);
559}
560
561void AArch64leTargetMachine::anchor() { }
562
563AArch64leTargetMachine::AArch64leTargetMachine(
564 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
565 const TargetOptions &Options, std::optional<Reloc::Model> RM,
566 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT)
567 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
568
569void AArch64beTargetMachine::anchor() { }
570
571AArch64beTargetMachine::AArch64beTargetMachine(
572 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
573 const TargetOptions &Options, std::optional<Reloc::Model> RM,
574 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT)
575 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
576
577namespace {
578
579/// AArch64 Code Generator Pass Configuration Options.
580class AArch64PassConfig : public TargetPassConfig {
581public:
582 AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
583 : TargetPassConfig(TM, PM) {
584 if (TM.getOptLevel() != CodeGenOptLevel::None)
585 substitutePass(StandardID: &PostRASchedulerID, TargetID: &PostMachineSchedulerID);
586 setEnableSinkAndFold(EnableSinkFold);
587 }
588
589 AArch64TargetMachine &getAArch64TargetMachine() const {
590 return getTM<AArch64TargetMachine>();
591 }
592
593 void addIRPasses() override;
594 bool addPreISel() override;
595 void addCodeGenPrepare() override;
596 bool addInstSelector() override;
597 bool addIRTranslator() override;
598 void addPreLegalizeMachineIR() override;
599 bool addLegalizeMachineIR() override;
600 void addPreRegBankSelect() override;
601 bool addRegBankSelect() override;
602 bool addGlobalInstructionSelect() override;
603 void addMachineSSAOptimization() override;
604 bool addILPOpts() override;
605 void addPreRegAlloc() override;
606 void addPostRewrite() override;
607 void addPostRegAlloc() override;
608 void addPreSched2() override;
609 void addPreEmitPass() override;
610 void addPostBBSections() override;
611 void addPreEmitPass2() override;
612 bool addRegAssignAndRewriteOptimized() override;
613
614 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
615};
616
617} // end anonymous namespace
618
619void AArch64TargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
620#define GET_PASS_REGISTRY "AArch64PassRegistry.def"
621#include "llvm/Passes/TargetPassRegistry.inc"
622
623 PB.registerLateLoopOptimizationsEPCallback(
624 C: [=](LoopPassManager &LPM, OptimizationLevel Level) {
625 if (Level != OptimizationLevel::O0)
626 LPM.addPass(Pass: LoopIdiomVectorizePass());
627 });
628 if (getTargetTriple().isOSWindows())
629 PB.registerPipelineEarlySimplificationEPCallback(
630 C: [](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
631 PM.addPass(Pass: LowerIFuncPass());
632 });
633}
634
635TargetTransformInfo
636AArch64TargetMachine::getTargetTransformInfo(const Function &F) const {
637 return TargetTransformInfo(std::make_unique<AArch64TTIImpl>(args: this, args: F));
638}
639
640TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
641 return new AArch64PassConfig(*this, PM);
642}
643
644std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
645 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
646}
647
648void AArch64PassConfig::addIRPasses() {
649 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
650 // ourselves.
651 addPass(P: createAtomicExpandLegacyPass());
652
653 // Cmpxchg instructions are often used with a subsequent comparison to
654 // determine whether it succeeded. We can exploit existing control-flow in
655 // ldrex/strex loops to simplify this, but it needs tidying up.
656 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAtomicTidy)
657 addPass(P: createCFGSimplificationPass(Options: SimplifyCFGOptions()
658 .forwardSwitchCondToPhi(B: true)
659 .convertSwitchRangeToICmp(B: true)
660 .convertSwitchToLookupTable(B: true)
661 .needCanonicalLoops(B: false)
662 .hoistCommonInsts(B: true)
663 .sinkCommonInsts(B: true)));
664
665 // Run LoopDataPrefetch
666 //
667 // Run this before LSR to remove the multiplies involved in computing the
668 // pointer values N iterations ahead.
669 if (TM->getOptLevel() != CodeGenOptLevel::None) {
670 if (EnableLoopDataPrefetch)
671 addPass(P: createLoopDataPrefetchPass());
672 if (EnableFalkorHWPFFix)
673 addPass(P: createFalkorMarkStridedAccessesPass());
674 }
675
676 if (EnableGEPOpt) {
677 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
678 // and lower a GEP with multiple indices to either arithmetic operations or
679 // multiple GEPs with single index.
680 addPass(P: createSeparateConstOffsetFromGEPPass(LowerGEP: true));
681 // Call EarlyCSE pass to find and remove subexpressions in the lowered
682 // result.
683 addPass(P: createEarlyCSEPass());
684 // Do loop invariant code motion in case part of the lowered result is
685 // invariant.
686 addPass(P: createLICMPass());
687 }
688
689 TargetPassConfig::addIRPasses();
690
691 if (getOptLevel() == CodeGenOptLevel::Aggressive && EnableSelectOpt)
692 addPass(P: createSelectOptimizePass());
693
694 addPass(P: createAArch64StackTaggingPass(
695 /*IsOptNone=*/TM->getOptLevel() == CodeGenOptLevel::None));
696
697 // Try to use tbl in place of other shuffling operations if doing so would
698 // reduce the total number of instructions. Shuffle masks for big endian may
699 // be different, so require a little endian target.
700 if (TM->createDataLayout().isLittleEndian() &&
701 getOptLevel() >= CodeGenOptLevel::Default && EnableSVEShuffleOpt)
702 addPass(P: createSVEShuffleOptsPass());
703
704 // Match complex arithmetic patterns
705 if (TM->getOptLevel() >= CodeGenOptLevel::Default)
706 addPass(P: createComplexDeinterleavingPass(TM));
707
708 // Match interleaved memory accesses to ldN/stN intrinsics.
709 if (TM->getOptLevel() != CodeGenOptLevel::None) {
710 addPass(P: createInterleavedLoadCombinePass());
711 addPass(P: createInterleavedAccessPass());
712 }
713
714 // Add Control Flow Guard checks.
715 if (TM->getTargetTriple().isOSWindows()) {
716 if (TM->getTargetTriple().isWindowsArm64EC())
717 addPass(P: createAArch64Arm64ECCallLoweringPass());
718 else
719 addPass(P: createCFGuardPass());
720 }
721
722 if (TM->Options.JMCInstrument)
723 addPass(P: createJMCInstrumenterPass());
724}
725
726// Pass Pipeline Configuration
727bool AArch64PassConfig::addPreISel() {
728 // Run promote constant before global merge, so that the promoted constants
729 // get a chance to be merged
730 if (TM->getOptLevel() != CodeGenOptLevel::None && EnablePromoteConstant)
731 addPass(P: createAArch64PromoteConstantPass());
732 // FIXME: On AArch64, this depends on the type.
733 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
734 // and the offset has to be a multiple of the related size in bytes.
735 if ((TM->getOptLevel() != CodeGenOptLevel::None &&
736 EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET) ||
737 EnableGlobalMerge == cl::boolOrDefault::BOU_TRUE) {
738 bool OnlyOptimizeForSize =
739 (TM->getOptLevel() < CodeGenOptLevel::Aggressive) &&
740 (EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET);
741
742 // Merging of extern globals is enabled by default on non-Mach-O as we
743 // expect it to be generally either beneficial or harmless. On Mach-O it
744 // is disabled as we emit the .subsections_via_symbols directive which
745 // means that merging extern globals is not safe.
746 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
747 addPass(P: createGlobalMergePass(TM, MaximalOffset: 4095, OnlyOptimizeForSize,
748 MergeExternalByDefault));
749 }
750
751 return false;
752}
753
754void AArch64PassConfig::addCodeGenPrepare() {
755 if (getOptLevel() != CodeGenOptLevel::None)
756 addPass(P: createTypePromotionLegacyPass());
757 TargetPassConfig::addCodeGenPrepare();
758}
759
760bool AArch64PassConfig::addInstSelector() {
761 addPass(P: createAArch64ISelDag(TM&: getAArch64TargetMachine(), OptLevel: getOptLevel()));
762
763 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
764 // references to _TLS_MODULE_BASE_ as possible.
765 if (TM->getTargetTriple().isOSBinFormatELF() &&
766 getOptLevel() != CodeGenOptLevel::None)
767 addPass(P: createAArch64CleanupLocalDynamicTLSPass());
768
769 return false;
770}
771
772bool AArch64PassConfig::addIRTranslator() {
773 addPass(P: new IRTranslatorLegacy(getOptLevel()));
774 return false;
775}
776
777void AArch64PassConfig::addPreLegalizeMachineIR() {
778 if (getAArch64TargetMachine().isGlobalISelOptNone()) {
779 addPass(P: createAArch64O0PreLegalizerCombiner());
780 addPass(P: new LocalizerLegacy());
781 } else {
782 addPass(P: createAArch64PreLegalizerCombiner());
783 addPass(P: new LocalizerLegacy());
784 if (EnableGISelLoadStoreOptPreLegal)
785 addPass(P: new LoadStoreOptLegacy());
786 }
787}
788
789bool AArch64PassConfig::addLegalizeMachineIR() {
790 addPass(P: new LegalizerLegacy());
791 return false;
792}
793
794void AArch64PassConfig::addPreRegBankSelect() {
795 const bool IsGlobalISelOptNone =
796 getAArch64TargetMachine().isGlobalISelOptNone();
797 if (!IsGlobalISelOptNone) {
798 addPass(P: createAArch64PostLegalizerCombinerLegacy(IsOptNone: IsGlobalISelOptNone));
799 if (EnableGISelLoadStoreOptPostLegal)
800 addPass(P: new LoadStoreOptLegacy());
801 }
802 addPass(P: createAArch64PostLegalizerLowering());
803}
804
805bool AArch64PassConfig::addRegBankSelect() {
806 addPass(P: new RegBankSelectLegacy());
807 return false;
808}
809
810bool AArch64PassConfig::addGlobalInstructionSelect() {
811 addPass(P: new InstructionSelectLegacy(getOptLevel()));
812 if (!getAArch64TargetMachine().isGlobalISelOptNone())
813 addPass(P: createAArch64PostSelectOptimize());
814 return false;
815}
816
817void AArch64PassConfig::addMachineSSAOptimization() {
818 if (TM->getOptLevel() != CodeGenOptLevel::None)
819 addPass(P: createMachineSMEABIPass(TM->getOptLevel()));
820
821 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableSMEPeepholeOpt)
822 addPass(P: createSMEPeepholeOptPass());
823
824 // Run default MachineSSAOptimization first.
825 TargetPassConfig::addMachineSSAOptimization();
826
827 if (TM->getOptLevel() != CodeGenOptLevel::None) {
828 addPass(P: createAArch64MIPeepholeOptLegacyPass());
829 addPass(P: createAArch64PTrueCoalescingLegacyPass());
830 }
831}
832
833bool AArch64PassConfig::addILPOpts() {
834 if (EnableCondOpt)
835 addPass(P: createAArch64ConditionOptimizerLegacyPass());
836 if (EnableCCMP)
837 addPass(P: createAArch64ConditionalCompares());
838 if (EnableMCR)
839 addPass(PassID: &MachineCombinerID);
840 if (EnableCondBrTuning)
841 addPass(P: createAArch64CondBrTuning());
842 if (EnableEarlyIfConversion)
843 addPass(PassID: &EarlyIfConverterLegacyID);
844 if (EnableStPairSuppress)
845 addPass(P: createAArch64StorePairSuppressPass());
846 addPass(P: createAArch64SIMDInstrOptPass());
847 if (TM->getOptLevel() != CodeGenOptLevel::None)
848 addPass(P: createAArch64StackTaggingPreRALegacyPass());
849 return true;
850}
851
852void AArch64PassConfig::addPreRegAlloc() {
853 if (TM->getOptLevel() == CodeGenOptLevel::None)
854 addPass(P: createMachineSMEABIPass(CodeGenOptLevel::None));
855
856 // Change dead register definitions to refer to the zero register.
857 if (TM->getOptLevel() != CodeGenOptLevel::None &&
858 EnableDeadRegisterElimination)
859 addPass(P: createAArch64DeadRegisterDefinitions());
860
861 // Use AdvSIMD scalar instructions whenever profitable.
862 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAdvSIMDScalar) {
863 addPass(P: createAArch64AdvSIMDScalar());
864 // The AdvSIMD pass may produce copies that can be rewritten to
865 // be register coalescer friendly.
866 addPass(PassID: &PeepholeOptimizerLegacyID);
867 }
868 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableMachinePipeliner)
869 addPass(PassID: &MachinePipelinerID);
870}
871
872void AArch64PassConfig::addPostRewrite() {
873 if (EnableSRLTSubregToRegMitigation)
874 addPass(P: createAArch64SRLTDefineSuperRegsLegacyPass());
875}
876
877void AArch64PassConfig::addPostRegAlloc() {
878 // Remove redundant copy instructions.
879 if (TM->getOptLevel() != CodeGenOptLevel::None &&
880 EnableRedundantCopyElimination)
881 addPass(P: createAArch64RedundantCopyEliminationPass());
882
883 if (TM->getOptLevel() != CodeGenOptLevel::None && usingDefaultRegAlloc())
884 // Improve performance for some FP/SIMD code for A57.
885 addPass(P: createAArch64A57FPLoadBalancingLegacyPass());
886}
887
888void AArch64PassConfig::addPreSched2() {
889 // Lower homogeneous frame instructions
890 if (EnableHomogeneousPrologEpilog)
891 addPass(P: createAArch64LowerHomogeneousPrologEpilogPass());
892 // Expand some pseudo instructions to allow proper scheduling.
893 addPass(P: createAArch64ExpandPseudoLegacyPass());
894 // Use load/store pair instructions when possible.
895 if (TM->getOptLevel() != CodeGenOptLevel::None) {
896 if (EnableLoadStoreOpt)
897 addPass(P: createAArch64LoadStoreOptLegacyPass());
898 }
899 // Emit KCFI checks for indirect calls.
900 addPass(P: createKCFIPass());
901
902 // The AArch64SpeculationHardeningPass destroys dominator tree and natural
903 // loop info, which is needed for the FalkorHWPFFixPass and also later on.
904 // Therefore, run the AArch64SpeculationHardeningPass before the
905 // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
906 // info.
907 addPass(P: createAArch64SpeculationHardeningPass());
908
909 if (TM->getOptLevel() != CodeGenOptLevel::None) {
910 if (EnableFalkorHWPFFix)
911 addPass(P: createFalkorHWPFFixPass());
912 }
913}
914
915void AArch64PassConfig::addPreEmitPass() {
916 // Machine Block Placement might have created new opportunities when run
917 // at O3, where the Tail Duplication Threshold is set to 4 instructions.
918 // Run the load/store optimizer once more.
919 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive && EnableLoadStoreOpt)
920 addPass(P: createAArch64LoadStoreOptLegacyPass());
921
922 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive &&
923 EnableAArch64CopyPropagation)
924 addPass(P: createMachineCopyPropagationPass(UseCopyInstr: true));
925 if (TM->getOptLevel() != CodeGenOptLevel::None)
926 addPass(P: createAArch64RedundantCondBranchPass());
927
928 addPass(P: createAArch64A53Fix835769LegacyPass());
929
930 if (TM->getTargetTriple().isOSWindows()) {
931 // Identify valid longjmp targets for Windows Control Flow Guard.
932 addPass(P: createCFGuardLongjmpPass());
933 // Identify valid eh continuation targets for Windows EHCont Guard.
934 addPass(P: createEHContGuardTargetsLegacy());
935 }
936
937 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCollectLOH &&
938 TM->getTargetTriple().isOSBinFormatMachO())
939 addPass(P: createAArch64CollectLOHPass());
940
941 // Apply code layout optimizations. Run late so detection reflects the
942 // final MI stream.
943 if (getOptLevel() != CodeGenOptLevel::None)
944 addPass(P: createAArch64CodeLayoutOptPass());
945}
946
947void AArch64PassConfig::addPostBBSections() {
948 addPass(P: createAArch64SLSHardeningLegacyPass());
949 addPass(P: createAArch64PointerAuthPass());
950 if (EnableBranchTargets)
951 addPass(P: createAArch64BranchTargetsPass());
952 // Relax conditional branch instructions if they're otherwise out of
953 // range of their destination.
954 if (BranchRelaxation)
955 addPass(PassID: &BranchRelaxationPassID);
956
957 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCompressJumpTables)
958 addPass(P: createAArch64CompressJumpTablesPass());
959}
960
961void AArch64PassConfig::addPreEmitPass2() {
962 // Insert pseudo probe annotation for callsite profiling
963 addPass(P: createPseudoProbeInserter());
964
965 // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
966 // instructions are lowered to bundles as well.
967 addPass(P: createUnpackMachineBundlesLegacy(Ftor: nullptr));
968}
969
970bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
971 addPass(P: createAArch64PostCoalescerPass());
972 return TargetPassConfig::addRegAssignAndRewriteOptimized();
973}
974
975MachineFunctionInfo *AArch64TargetMachine::createMachineFunctionInfo(
976 BumpPtrAllocator &Allocator, const Function &F,
977 const TargetSubtargetInfo *STI) const {
978 return AArch64FunctionInfo::create<AArch64FunctionInfo>(
979 Allocator, F, STI: static_cast<const AArch64Subtarget *>(STI));
980}
981
982yaml::MachineFunctionInfo *
983AArch64TargetMachine::createDefaultFuncInfoYAML() const {
984 return new yaml::AArch64FunctionInfo();
985}
986
987yaml::MachineFunctionInfo *
988AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
989 const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
990 return new yaml::AArch64FunctionInfo(*MFI);
991}
992
993bool AArch64TargetMachine::parseMachineFunctionInfo(
994 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
995 SMDiagnostic &Error, SMRange &SourceRange) const {
996 const auto &YamlMFI = static_cast<const yaml::AArch64FunctionInfo &>(MFI);
997 MachineFunction &MF = PFS.MF;
998 MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
999 return false;
1000}
1001