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