LLVM 20.0.0git
AArch64LoadStoreOptimizer.cpp
Go to the documentation of this file.
1//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
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// This file contains a pass that performs load / store related peephole
10// optimizations. This pass should be run after register allocation.
11//
12// The pass runs after the PrologEpilogInserter where we emit the CFI
13// instructions. In order to preserve the correctness of the unwind informaiton,
14// the pass should not change the order of any two instructions, one of which
15// has the FrameSetup/FrameDestroy flag or, alternatively, apply an add-hoc fix
16// to unwind information.
17//
18//===----------------------------------------------------------------------===//
19
20#include "AArch64InstrInfo.h"
22#include "AArch64Subtarget.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/DebugLoc.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCDwarf.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
47#include <cassert>
48#include <cstdint>
49#include <functional>
50#include <iterator>
51#include <limits>
52#include <optional>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "aarch64-ldst-opt"
57
58STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
59STATISTIC(NumPostFolded, "Number of post-index updates folded");
60STATISTIC(NumPreFolded, "Number of pre-index updates folded");
61STATISTIC(NumUnscaledPairCreated,
62 "Number of load/store from unscaled generated");
63STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
64STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
65STATISTIC(NumFailedAlignmentCheck, "Number of load/store pair transformation "
66 "not passed the alignment check");
67STATISTIC(NumConstOffsetFolded,
68 "Number of const offset of index address folded");
69
70DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
71 "Controls which pairs are considered for renaming");
72
73// The LdStLimit limits how far we search for load/store pairs.
74static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
75 cl::init(20), cl::Hidden);
76
77// The UpdateLimit limits how far we search for update instructions when we form
78// pre-/post-index instructions.
79static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
81
82// The LdStConstLimit limits how far we search for const offset instructions
83// when we form index address load/store instructions.
84static cl::opt<unsigned> LdStConstLimit("aarch64-load-store-const-scan-limit",
85 cl::init(10), cl::Hidden);
86
87// Enable register renaming to find additional store pairing opportunities.
88static cl::opt<bool> EnableRenaming("aarch64-load-store-renaming",
89 cl::init(true), cl::Hidden);
90
91#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
92
93namespace {
94
95using LdStPairFlags = struct LdStPairFlags {
96 // If a matching instruction is found, MergeForward is set to true if the
97 // merge is to remove the first instruction and replace the second with
98 // a pair-wise insn, and false if the reverse is true.
99 bool MergeForward = false;
100
101 // SExtIdx gives the index of the result of the load pair that must be
102 // extended. The value of SExtIdx assumes that the paired load produces the
103 // value in this order: (I, returned iterator), i.e., -1 means no value has
104 // to be extended, 0 means I, and 1 means the returned iterator.
105 int SExtIdx = -1;
106
107 // If not none, RenameReg can be used to rename the result register of the
108 // first store in a pair. Currently this only works when merging stores
109 // forward.
110 std::optional<MCPhysReg> RenameReg;
111
112 LdStPairFlags() = default;
113
114 void setMergeForward(bool V = true) { MergeForward = V; }
115 bool getMergeForward() const { return MergeForward; }
116
117 void setSExtIdx(int V) { SExtIdx = V; }
118 int getSExtIdx() const { return SExtIdx; }
119
120 void setRenameReg(MCPhysReg R) { RenameReg = R; }
121 void clearRenameReg() { RenameReg = std::nullopt; }
122 std::optional<MCPhysReg> getRenameReg() const { return RenameReg; }
123};
124
125struct AArch64LoadStoreOpt : public MachineFunctionPass {
126 static char ID;
127
128 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
130 }
131
132 AliasAnalysis *AA;
133 const AArch64InstrInfo *TII;
134 const TargetRegisterInfo *TRI;
135 const AArch64Subtarget *Subtarget;
136
137 // Track which register units have been modified and used.
138 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
139 LiveRegUnits DefinedInBB;
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 }
145
146 // Scan the instructions looking for a load/store that can be combined
147 // with the current instruction into a load/store pair.
148 // Return the matching instruction if one is found, else MBB->end().
150 LdStPairFlags &Flags,
151 unsigned Limit,
152 bool FindNarrowMerge);
153
154 // Scan the instructions looking for a store that writes to the address from
155 // which the current load instruction reads. Return true if one is found.
156 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
158
159 // Merge the two instructions indicated into a wider narrow store instruction.
161 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
163 const LdStPairFlags &Flags);
164
165 // Merge the two instructions indicated into a single pair-wise instruction.
167 mergePairedInsns(MachineBasicBlock::iterator I,
169 const LdStPairFlags &Flags);
170
171 // Promote the load that reads directly from the address stored to.
173 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
175
176 // Scan the instruction list to find a base register update that can
177 // be combined with the current instruction (a load or store) using
178 // pre or post indexed addressing with writeback. Scan forwards.
180 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
181 int UnscaledOffset, unsigned Limit);
182
183 // Scan the instruction list to find a register assigned with a const
184 // value that can be combined with the current instruction (a load or store)
185 // using base addressing with writeback. Scan backwards.
187 findMatchingConstOffsetBackward(MachineBasicBlock::iterator I, unsigned Limit,
188 unsigned &Offset);
189
190 // Scan the instruction list to find a base register update that can
191 // be combined with the current instruction (a load or store) using
192 // pre or post indexed addressing with writeback. Scan backwards.
194 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
195
196 // Find an instruction that updates the base register of the ld/st
197 // instruction.
198 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
199 unsigned BaseReg, int Offset);
200
201 bool isMatchingMovConstInsn(MachineInstr &MemMI, MachineInstr &MI,
202 unsigned IndexReg, unsigned &Offset);
203
204 // Merge a pre- or post-index base register update into a ld/st instruction.
206 mergeUpdateInsn(MachineBasicBlock::iterator I,
207 MachineBasicBlock::iterator Update, bool IsPreIdx);
208
210 mergeConstOffsetInsn(MachineBasicBlock::iterator I,
211 MachineBasicBlock::iterator Update, unsigned Offset,
212 int Scale);
213
214 // Find and merge zero store instructions.
215 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
216
217 // Find and pair ldr/str instructions.
218 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
219
220 // Find and promote load instructions which read directly from store.
221 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
222
223 // Find and merge a base register updates before or after a ld/st instruction.
224 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
225
226 // Find and merge an index ldr/st instruction into a base ld/st instruction.
227 bool tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI, int Scale);
228
229 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
230
231 bool runOnMachineFunction(MachineFunction &Fn) override;
232
235 MachineFunctionProperties::Property::NoVRegs);
236 }
237
238 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
239};
240
241char AArch64LoadStoreOpt::ID = 0;
242
243} // end anonymous namespace
244
245INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
246 AARCH64_LOAD_STORE_OPT_NAME, false, false)
247
248static bool isNarrowStore(unsigned Opc) {
249 switch (Opc) {
250 default:
251 return false;
252 case AArch64::STRBBui:
253 case AArch64::STURBBi:
254 case AArch64::STRHHui:
255 case AArch64::STURHHi:
256 return true;
257 }
258}
259
260// These instruction set memory tag and either keep memory contents unchanged or
261// set it to zero, ignoring the address part of the source register.
262static bool isTagStore(const MachineInstr &MI) {
263 switch (MI.getOpcode()) {
264 default:
265 return false;
266 case AArch64::STGi:
267 case AArch64::STZGi:
268 case AArch64::ST2Gi:
269 case AArch64::STZ2Gi:
270 return true;
271 }
272}
273
274static unsigned getMatchingNonSExtOpcode(unsigned Opc,
275 bool *IsValidLdStrOpc = nullptr) {
276 if (IsValidLdStrOpc)
277 *IsValidLdStrOpc = true;
278 switch (Opc) {
279 default:
280 if (IsValidLdStrOpc)
281 *IsValidLdStrOpc = false;
282 return std::numeric_limits<unsigned>::max();
283 case AArch64::STRDui:
284 case AArch64::STURDi:
285 case AArch64::STRDpre:
286 case AArch64::STRQui:
287 case AArch64::STURQi:
288 case AArch64::STRQpre:
289 case AArch64::STRBBui:
290 case AArch64::STURBBi:
291 case AArch64::STRHHui:
292 case AArch64::STURHHi:
293 case AArch64::STRWui:
294 case AArch64::STRWpre:
295 case AArch64::STURWi:
296 case AArch64::STRXui:
297 case AArch64::STRXpre:
298 case AArch64::STURXi:
299 case AArch64::LDRDui:
300 case AArch64::LDURDi:
301 case AArch64::LDRDpre:
302 case AArch64::LDRQui:
303 case AArch64::LDURQi:
304 case AArch64::LDRQpre:
305 case AArch64::LDRWui:
306 case AArch64::LDURWi:
307 case AArch64::LDRWpre:
308 case AArch64::LDRXui:
309 case AArch64::LDURXi:
310 case AArch64::LDRXpre:
311 case AArch64::STRSui:
312 case AArch64::STURSi:
313 case AArch64::STRSpre:
314 case AArch64::LDRSui:
315 case AArch64::LDURSi:
316 case AArch64::LDRSpre:
317 return Opc;
318 case AArch64::LDRSWui:
319 return AArch64::LDRWui;
320 case AArch64::LDURSWi:
321 return AArch64::LDURWi;
322 case AArch64::LDRSWpre:
323 return AArch64::LDRWpre;
324 }
325}
326
327static unsigned getMatchingWideOpcode(unsigned Opc) {
328 switch (Opc) {
329 default:
330 llvm_unreachable("Opcode has no wide equivalent!");
331 case AArch64::STRBBui:
332 return AArch64::STRHHui;
333 case AArch64::STRHHui:
334 return AArch64::STRWui;
335 case AArch64::STURBBi:
336 return AArch64::STURHHi;
337 case AArch64::STURHHi:
338 return AArch64::STURWi;
339 case AArch64::STURWi:
340 return AArch64::STURXi;
341 case AArch64::STRWui:
342 return AArch64::STRXui;
343 }
344}
345
346static unsigned getMatchingPairOpcode(unsigned Opc) {
347 switch (Opc) {
348 default:
349 llvm_unreachable("Opcode has no pairwise equivalent!");
350 case AArch64::STRSui:
351 case AArch64::STURSi:
352 return AArch64::STPSi;
353 case AArch64::STRSpre:
354 return AArch64::STPSpre;
355 case AArch64::STRDui:
356 case AArch64::STURDi:
357 return AArch64::STPDi;
358 case AArch64::STRDpre:
359 return AArch64::STPDpre;
360 case AArch64::STRQui:
361 case AArch64::STURQi:
362 return AArch64::STPQi;
363 case AArch64::STRQpre:
364 return AArch64::STPQpre;
365 case AArch64::STRWui:
366 case AArch64::STURWi:
367 return AArch64::STPWi;
368 case AArch64::STRWpre:
369 return AArch64::STPWpre;
370 case AArch64::STRXui:
371 case AArch64::STURXi:
372 return AArch64::STPXi;
373 case AArch64::STRXpre:
374 return AArch64::STPXpre;
375 case AArch64::LDRSui:
376 case AArch64::LDURSi:
377 return AArch64::LDPSi;
378 case AArch64::LDRSpre:
379 return AArch64::LDPSpre;
380 case AArch64::LDRDui:
381 case AArch64::LDURDi:
382 return AArch64::LDPDi;
383 case AArch64::LDRDpre:
384 return AArch64::LDPDpre;
385 case AArch64::LDRQui:
386 case AArch64::LDURQi:
387 return AArch64::LDPQi;
388 case AArch64::LDRQpre:
389 return AArch64::LDPQpre;
390 case AArch64::LDRWui:
391 case AArch64::LDURWi:
392 return AArch64::LDPWi;
393 case AArch64::LDRWpre:
394 return AArch64::LDPWpre;
395 case AArch64::LDRXui:
396 case AArch64::LDURXi:
397 return AArch64::LDPXi;
398 case AArch64::LDRXpre:
399 return AArch64::LDPXpre;
400 case AArch64::LDRSWui:
401 case AArch64::LDURSWi:
402 return AArch64::LDPSWi;
403 case AArch64::LDRSWpre:
404 return AArch64::LDPSWpre;
405 }
406}
407
410 unsigned LdOpc = LoadInst.getOpcode();
411 unsigned StOpc = StoreInst.getOpcode();
412 switch (LdOpc) {
413 default:
414 llvm_unreachable("Unsupported load instruction!");
415 case AArch64::LDRBBui:
416 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
417 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
418 case AArch64::LDURBBi:
419 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
420 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
421 case AArch64::LDRHHui:
422 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
423 StOpc == AArch64::STRXui;
424 case AArch64::LDURHHi:
425 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
426 StOpc == AArch64::STURXi;
427 case AArch64::LDRWui:
428 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
429 case AArch64::LDURWi:
430 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
431 case AArch64::LDRXui:
432 return StOpc == AArch64::STRXui;
433 case AArch64::LDURXi:
434 return StOpc == AArch64::STURXi;
435 }
436}
437
438static unsigned getPreIndexedOpcode(unsigned Opc) {
439 // FIXME: We don't currently support creating pre-indexed loads/stores when
440 // the load or store is the unscaled version. If we decide to perform such an
441 // optimization in the future the cases for the unscaled loads/stores will
442 // need to be added here.
443 switch (Opc) {
444 default:
445 llvm_unreachable("Opcode has no pre-indexed equivalent!");
446 case AArch64::STRSui:
447 return AArch64::STRSpre;
448 case AArch64::STRDui:
449 return AArch64::STRDpre;
450 case AArch64::STRQui:
451 return AArch64::STRQpre;
452 case AArch64::STRBBui:
453 return AArch64::STRBBpre;
454 case AArch64::STRHHui:
455 return AArch64::STRHHpre;
456 case AArch64::STRWui:
457 return AArch64::STRWpre;
458 case AArch64::STRXui:
459 return AArch64::STRXpre;
460 case AArch64::LDRSui:
461 return AArch64::LDRSpre;
462 case AArch64::LDRDui:
463 return AArch64::LDRDpre;
464 case AArch64::LDRQui:
465 return AArch64::LDRQpre;
466 case AArch64::LDRBBui:
467 return AArch64::LDRBBpre;
468 case AArch64::LDRHHui:
469 return AArch64::LDRHHpre;
470 case AArch64::LDRWui:
471 return AArch64::LDRWpre;
472 case AArch64::LDRXui:
473 return AArch64::LDRXpre;
474 case AArch64::LDRSWui:
475 return AArch64::LDRSWpre;
476 case AArch64::LDPSi:
477 return AArch64::LDPSpre;
478 case AArch64::LDPSWi:
479 return AArch64::LDPSWpre;
480 case AArch64::LDPDi:
481 return AArch64::LDPDpre;
482 case AArch64::LDPQi:
483 return AArch64::LDPQpre;
484 case AArch64::LDPWi:
485 return AArch64::LDPWpre;
486 case AArch64::LDPXi:
487 return AArch64::LDPXpre;
488 case AArch64::STPSi:
489 return AArch64::STPSpre;
490 case AArch64::STPDi:
491 return AArch64::STPDpre;
492 case AArch64::STPQi:
493 return AArch64::STPQpre;
494 case AArch64::STPWi:
495 return AArch64::STPWpre;
496 case AArch64::STPXi:
497 return AArch64::STPXpre;
498 case AArch64::STGi:
499 return AArch64::STGPreIndex;
500 case AArch64::STZGi:
501 return AArch64::STZGPreIndex;
502 case AArch64::ST2Gi:
503 return AArch64::ST2GPreIndex;
504 case AArch64::STZ2Gi:
505 return AArch64::STZ2GPreIndex;
506 case AArch64::STGPi:
507 return AArch64::STGPpre;
508 }
509}
510
511static unsigned getBaseAddressOpcode(unsigned Opc) {
512 // TODO: Add more index address stores.
513 switch (Opc) {
514 default:
515 llvm_unreachable("Opcode has no base address equivalent!");
516 case AArch64::LDRBroX:
517 return AArch64::LDRBui;
518 case AArch64::LDRBBroX:
519 return AArch64::LDRBBui;
520 case AArch64::LDRSBXroX:
521 return AArch64::LDRSBXui;
522 case AArch64::LDRSBWroX:
523 return AArch64::LDRSBWui;
524 case AArch64::LDRHroX:
525 return AArch64::LDRHui;
526 case AArch64::LDRHHroX:
527 return AArch64::LDRHHui;
528 case AArch64::LDRSHXroX:
529 return AArch64::LDRSHXui;
530 case AArch64::LDRSHWroX:
531 return AArch64::LDRSHWui;
532 case AArch64::LDRWroX:
533 return AArch64::LDRWui;
534 case AArch64::LDRSroX:
535 return AArch64::LDRSui;
536 case AArch64::LDRSWroX:
537 return AArch64::LDRSWui;
538 case AArch64::LDRDroX:
539 return AArch64::LDRDui;
540 case AArch64::LDRXroX:
541 return AArch64::LDRXui;
542 case AArch64::LDRQroX:
543 return AArch64::LDRQui;
544 }
545}
546
547static unsigned getPostIndexedOpcode(unsigned Opc) {
548 switch (Opc) {
549 default:
550 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
551 case AArch64::STRSui:
552 case AArch64::STURSi:
553 return AArch64::STRSpost;
554 case AArch64::STRDui:
555 case AArch64::STURDi:
556 return AArch64::STRDpost;
557 case AArch64::STRQui:
558 case AArch64::STURQi:
559 return AArch64::STRQpost;
560 case AArch64::STRBBui:
561 return AArch64::STRBBpost;
562 case AArch64::STRHHui:
563 return AArch64::STRHHpost;
564 case AArch64::STRWui:
565 case AArch64::STURWi:
566 return AArch64::STRWpost;
567 case AArch64::STRXui:
568 case AArch64::STURXi:
569 return AArch64::STRXpost;
570 case AArch64::LDRSui:
571 case AArch64::LDURSi:
572 return AArch64::LDRSpost;
573 case AArch64::LDRDui:
574 case AArch64::LDURDi:
575 return AArch64::LDRDpost;
576 case AArch64::LDRQui:
577 case AArch64::LDURQi:
578 return AArch64::LDRQpost;
579 case AArch64::LDRBBui:
580 return AArch64::LDRBBpost;
581 case AArch64::LDRHHui:
582 return AArch64::LDRHHpost;
583 case AArch64::LDRWui:
584 case AArch64::LDURWi:
585 return AArch64::LDRWpost;
586 case AArch64::LDRXui:
587 case AArch64::LDURXi:
588 return AArch64::LDRXpost;
589 case AArch64::LDRSWui:
590 return AArch64::LDRSWpost;
591 case AArch64::LDPSi:
592 return AArch64::LDPSpost;
593 case AArch64::LDPSWi:
594 return AArch64::LDPSWpost;
595 case AArch64::LDPDi:
596 return AArch64::LDPDpost;
597 case AArch64::LDPQi:
598 return AArch64::LDPQpost;
599 case AArch64::LDPWi:
600 return AArch64::LDPWpost;
601 case AArch64::LDPXi:
602 return AArch64::LDPXpost;
603 case AArch64::STPSi:
604 return AArch64::STPSpost;
605 case AArch64::STPDi:
606 return AArch64::STPDpost;
607 case AArch64::STPQi:
608 return AArch64::STPQpost;
609 case AArch64::STPWi:
610 return AArch64::STPWpost;
611 case AArch64::STPXi:
612 return AArch64::STPXpost;
613 case AArch64::STGi:
614 return AArch64::STGPostIndex;
615 case AArch64::STZGi:
616 return AArch64::STZGPostIndex;
617 case AArch64::ST2Gi:
618 return AArch64::ST2GPostIndex;
619 case AArch64::STZ2Gi:
620 return AArch64::STZ2GPostIndex;
621 case AArch64::STGPi:
622 return AArch64::STGPpost;
623 }
624}
625
627
628 unsigned OpcA = FirstMI.getOpcode();
629 unsigned OpcB = MI.getOpcode();
630
631 switch (OpcA) {
632 default:
633 return false;
634 case AArch64::STRSpre:
635 return (OpcB == AArch64::STRSui) || (OpcB == AArch64::STURSi);
636 case AArch64::STRDpre:
637 return (OpcB == AArch64::STRDui) || (OpcB == AArch64::STURDi);
638 case AArch64::STRQpre:
639 return (OpcB == AArch64::STRQui) || (OpcB == AArch64::STURQi);
640 case AArch64::STRWpre:
641 return (OpcB == AArch64::STRWui) || (OpcB == AArch64::STURWi);
642 case AArch64::STRXpre:
643 return (OpcB == AArch64::STRXui) || (OpcB == AArch64::STURXi);
644 case AArch64::LDRSpre:
645 return (OpcB == AArch64::LDRSui) || (OpcB == AArch64::LDURSi);
646 case AArch64::LDRDpre:
647 return (OpcB == AArch64::LDRDui) || (OpcB == AArch64::LDURDi);
648 case AArch64::LDRQpre:
649 return (OpcB == AArch64::LDRQui) || (OpcB == AArch64::LDURQi);
650 case AArch64::LDRWpre:
651 return (OpcB == AArch64::LDRWui) || (OpcB == AArch64::LDURWi);
652 case AArch64::LDRXpre:
653 return (OpcB == AArch64::LDRXui) || (OpcB == AArch64::LDURXi);
654 case AArch64::LDRSWpre:
655 return (OpcB == AArch64::LDRSWui) || (OpcB == AArch64::LDURSWi);
656 }
657}
658
659// Returns the scale and offset range of pre/post indexed variants of MI.
660static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
661 int &MinOffset, int &MaxOffset) {
662 bool IsPaired = AArch64InstrInfo::isPairedLdSt(MI);
663 bool IsTagStore = isTagStore(MI);
664 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
665 // as in the "unsigned offset" variant.
666 // All other pre/post indexed ldst instructions are unscaled.
667 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
668
669 if (IsPaired) {
670 MinOffset = -64;
671 MaxOffset = 63;
672 } else {
673 MinOffset = -256;
674 MaxOffset = 255;
675 }
676}
677
679 unsigned PairedRegOp = 0) {
680 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
681 bool IsPreLdSt = AArch64InstrInfo::isPreLdSt(MI);
682 if (IsPreLdSt)
683 PairedRegOp += 1;
684 unsigned Idx =
685 AArch64InstrInfo::isPairedLdSt(MI) || IsPreLdSt ? PairedRegOp : 0;
686 return MI.getOperand(Idx);
687}
688
691 const AArch64InstrInfo *TII) {
692 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
693 int LoadSize = TII->getMemScale(LoadInst);
694 int StoreSize = TII->getMemScale(StoreInst);
695 int UnscaledStOffset =
696 TII->hasUnscaledLdStOffset(StoreInst)
699 int UnscaledLdOffset =
700 TII->hasUnscaledLdStOffset(LoadInst)
703 return (UnscaledStOffset <= UnscaledLdOffset) &&
704 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
705}
706
708 unsigned Opc = MI.getOpcode();
709 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
710 isNarrowStore(Opc)) &&
711 getLdStRegOp(MI).getReg() == AArch64::WZR;
712}
713
715 switch (MI.getOpcode()) {
716 default:
717 return false;
718 // Scaled instructions.
719 case AArch64::LDRBBui:
720 case AArch64::LDRHHui:
721 case AArch64::LDRWui:
722 case AArch64::LDRXui:
723 // Unscaled instructions.
724 case AArch64::LDURBBi:
725 case AArch64::LDURHHi:
726 case AArch64::LDURWi:
727 case AArch64::LDURXi:
728 return true;
729 }
730}
731
733 unsigned Opc = MI.getOpcode();
734 switch (Opc) {
735 default:
736 return false;
737 // Scaled instructions.
738 case AArch64::STRSui:
739 case AArch64::STRDui:
740 case AArch64::STRQui:
741 case AArch64::STRXui:
742 case AArch64::STRWui:
743 case AArch64::STRHHui:
744 case AArch64::STRBBui:
745 case AArch64::LDRSui:
746 case AArch64::LDRDui:
747 case AArch64::LDRQui:
748 case AArch64::LDRXui:
749 case AArch64::LDRWui:
750 case AArch64::LDRHHui:
751 case AArch64::LDRBBui:
752 case AArch64::STGi:
753 case AArch64::STZGi:
754 case AArch64::ST2Gi:
755 case AArch64::STZ2Gi:
756 case AArch64::STGPi:
757 // Unscaled instructions.
758 case AArch64::STURSi:
759 case AArch64::STURDi:
760 case AArch64::STURQi:
761 case AArch64::STURWi:
762 case AArch64::STURXi:
763 case AArch64::LDURSi:
764 case AArch64::LDURDi:
765 case AArch64::LDURQi:
766 case AArch64::LDURWi:
767 case AArch64::LDURXi:
768 // Paired instructions.
769 case AArch64::LDPSi:
770 case AArch64::LDPSWi:
771 case AArch64::LDPDi:
772 case AArch64::LDPQi:
773 case AArch64::LDPWi:
774 case AArch64::LDPXi:
775 case AArch64::STPSi:
776 case AArch64::STPDi:
777 case AArch64::STPQi:
778 case AArch64::STPWi:
779 case AArch64::STPXi:
780 // Make sure this is a reg+imm (as opposed to an address reloc).
782 return false;
783
784 return true;
785 }
786}
787
788// Make sure this is a reg+reg Ld/St
789static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale) {
790 unsigned Opc = MI.getOpcode();
791 switch (Opc) {
792 default:
793 return false;
794 // Scaled instructions.
795 // TODO: Add more index address stores.
796 case AArch64::LDRBroX:
797 case AArch64::LDRBBroX:
798 case AArch64::LDRSBXroX:
799 case AArch64::LDRSBWroX:
800 Scale = 1;
801 return true;
802 case AArch64::LDRHroX:
803 case AArch64::LDRHHroX:
804 case AArch64::LDRSHXroX:
805 case AArch64::LDRSHWroX:
806 Scale = 2;
807 return true;
808 case AArch64::LDRWroX:
809 case AArch64::LDRSroX:
810 case AArch64::LDRSWroX:
811 Scale = 4;
812 return true;
813 case AArch64::LDRDroX:
814 case AArch64::LDRXroX:
815 Scale = 8;
816 return true;
817 case AArch64::LDRQroX:
818 Scale = 16;
819 return true;
820 }
821}
822
823static bool isRewritableImplicitDef(unsigned Opc) {
824 switch (Opc) {
825 default:
826 return false;
827 case AArch64::ORRWrs:
828 case AArch64::ADDWri:
829 return true;
830 }
831}
832
834AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
836 const LdStPairFlags &Flags) {
838 "Expected promotable zero stores.");
839
840 MachineBasicBlock::iterator E = I->getParent()->end();
842 // If NextI is the second of the two instructions to be merged, we need
843 // to skip one further. Either way we merge will invalidate the iterator,
844 // and we don't need to scan the new instruction, as it's a pairwise
845 // instruction, which we're not considering for further action anyway.
846 if (NextI == MergeMI)
847 NextI = next_nodbg(NextI, E);
848
849 unsigned Opc = I->getOpcode();
850 unsigned MergeMIOpc = MergeMI->getOpcode();
851 bool IsScaled = !TII->hasUnscaledLdStOffset(Opc);
852 bool IsMergedMIScaled = !TII->hasUnscaledLdStOffset(MergeMIOpc);
853 int OffsetStride = IsScaled ? TII->getMemScale(*I) : 1;
854 int MergeMIOffsetStride = IsMergedMIScaled ? TII->getMemScale(*MergeMI) : 1;
855
856 bool MergeForward = Flags.getMergeForward();
857 // Insert our new paired instruction after whichever of the paired
858 // instructions MergeForward indicates.
859 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
860 // Also based on MergeForward is from where we copy the base register operand
861 // so we get the flags compatible with the input code.
862 const MachineOperand &BaseRegOp =
863 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*MergeMI)
864 : AArch64InstrInfo::getLdStBaseOp(*I);
865
866 // Which register is Rt and which is Rt2 depends on the offset order.
867 int64_t IOffsetInBytes =
868 AArch64InstrInfo::getLdStOffsetOp(*I).getImm() * OffsetStride;
869 int64_t MIOffsetInBytes =
871 MergeMIOffsetStride;
872 // Select final offset based on the offset order.
873 int64_t OffsetImm;
874 if (IOffsetInBytes > MIOffsetInBytes)
875 OffsetImm = MIOffsetInBytes;
876 else
877 OffsetImm = IOffsetInBytes;
878
879 int NewOpcode = getMatchingWideOpcode(Opc);
880 bool FinalIsScaled = !TII->hasUnscaledLdStOffset(NewOpcode);
881
882 // Adjust final offset if the result opcode is a scaled store.
883 if (FinalIsScaled) {
884 int NewOffsetStride = FinalIsScaled ? TII->getMemScale(NewOpcode) : 1;
885 assert(((OffsetImm % NewOffsetStride) == 0) &&
886 "Offset should be a multiple of the store memory scale");
887 OffsetImm = OffsetImm / NewOffsetStride;
888 }
889
890 // Construct the new instruction.
891 DebugLoc DL = I->getDebugLoc();
892 MachineBasicBlock *MBB = I->getParent();
894 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
895 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
896 .add(BaseRegOp)
897 .addImm(OffsetImm)
898 .cloneMergedMemRefs({&*I, &*MergeMI})
899 .setMIFlags(I->mergeFlagsWith(*MergeMI));
900 (void)MIB;
901
902 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
903 LLVM_DEBUG(I->print(dbgs()));
904 LLVM_DEBUG(dbgs() << " ");
905 LLVM_DEBUG(MergeMI->print(dbgs()));
906 LLVM_DEBUG(dbgs() << " with instruction:\n ");
907 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
908 LLVM_DEBUG(dbgs() << "\n");
909
910 // Erase the old instructions.
911 I->eraseFromParent();
912 MergeMI->eraseFromParent();
913 return NextI;
914}
915
916// Apply Fn to all instructions between MI and the beginning of the block, until
917// a def for DefReg is reached. Returns true, iff Fn returns true for all
918// visited instructions. Stop after visiting Limit iterations.
920 const TargetRegisterInfo *TRI, unsigned Limit,
921 std::function<bool(MachineInstr &, bool)> &Fn) {
922 auto MBB = MI.getParent();
923 for (MachineInstr &I :
924 instructionsWithoutDebug(MI.getReverseIterator(), MBB->instr_rend())) {
925 if (!Limit)
926 return false;
927 --Limit;
928
929 bool isDef = any_of(I.operands(), [DefReg, TRI](MachineOperand &MOP) {
930 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
931 TRI->regsOverlap(MOP.getReg(), DefReg);
932 });
933 if (!Fn(I, isDef))
934 return false;
935 if (isDef)
936 break;
937 }
938 return true;
939}
940
942 const TargetRegisterInfo *TRI) {
943
944 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
945 if (MOP.isReg() && MOP.isKill())
946 Units.removeReg(MOP.getReg());
947
948 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
949 if (MOP.isReg() && !MOP.isKill())
950 Units.addReg(MOP.getReg());
951}
952
954AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
956 const LdStPairFlags &Flags) {
957 MachineBasicBlock::iterator E = I->getParent()->end();
959 // If NextI is the second of the two instructions to be merged, we need
960 // to skip one further. Either way we merge will invalidate the iterator,
961 // and we don't need to scan the new instruction, as it's a pairwise
962 // instruction, which we're not considering for further action anyway.
963 if (NextI == Paired)
964 NextI = next_nodbg(NextI, E);
965
966 int SExtIdx = Flags.getSExtIdx();
967 unsigned Opc =
968 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
969 bool IsUnscaled = TII->hasUnscaledLdStOffset(Opc);
970 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
971
972 bool MergeForward = Flags.getMergeForward();
973
974 std::optional<MCPhysReg> RenameReg = Flags.getRenameReg();
975 if (RenameReg) {
976 MCRegister RegToRename = getLdStRegOp(*I).getReg();
977 DefinedInBB.addReg(*RenameReg);
978
979 // Return the sub/super register for RenameReg, matching the size of
980 // OriginalReg.
981 auto GetMatchingSubReg =
982 [this, RenameReg](const TargetRegisterClass *C) -> MCPhysReg {
983 for (MCPhysReg SubOrSuper :
984 TRI->sub_and_superregs_inclusive(*RenameReg)) {
985 if (C->contains(SubOrSuper))
986 return SubOrSuper;
987 }
988 llvm_unreachable("Should have found matching sub or super register!");
989 };
990
991 std::function<bool(MachineInstr &, bool)> UpdateMIs =
992 [this, RegToRename, GetMatchingSubReg, MergeForward](MachineInstr &MI,
993 bool IsDef) {
994 if (IsDef) {
995 bool SeenDef = false;
996 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
997 MachineOperand &MOP = MI.getOperand(OpIdx);
998 // Rename the first explicit definition and all implicit
999 // definitions matching RegToRename.
1000 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1001 (!MergeForward || !SeenDef ||
1002 (MOP.isDef() && MOP.isImplicit())) &&
1003 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
1004 assert((MOP.isImplicit() ||
1005 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
1006 "Need renamable operands");
1007 Register MatchingReg;
1008 if (const TargetRegisterClass *RC =
1009 MI.getRegClassConstraint(OpIdx, TII, TRI))
1010 MatchingReg = GetMatchingSubReg(RC);
1011 else {
1012 if (!isRewritableImplicitDef(MI.getOpcode()))
1013 continue;
1014 MatchingReg = GetMatchingSubReg(
1015 TRI->getMinimalPhysRegClass(MOP.getReg()));
1016 }
1017 MOP.setReg(MatchingReg);
1018 SeenDef = true;
1019 }
1020 }
1021 } else {
1022 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
1023 MachineOperand &MOP = MI.getOperand(OpIdx);
1024 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1025 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
1026 assert((MOP.isImplicit() ||
1027 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
1028 "Need renamable operands");
1029 Register MatchingReg;
1030 if (const TargetRegisterClass *RC =
1031 MI.getRegClassConstraint(OpIdx, TII, TRI))
1032 MatchingReg = GetMatchingSubReg(RC);
1033 else
1034 MatchingReg = GetMatchingSubReg(
1035 TRI->getMinimalPhysRegClass(MOP.getReg()));
1036 assert(MatchingReg != AArch64::NoRegister &&
1037 "Cannot find matching regs for renaming");
1038 MOP.setReg(MatchingReg);
1039 }
1040 }
1041 }
1042 LLVM_DEBUG(dbgs() << "Renamed " << MI);
1043 return true;
1044 };
1045 forAllMIsUntilDef(MergeForward ? *I : *std::prev(Paired), RegToRename, TRI,
1046 UINT32_MAX, UpdateMIs);
1047
1048#if !defined(NDEBUG)
1049 // For forward merging store:
1050 // Make sure the register used for renaming is not used between the
1051 // paired instructions. That would trash the content before the new
1052 // paired instruction.
1053 MCPhysReg RegToCheck = *RenameReg;
1054 // For backward merging load:
1055 // Make sure the register being renamed is not used between the
1056 // paired instructions. That would trash the content after the new
1057 // paired instruction.
1058 if (!MergeForward)
1059 RegToCheck = RegToRename;
1060 for (auto &MI :
1062 MergeForward ? std::next(I) : I,
1063 MergeForward ? std::next(Paired) : Paired))
1064 assert(all_of(MI.operands(),
1065 [this, RegToCheck](const MachineOperand &MOP) {
1066 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1067 MOP.isUndef() ||
1068 !TRI->regsOverlap(MOP.getReg(), RegToCheck);
1069 }) &&
1070 "Rename register used between paired instruction, trashing the "
1071 "content");
1072#endif
1073 }
1074
1075 // Insert our new paired instruction after whichever of the paired
1076 // instructions MergeForward indicates.
1077 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
1078 // Also based on MergeForward is from where we copy the base register operand
1079 // so we get the flags compatible with the input code.
1080 const MachineOperand &BaseRegOp =
1081 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*Paired)
1082 : AArch64InstrInfo::getLdStBaseOp(*I);
1083
1085 int PairedOffset = AArch64InstrInfo::getLdStOffsetOp(*Paired).getImm();
1086 bool PairedIsUnscaled = TII->hasUnscaledLdStOffset(Paired->getOpcode());
1087 if (IsUnscaled != PairedIsUnscaled) {
1088 // We're trying to pair instructions that differ in how they are scaled. If
1089 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
1090 // the opposite (i.e., make Paired's offset unscaled).
1091 int MemSize = TII->getMemScale(*Paired);
1092 if (PairedIsUnscaled) {
1093 // If the unscaled offset isn't a multiple of the MemSize, we can't
1094 // pair the operations together.
1095 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
1096 "Offset should be a multiple of the stride!");
1097 PairedOffset /= MemSize;
1098 } else {
1099 PairedOffset *= MemSize;
1100 }
1101 }
1102
1103 // Which register is Rt and which is Rt2 depends on the offset order.
1104 // However, for pre load/stores the Rt should be the one of the pre
1105 // load/store.
1106 MachineInstr *RtMI, *Rt2MI;
1107 if (Offset == PairedOffset + OffsetStride &&
1109 RtMI = &*Paired;
1110 Rt2MI = &*I;
1111 // Here we swapped the assumption made for SExtIdx.
1112 // I.e., we turn ldp I, Paired into ldp Paired, I.
1113 // Update the index accordingly.
1114 if (SExtIdx != -1)
1115 SExtIdx = (SExtIdx + 1) % 2;
1116 } else {
1117 RtMI = &*I;
1118 Rt2MI = &*Paired;
1119 }
1120 int OffsetImm = AArch64InstrInfo::getLdStOffsetOp(*RtMI).getImm();
1121 // Scale the immediate offset, if necessary.
1122 if (TII->hasUnscaledLdStOffset(RtMI->getOpcode())) {
1123 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
1124 "Unscaled offset cannot be scaled.");
1125 OffsetImm /= TII->getMemScale(*RtMI);
1126 }
1127
1128 // Construct the new instruction.
1130 DebugLoc DL = I->getDebugLoc();
1131 MachineBasicBlock *MBB = I->getParent();
1132 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
1133 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
1134 MachineOperand &PairedRegOp = RtMI == &*Paired ? RegOp0 : RegOp1;
1135 // Kill flags may become invalid when moving stores for pairing.
1136 if (RegOp0.isUse()) {
1137 if (!MergeForward) {
1138 // Clear kill flags on store if moving upwards. Example:
1139 // STRWui kill %w0, ...
1140 // USE %w1
1141 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
1142 // We are about to move the store of w1, so its kill flag may become
1143 // invalid; not the case for w0.
1144 // Since w1 is used between the stores, the kill flag on w1 is cleared
1145 // after merging.
1146 // STPWi kill %w0, %w1, ...
1147 // USE %w1
1148 for (auto It = std::next(I); It != Paired && PairedRegOp.isKill(); ++It)
1149 if (It->readsRegister(PairedRegOp.getReg(), TRI))
1150 PairedRegOp.setIsKill(false);
1151 } else {
1152 // Clear kill flags of the first stores register. Example:
1153 // STRWui %w1, ...
1154 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
1155 // STRW %w0
1157 for (MachineInstr &MI : make_range(std::next(I), Paired))
1158 MI.clearRegisterKills(Reg, TRI);
1159 }
1160 }
1161
1162 unsigned int MatchPairOpcode = getMatchingPairOpcode(Opc);
1163 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(MatchPairOpcode));
1164
1165 // Adds the pre-index operand for pre-indexed ld/st pairs.
1166 if (AArch64InstrInfo::isPreLdSt(*RtMI))
1167 MIB.addReg(BaseRegOp.getReg(), RegState::Define);
1168
1169 MIB.add(RegOp0)
1170 .add(RegOp1)
1171 .add(BaseRegOp)
1172 .addImm(OffsetImm)
1173 .cloneMergedMemRefs({&*I, &*Paired})
1174 .setMIFlags(I->mergeFlagsWith(*Paired));
1175
1176 (void)MIB;
1177
1178 LLVM_DEBUG(
1179 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
1180 LLVM_DEBUG(I->print(dbgs()));
1181 LLVM_DEBUG(dbgs() << " ");
1182 LLVM_DEBUG(Paired->print(dbgs()));
1183 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1184 if (SExtIdx != -1) {
1185 // Generate the sign extension for the proper result of the ldp.
1186 // I.e., with X1, that would be:
1187 // %w1 = KILL %w1, implicit-def %x1
1188 // %x1 = SBFMXri killed %x1, 0, 31
1189 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
1190 // Right now, DstMO has the extended register, since it comes from an
1191 // extended opcode.
1192 Register DstRegX = DstMO.getReg();
1193 // Get the W variant of that register.
1194 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
1195 // Update the result of LDP to use the W instead of the X variant.
1196 DstMO.setReg(DstRegW);
1197 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1198 LLVM_DEBUG(dbgs() << "\n");
1199 // Make the machine verifier happy by providing a definition for
1200 // the X register.
1201 // Insert this definition right after the generated LDP, i.e., before
1202 // InsertionPoint.
1203 MachineInstrBuilder MIBKill =
1204 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
1205 .addReg(DstRegW)
1206 .addReg(DstRegX, RegState::Define);
1207 MIBKill->getOperand(2).setImplicit();
1208 // Create the sign extension.
1209 MachineInstrBuilder MIBSXTW =
1210 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
1211 .addReg(DstRegX)
1212 .addImm(0)
1213 .addImm(31);
1214 (void)MIBSXTW;
1215 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
1216 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
1217 } else {
1218 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1219 }
1220 LLVM_DEBUG(dbgs() << "\n");
1221
1222 if (MergeForward)
1223 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
1224 if (MOP.isReg() && MOP.isKill())
1225 DefinedInBB.addReg(MOP.getReg());
1226
1227 // Erase the old instructions.
1228 I->eraseFromParent();
1229 Paired->eraseFromParent();
1230
1231 return NextI;
1232}
1233
1235AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1238 next_nodbg(LoadI, LoadI->getParent()->end());
1239
1240 int LoadSize = TII->getMemScale(*LoadI);
1241 int StoreSize = TII->getMemScale(*StoreI);
1242 Register LdRt = getLdStRegOp(*LoadI).getReg();
1243 const MachineOperand &StMO = getLdStRegOp(*StoreI);
1244 Register StRt = getLdStRegOp(*StoreI).getReg();
1245 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1246
1247 assert((IsStoreXReg ||
1248 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1249 "Unexpected RegClass");
1250
1251 MachineInstr *BitExtMI;
1252 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1253 // Remove the load, if the destination register of the loads is the same
1254 // register for stored value.
1255 if (StRt == LdRt && LoadSize == 8) {
1256 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1257 LoadI->getIterator())) {
1258 if (MI.killsRegister(StRt, TRI)) {
1259 MI.clearRegisterKills(StRt, TRI);
1260 break;
1261 }
1262 }
1263 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1264 LLVM_DEBUG(LoadI->print(dbgs()));
1265 LLVM_DEBUG(dbgs() << "\n");
1266 LoadI->eraseFromParent();
1267 return NextI;
1268 }
1269 // Replace the load with a mov if the load and store are in the same size.
1270 BitExtMI =
1271 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1272 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1273 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
1274 .add(StMO)
1276 .setMIFlags(LoadI->getFlags());
1277 } else {
1278 // FIXME: Currently we disable this transformation in big-endian targets as
1279 // performance and correctness are verified only in little-endian.
1280 if (!Subtarget->isLittleEndian())
1281 return NextI;
1282 bool IsUnscaled = TII->hasUnscaledLdStOffset(*LoadI);
1283 assert(IsUnscaled == TII->hasUnscaledLdStOffset(*StoreI) &&
1284 "Unsupported ld/st match");
1285 assert(LoadSize <= StoreSize && "Invalid load size");
1286 int UnscaledLdOffset =
1287 IsUnscaled
1289 : AArch64InstrInfo::getLdStOffsetOp(*LoadI).getImm() * LoadSize;
1290 int UnscaledStOffset =
1291 IsUnscaled
1293 : AArch64InstrInfo::getLdStOffsetOp(*StoreI).getImm() * StoreSize;
1294 int Width = LoadSize * 8;
1295 Register DestReg =
1296 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1297 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1298 : LdRt;
1299
1300 assert((UnscaledLdOffset >= UnscaledStOffset &&
1301 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1302 "Invalid offset");
1303
1304 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1305 int Imms = Immr + Width - 1;
1306 if (UnscaledLdOffset == UnscaledStOffset) {
1307 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1308 | ((Immr) << 6) // immr
1309 | ((Imms) << 0) // imms
1310 ;
1311
1312 BitExtMI =
1313 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1314 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1315 DestReg)
1316 .add(StMO)
1317 .addImm(AndMaskEncoded)
1318 .setMIFlags(LoadI->getFlags());
1319 } else {
1320 BitExtMI =
1321 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1322 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1323 DestReg)
1324 .add(StMO)
1325 .addImm(Immr)
1326 .addImm(Imms)
1327 .setMIFlags(LoadI->getFlags());
1328 }
1329 }
1330
1331 // Clear kill flags between store and load.
1332 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1333 BitExtMI->getIterator()))
1334 if (MI.killsRegister(StRt, TRI)) {
1335 MI.clearRegisterKills(StRt, TRI);
1336 break;
1337 }
1338
1339 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1340 LLVM_DEBUG(StoreI->print(dbgs()));
1341 LLVM_DEBUG(dbgs() << " ");
1342 LLVM_DEBUG(LoadI->print(dbgs()));
1343 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1344 LLVM_DEBUG(StoreI->print(dbgs()));
1345 LLVM_DEBUG(dbgs() << " ");
1346 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1347 LLVM_DEBUG(dbgs() << "\n");
1348
1349 // Erase the old instructions.
1350 LoadI->eraseFromParent();
1351 return NextI;
1352}
1353
1354static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1355 // Convert the byte-offset used by unscaled into an "element" offset used
1356 // by the scaled pair load/store instructions.
1357 if (IsUnscaled) {
1358 // If the byte-offset isn't a multiple of the stride, there's no point
1359 // trying to match it.
1360 if (Offset % OffsetStride)
1361 return false;
1362 Offset /= OffsetStride;
1363 }
1364 return Offset <= 63 && Offset >= -64;
1365}
1366
1367// Do alignment, specialized to power of 2 and for signed ints,
1368// avoiding having to do a C-style cast from uint_64t to int when
1369// using alignTo from include/llvm/Support/MathExtras.h.
1370// FIXME: Move this function to include/MathExtras.h?
1371static int alignTo(int Num, int PowOf2) {
1372 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1373}
1374
1375static bool mayAlias(MachineInstr &MIa,
1377 AliasAnalysis *AA) {
1378 for (MachineInstr *MIb : MemInsns) {
1379 if (MIa.mayAlias(AA, *MIb, /*UseTBAA*/ false)) {
1380 LLVM_DEBUG(dbgs() << "Aliasing with: "; MIb->dump());
1381 return true;
1382 }
1383 }
1384
1385 LLVM_DEBUG(dbgs() << "No aliases found\n");
1386 return false;
1387}
1388
1389bool AArch64LoadStoreOpt::findMatchingStore(
1390 MachineBasicBlock::iterator I, unsigned Limit,
1392 MachineBasicBlock::iterator B = I->getParent()->begin();
1394 MachineInstr &LoadMI = *I;
1396
1397 // If the load is the first instruction in the block, there's obviously
1398 // not any matching store.
1399 if (MBBI == B)
1400 return false;
1401
1402 // Track which register units have been modified and used between the first
1403 // insn and the second insn.
1404 ModifiedRegUnits.clear();
1405 UsedRegUnits.clear();
1406
1407 unsigned Count = 0;
1408 do {
1409 MBBI = prev_nodbg(MBBI, B);
1410 MachineInstr &MI = *MBBI;
1411
1412 // Don't count transient instructions towards the search limit since there
1413 // may be different numbers of them if e.g. debug information is present.
1414 if (!MI.isTransient())
1415 ++Count;
1416
1417 // If the load instruction reads directly from the address to which the
1418 // store instruction writes and the stored value is not modified, we can
1419 // promote the load. Since we do not handle stores with pre-/post-index,
1420 // it's unnecessary to check if BaseReg is modified by the store itself.
1421 // Also we can't handle stores without an immediate offset operand,
1422 // while the operand might be the address for a global variable.
1423 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1426 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1427 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1428 StoreI = MBBI;
1429 return true;
1430 }
1431
1432 if (MI.isCall())
1433 return false;
1434
1435 // Update modified / uses register units.
1436 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1437
1438 // Otherwise, if the base register is modified, we have no match, so
1439 // return early.
1440 if (!ModifiedRegUnits.available(BaseReg))
1441 return false;
1442
1443 // If we encounter a store aliased with the load, return early.
1444 if (MI.mayStore() && LoadMI.mayAlias(AA, MI, /*UseTBAA*/ false))
1445 return false;
1446 } while (MBBI != B && Count < Limit);
1447 return false;
1448}
1449
1450static bool needsWinCFI(const MachineFunction *MF) {
1451 return MF->getTarget().getMCAsmInfo()->usesWindowsCFI() &&
1453}
1454
1455// Returns true if FirstMI and MI are candidates for merging or pairing.
1456// Otherwise, returns false.
1458 LdStPairFlags &Flags,
1459 const AArch64InstrInfo *TII) {
1460 // If this is volatile or if pairing is suppressed, not a candidate.
1461 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1462 return false;
1463
1464 // We should have already checked FirstMI for pair suppression and volatility.
1465 assert(!FirstMI.hasOrderedMemoryRef() &&
1466 !TII->isLdStPairSuppressed(FirstMI) &&
1467 "FirstMI shouldn't get here if either of these checks are true.");
1468
1469 if (needsWinCFI(MI.getMF()) && (MI.getFlag(MachineInstr::FrameSetup) ||
1471 return false;
1472
1473 unsigned OpcA = FirstMI.getOpcode();
1474 unsigned OpcB = MI.getOpcode();
1475
1476 // Opcodes match: If the opcodes are pre ld/st there is nothing more to check.
1477 if (OpcA == OpcB)
1478 return !AArch64InstrInfo::isPreLdSt(FirstMI);
1479
1480 // Two pre ld/st of different opcodes cannot be merged either
1482 return false;
1483
1484 // Try to match a sign-extended load/store with a zero-extended load/store.
1485 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1486 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1487 assert(IsValidLdStrOpc &&
1488 "Given Opc should be a Load or Store with an immediate");
1489 // OpcA will be the first instruction in the pair.
1490 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1491 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1492 return true;
1493 }
1494
1495 // If the second instruction isn't even a mergable/pairable load/store, bail
1496 // out.
1497 if (!PairIsValidLdStrOpc)
1498 return false;
1499
1500 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1501 // offsets.
1502 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1503 return false;
1504
1505 // The STR<S,D,Q,W,X>pre - STR<S,D,Q,W,X>ui and
1506 // LDR<S,D,Q,W,X,SW>pre-LDR<S,D,Q,W,X,SW>ui
1507 // are candidate pairs that can be merged.
1508 if (isPreLdStPairCandidate(FirstMI, MI))
1509 return true;
1510
1511 // Try to match an unscaled load/store with a scaled load/store.
1512 return TII->hasUnscaledLdStOffset(OpcA) != TII->hasUnscaledLdStOffset(OpcB) &&
1514
1515 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1516}
1517
1518static bool canRenameMOP(const MachineOperand &MOP,
1519 const TargetRegisterInfo *TRI) {
1520 if (MOP.isReg()) {
1521 auto *RegClass = TRI->getMinimalPhysRegClass(MOP.getReg());
1522 // Renaming registers with multiple disjunct sub-registers (e.g. the
1523 // result of a LD3) means that all sub-registers are renamed, potentially
1524 // impacting other instructions we did not check. Bail out.
1525 // Note that this relies on the structure of the AArch64 register file. In
1526 // particular, a subregister cannot be written without overwriting the
1527 // whole register.
1528 if (RegClass->HasDisjunctSubRegs) {
1529 LLVM_DEBUG(
1530 dbgs()
1531 << " Cannot rename operands with multiple disjunct subregisters ("
1532 << MOP << ")\n");
1533 return false;
1534 }
1535
1536 // We cannot rename arbitrary implicit-defs, the specific rule to rewrite
1537 // them must be known. For example, in ORRWrs the implicit-def
1538 // corresponds to the result register.
1539 if (MOP.isImplicit() && MOP.isDef()) {
1541 return false;
1542 return TRI->isSuperOrSubRegisterEq(
1543 MOP.getParent()->getOperand(0).getReg(), MOP.getReg());
1544 }
1545 }
1546 return MOP.isImplicit() ||
1547 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1548}
1549
1550static bool
1553 const TargetRegisterInfo *TRI) {
1554 if (!FirstMI.mayStore())
1555 return false;
1556
1557 // Check if we can find an unused register which we can use to rename
1558 // the register used by the first load/store.
1559
1560 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1561 // For now, we only rename if the store operand gets killed at the store.
1562 if (!getLdStRegOp(FirstMI).isKill() &&
1563 !any_of(FirstMI.operands(),
1564 [TRI, RegToRename](const MachineOperand &MOP) {
1565 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1566 MOP.isImplicit() && MOP.isKill() &&
1567 TRI->regsOverlap(RegToRename, MOP.getReg());
1568 })) {
1569 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI);
1570 return false;
1571 }
1572
1573 bool FoundDef = false;
1574
1575 // For each instruction between FirstMI and the previous def for RegToRename,
1576 // we
1577 // * check if we can rename RegToRename in this instruction
1578 // * collect the registers used and required register classes for RegToRename.
1579 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1580 bool IsDef) {
1581 LLVM_DEBUG(dbgs() << "Checking " << MI);
1582 // Currently we do not try to rename across frame-setup instructions.
1583 if (MI.getFlag(MachineInstr::FrameSetup)) {
1584 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1585 << "currently\n");
1586 return false;
1587 }
1588
1589 UsedInBetween.accumulate(MI);
1590
1591 // For a definition, check that we can rename the definition and exit the
1592 // loop.
1593 FoundDef = IsDef;
1594
1595 // For defs, check if we can rename the first def of RegToRename.
1596 if (FoundDef) {
1597 // For some pseudo instructions, we might not generate code in the end
1598 // (e.g. KILL) and we would end up without a correct def for the rename
1599 // register.
1600 // TODO: This might be overly conservative and we could handle those cases
1601 // in multiple ways:
1602 // 1. Insert an extra copy, to materialize the def.
1603 // 2. Skip pseudo-defs until we find an non-pseudo def.
1604 if (MI.isPseudo()) {
1605 LLVM_DEBUG(dbgs() << " Cannot rename pseudo/bundle instruction\n");
1606 return false;
1607 }
1608
1609 for (auto &MOP : MI.operands()) {
1610 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1611 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1612 continue;
1613 if (!canRenameMOP(MOP, TRI)) {
1614 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1615 return false;
1616 }
1617 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1618 }
1619 return true;
1620 } else {
1621 for (auto &MOP : MI.operands()) {
1622 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1623 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1624 continue;
1625
1626 if (!canRenameMOP(MOP, TRI)) {
1627 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1628 return false;
1629 }
1630 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1631 }
1632 }
1633 return true;
1634 };
1635
1636 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1637 return false;
1638
1639 if (!FoundDef) {
1640 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1641 return false;
1642 }
1643 return true;
1644}
1645
1646// We want to merge the second load into the first by rewriting the usages of
1647// the same reg between first (incl.) and second (excl.). We don't need to care
1648// about any insns before FirstLoad or after SecondLoad.
1649// 1. The second load writes new value into the same reg.
1650// - The renaming is impossible to impact later use of the reg.
1651// - The second load always trash the value written by the first load which
1652// means the reg must be killed before the second load.
1653// 2. The first load must be a def for the same reg so we don't need to look
1654// into anything before it.
1656 MachineInstr &FirstLoad, MachineInstr &SecondLoad,
1657 LiveRegUnits &UsedInBetween,
1659 const TargetRegisterInfo *TRI) {
1660 if (FirstLoad.isPseudo())
1661 return false;
1662
1663 UsedInBetween.accumulate(FirstLoad);
1664 auto RegToRename = getLdStRegOp(FirstLoad).getReg();
1665 bool Success = std::all_of(
1666 FirstLoad.getIterator(), SecondLoad.getIterator(),
1667 [&](MachineInstr &MI) {
1668 LLVM_DEBUG(dbgs() << "Checking " << MI);
1669 // Currently we do not try to rename across frame-setup instructions.
1670 if (MI.getFlag(MachineInstr::FrameSetup)) {
1671 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1672 << "currently\n");
1673 return false;
1674 }
1675
1676 for (auto &MOP : MI.operands()) {
1677 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1678 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1679 continue;
1680 if (!canRenameMOP(MOP, TRI)) {
1681 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1682 return false;
1683 }
1684 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1685 }
1686
1687 return true;
1688 });
1689 return Success;
1690}
1691
1692// Check if we can find a physical register for renaming \p Reg. This register
1693// must:
1694// * not be defined already in \p DefinedInBB; DefinedInBB must contain all
1695// defined registers up to the point where the renamed register will be used,
1696// * not used in \p UsedInBetween; UsedInBetween must contain all accessed
1697// registers in the range the rename register will be used,
1698// * is available in all used register classes (checked using RequiredClasses).
1699static std::optional<MCPhysReg> tryToFindRegisterToRename(
1700 const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB,
1701 LiveRegUnits &UsedInBetween,
1703 const TargetRegisterInfo *TRI) {
1705
1706 // Checks if any sub- or super-register of PR is callee saved.
1707 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1708 return any_of(TRI->sub_and_superregs_inclusive(PR),
1709 [&MF, TRI](MCPhysReg SubOrSuper) {
1710 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1711 });
1712 };
1713
1714 // Check if PR or one of its sub- or super-registers can be used for all
1715 // required register classes.
1716 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1717 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1718 return any_of(
1719 TRI->sub_and_superregs_inclusive(PR),
1720 [C](MCPhysReg SubOrSuper) { return C->contains(SubOrSuper); });
1721 });
1722 };
1723
1724 auto *RegClass = TRI->getMinimalPhysRegClass(Reg);
1725 for (const MCPhysReg &PR : *RegClass) {
1726 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1727 !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1728 CanBeUsedForAllClasses(PR)) {
1729 DefinedInBB.addReg(PR);
1730 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1731 << "\n");
1732 return {PR};
1733 }
1734 }
1735 LLVM_DEBUG(dbgs() << "No rename register found from "
1736 << TRI->getRegClassName(RegClass) << "\n");
1737 return std::nullopt;
1738}
1739
1740// For store pairs: returns a register from FirstMI to the beginning of the
1741// block that can be renamed.
1742// For load pairs: returns a register from FirstMI to MI that can be renamed.
1743static std::optional<MCPhysReg> findRenameRegForSameLdStRegPair(
1744 std::optional<bool> MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI,
1745 Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween,
1747 const TargetRegisterInfo *TRI) {
1748 std::optional<MCPhysReg> RenameReg;
1749 if (!DebugCounter::shouldExecute(RegRenamingCounter))
1750 return RenameReg;
1751
1752 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1753 MachineFunction &MF = *FirstMI.getParent()->getParent();
1754 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1755 return RenameReg;
1756
1757 const bool IsLoad = FirstMI.mayLoad();
1758
1759 if (!MaybeCanRename) {
1760 if (IsLoad)
1761 MaybeCanRename = {canRenameUntilSecondLoad(FirstMI, MI, UsedInBetween,
1762 RequiredClasses, TRI)};
1763 else
1764 MaybeCanRename = {
1765 canRenameUpToDef(FirstMI, UsedInBetween, RequiredClasses, TRI)};
1766 }
1767
1768 if (*MaybeCanRename) {
1769 RenameReg = tryToFindRegisterToRename(MF, Reg, DefinedInBB, UsedInBetween,
1770 RequiredClasses, TRI);
1771 }
1772 return RenameReg;
1773}
1774
1775/// Scan the instructions looking for a load/store that can be combined with the
1776/// current instruction into a wider equivalent or a load/store pair.
1778AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1779 LdStPairFlags &Flags, unsigned Limit,
1780 bool FindNarrowMerge) {
1781 MachineBasicBlock::iterator E = I->getParent()->end();
1783 MachineBasicBlock::iterator MBBIWithRenameReg;
1784 MachineInstr &FirstMI = *I;
1785 MBBI = next_nodbg(MBBI, E);
1786
1787 bool MayLoad = FirstMI.mayLoad();
1788 bool IsUnscaled = TII->hasUnscaledLdStOffset(FirstMI);
1789 Register Reg = getLdStRegOp(FirstMI).getReg();
1790 Register BaseReg = AArch64InstrInfo::getLdStBaseOp(FirstMI).getReg();
1792 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1793 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1794
1795 std::optional<bool> MaybeCanRename;
1796 if (!EnableRenaming)
1797 MaybeCanRename = {false};
1798
1800 LiveRegUnits UsedInBetween;
1801 UsedInBetween.init(*TRI);
1802
1803 Flags.clearRenameReg();
1804
1805 // Track which register units have been modified and used between the first
1806 // insn (inclusive) and the second insn.
1807 ModifiedRegUnits.clear();
1808 UsedRegUnits.clear();
1809
1810 // Remember any instructions that read/write memory between FirstMI and MI.
1812
1813 LLVM_DEBUG(dbgs() << "Find match for: "; FirstMI.dump());
1814 for (unsigned Count = 0; MBBI != E && Count < Limit;
1815 MBBI = next_nodbg(MBBI, E)) {
1816 MachineInstr &MI = *MBBI;
1817 LLVM_DEBUG(dbgs() << "Analysing 2nd insn: "; MI.dump());
1818
1819 UsedInBetween.accumulate(MI);
1820
1821 // Don't count transient instructions towards the search limit since there
1822 // may be different numbers of them if e.g. debug information is present.
1823 if (!MI.isTransient())
1824 ++Count;
1825
1826 Flags.setSExtIdx(-1);
1827 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1829 assert(MI.mayLoadOrStore() && "Expected memory operation.");
1830 // If we've found another instruction with the same opcode, check to see
1831 // if the base and offset are compatible with our starting instruction.
1832 // These instructions all have scaled immediate operands, so we just
1833 // check for +1/-1. Make sure to check the new instruction offset is
1834 // actually an immediate and not a symbolic reference destined for
1835 // a relocation.
1838 bool MIIsUnscaled = TII->hasUnscaledLdStOffset(MI);
1839 if (IsUnscaled != MIIsUnscaled) {
1840 // We're trying to pair instructions that differ in how they are scaled.
1841 // If FirstMI is scaled then scale the offset of MI accordingly.
1842 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1843 int MemSize = TII->getMemScale(MI);
1844 if (MIIsUnscaled) {
1845 // If the unscaled offset isn't a multiple of the MemSize, we can't
1846 // pair the operations together: bail and keep looking.
1847 if (MIOffset % MemSize) {
1848 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1849 UsedRegUnits, TRI);
1850 MemInsns.push_back(&MI);
1851 continue;
1852 }
1853 MIOffset /= MemSize;
1854 } else {
1855 MIOffset *= MemSize;
1856 }
1857 }
1858
1859 bool IsPreLdSt = isPreLdStPairCandidate(FirstMI, MI);
1860
1861 if (BaseReg == MIBaseReg) {
1862 // If the offset of the second ld/st is not equal to the size of the
1863 // destination register it can’t be paired with a pre-index ld/st
1864 // pair. Additionally if the base reg is used or modified the operations
1865 // can't be paired: bail and keep looking.
1866 if (IsPreLdSt) {
1867 bool IsOutOfBounds = MIOffset != TII->getMemScale(MI);
1868 bool IsBaseRegUsed = !UsedRegUnits.available(
1870 bool IsBaseRegModified = !ModifiedRegUnits.available(
1872 // If the stored value and the address of the second instruction is
1873 // the same, it needs to be using the updated register and therefore
1874 // it must not be folded.
1875 bool IsMIRegTheSame =
1876 TRI->regsOverlap(getLdStRegOp(MI).getReg(),
1878 if (IsOutOfBounds || IsBaseRegUsed || IsBaseRegModified ||
1879 IsMIRegTheSame) {
1880 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1881 UsedRegUnits, TRI);
1882 MemInsns.push_back(&MI);
1883 continue;
1884 }
1885 } else {
1886 if ((Offset != MIOffset + OffsetStride) &&
1887 (Offset + OffsetStride != MIOffset)) {
1888 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1889 UsedRegUnits, TRI);
1890 MemInsns.push_back(&MI);
1891 continue;
1892 }
1893 }
1894
1895 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1896 if (FindNarrowMerge) {
1897 // If the alignment requirements of the scaled wide load/store
1898 // instruction can't express the offset of the scaled narrow input,
1899 // bail and keep looking. For promotable zero stores, allow only when
1900 // the stored value is the same (i.e., WZR).
1901 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1902 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1903 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1904 UsedRegUnits, TRI);
1905 MemInsns.push_back(&MI);
1906 continue;
1907 }
1908 } else {
1909 // Pairwise instructions have a 7-bit signed offset field. Single
1910 // insns have a 12-bit unsigned offset field. If the resultant
1911 // immediate offset of merging these instructions is out of range for
1912 // a pairwise instruction, bail and keep looking.
1913 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1914 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1915 UsedRegUnits, TRI);
1916 MemInsns.push_back(&MI);
1917 LLVM_DEBUG(dbgs() << "Offset doesn't fit in immediate, "
1918 << "keep looking.\n");
1919 continue;
1920 }
1921 // If the alignment requirements of the paired (scaled) instruction
1922 // can't express the offset of the unscaled input, bail and keep
1923 // looking.
1924 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1925 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1926 UsedRegUnits, TRI);
1927 MemInsns.push_back(&MI);
1929 << "Offset doesn't fit due to alignment requirements, "
1930 << "keep looking.\n");
1931 continue;
1932 }
1933 }
1934
1935 // If the BaseReg has been modified, then we cannot do the optimization.
1936 // For example, in the following pattern
1937 // ldr x1 [x2]
1938 // ldr x2 [x3]
1939 // ldr x4 [x2, #8],
1940 // the first and third ldr cannot be converted to ldp x1, x4, [x2]
1941 if (!ModifiedRegUnits.available(BaseReg))
1942 return E;
1943
1944 const bool SameLoadReg = MayLoad && TRI->isSuperOrSubRegisterEq(
1945 Reg, getLdStRegOp(MI).getReg());
1946
1947 // If the Rt of the second instruction (destination register of the
1948 // load) was not modified or used between the two instructions and none
1949 // of the instructions between the second and first alias with the
1950 // second, we can combine the second into the first.
1951 bool RtNotModified =
1952 ModifiedRegUnits.available(getLdStRegOp(MI).getReg());
1953 bool RtNotUsed = !(MI.mayLoad() && !SameLoadReg &&
1954 !UsedRegUnits.available(getLdStRegOp(MI).getReg()));
1955
1956 LLVM_DEBUG(dbgs() << "Checking, can combine 2nd into 1st insn:\n"
1957 << "Reg '" << getLdStRegOp(MI) << "' not modified: "
1958 << (RtNotModified ? "true" : "false") << "\n"
1959 << "Reg '" << getLdStRegOp(MI) << "' not used: "
1960 << (RtNotUsed ? "true" : "false") << "\n");
1961
1962 if (RtNotModified && RtNotUsed && !mayAlias(MI, MemInsns, AA)) {
1963 // For pairs loading into the same reg, try to find a renaming
1964 // opportunity to allow the renaming of Reg between FirstMI and MI
1965 // and combine MI into FirstMI; otherwise bail and keep looking.
1966 if (SameLoadReg) {
1967 std::optional<MCPhysReg> RenameReg =
1968 findRenameRegForSameLdStRegPair(MaybeCanRename, FirstMI, MI,
1969 Reg, DefinedInBB, UsedInBetween,
1970 RequiredClasses, TRI);
1971 if (!RenameReg) {
1972 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1973 UsedRegUnits, TRI);
1974 MemInsns.push_back(&MI);
1975 LLVM_DEBUG(dbgs() << "Can't find reg for renaming, "
1976 << "keep looking.\n");
1977 continue;
1978 }
1979 Flags.setRenameReg(*RenameReg);
1980 }
1981
1982 Flags.setMergeForward(false);
1983 if (!SameLoadReg)
1984 Flags.clearRenameReg();
1985 return MBBI;
1986 }
1987
1988 // Likewise, if the Rt of the first instruction is not modified or used
1989 // between the two instructions and none of the instructions between the
1990 // first and the second alias with the first, we can combine the first
1991 // into the second.
1992 RtNotModified = !(
1993 MayLoad && !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg()));
1994
1995 LLVM_DEBUG(dbgs() << "Checking, can combine 1st into 2nd insn:\n"
1996 << "Reg '" << getLdStRegOp(FirstMI)
1997 << "' not modified: "
1998 << (RtNotModified ? "true" : "false") << "\n");
1999
2000 if (RtNotModified && !mayAlias(FirstMI, MemInsns, AA)) {
2001 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
2002 Flags.setMergeForward(true);
2003 Flags.clearRenameReg();
2004 return MBBI;
2005 }
2006
2007 std::optional<MCPhysReg> RenameReg = findRenameRegForSameLdStRegPair(
2008 MaybeCanRename, FirstMI, MI, Reg, DefinedInBB, UsedInBetween,
2009 RequiredClasses, TRI);
2010 if (RenameReg) {
2011 Flags.setMergeForward(true);
2012 Flags.setRenameReg(*RenameReg);
2013 MBBIWithRenameReg = MBBI;
2014 }
2015 }
2016 LLVM_DEBUG(dbgs() << "Unable to combine these instructions due to "
2017 << "interference in between, keep looking.\n");
2018 }
2019 }
2020
2021 if (Flags.getRenameReg())
2022 return MBBIWithRenameReg;
2023
2024 // If the instruction wasn't a matching load or store. Stop searching if we
2025 // encounter a call instruction that might modify memory.
2026 if (MI.isCall()) {
2027 LLVM_DEBUG(dbgs() << "Found a call, stop looking.\n");
2028 return E;
2029 }
2030
2031 // Update modified / uses register units.
2032 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2033
2034 // Otherwise, if the base register is modified, we have no match, so
2035 // return early.
2036 if (!ModifiedRegUnits.available(BaseReg)) {
2037 LLVM_DEBUG(dbgs() << "Base reg is modified, stop looking.\n");
2038 return E;
2039 }
2040
2041 // Update list of instructions that read/write memory.
2042 if (MI.mayLoadOrStore())
2043 MemInsns.push_back(&MI);
2044 }
2045 return E;
2046}
2047
2050 assert((MI.getOpcode() == AArch64::SUBXri ||
2051 MI.getOpcode() == AArch64::ADDXri) &&
2052 "Expected a register update instruction");
2053 auto End = MI.getParent()->end();
2054 if (MaybeCFI == End ||
2055 MaybeCFI->getOpcode() != TargetOpcode::CFI_INSTRUCTION ||
2056 !(MI.getFlag(MachineInstr::FrameSetup) ||
2057 MI.getFlag(MachineInstr::FrameDestroy)) ||
2058 MI.getOperand(0).getReg() != AArch64::SP)
2059 return End;
2060
2061 const MachineFunction &MF = *MI.getParent()->getParent();
2062 unsigned CFIIndex = MaybeCFI->getOperand(0).getCFIIndex();
2063 const MCCFIInstruction &CFI = MF.getFrameInstructions()[CFIIndex];
2064 switch (CFI.getOperation()) {
2067 return MaybeCFI;
2068 default:
2069 return End;
2070 }
2071}
2072
2074AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
2076 bool IsPreIdx) {
2077 assert((Update->getOpcode() == AArch64::ADDXri ||
2078 Update->getOpcode() == AArch64::SUBXri) &&
2079 "Unexpected base register update instruction to merge!");
2080 MachineBasicBlock::iterator E = I->getParent()->end();
2082
2083 // If updating the SP and the following instruction is CFA offset related CFI
2084 // instruction move it after the merged instruction.
2086 IsPreIdx ? maybeMoveCFI(*Update, next_nodbg(Update, E)) : E;
2087
2088 // Return the instruction following the merged instruction, which is
2089 // the instruction following our unmerged load. Unless that's the add/sub
2090 // instruction we're merging, in which case it's the one after that.
2091 if (NextI == Update)
2092 NextI = next_nodbg(NextI, E);
2093
2094 int Value = Update->getOperand(2).getImm();
2095 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
2096 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
2097 if (Update->getOpcode() == AArch64::SUBXri)
2098 Value = -Value;
2099
2100 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
2103 int Scale, MinOffset, MaxOffset;
2104 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
2106 // Non-paired instruction.
2107 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2108 .add(Update->getOperand(0))
2109 .add(getLdStRegOp(*I))
2111 .addImm(Value / Scale)
2112 .setMemRefs(I->memoperands())
2113 .setMIFlags(I->mergeFlagsWith(*Update));
2114 } else {
2115 // Paired instruction.
2116 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2117 .add(Update->getOperand(0))
2118 .add(getLdStRegOp(*I, 0))
2119 .add(getLdStRegOp(*I, 1))
2121 .addImm(Value / Scale)
2122 .setMemRefs(I->memoperands())
2123 .setMIFlags(I->mergeFlagsWith(*Update));
2124 }
2125 if (CFI != E) {
2126 MachineBasicBlock *MBB = I->getParent();
2127 MBB->splice(std::next(MIB.getInstr()->getIterator()), MBB, CFI);
2128 }
2129
2130 if (IsPreIdx) {
2131 ++NumPreFolded;
2132 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
2133 } else {
2134 ++NumPostFolded;
2135 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
2136 }
2137 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2138 LLVM_DEBUG(I->print(dbgs()));
2139 LLVM_DEBUG(dbgs() << " ");
2140 LLVM_DEBUG(Update->print(dbgs()));
2141 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2142 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
2143 LLVM_DEBUG(dbgs() << "\n");
2144
2145 // Erase the old instructions for the block.
2146 I->eraseFromParent();
2147 Update->eraseFromParent();
2148
2149 return NextI;
2150}
2151
2153AArch64LoadStoreOpt::mergeConstOffsetInsn(MachineBasicBlock::iterator I,
2155 unsigned Offset, int Scale) {
2156 assert((Update->getOpcode() == AArch64::MOVKWi) &&
2157 "Unexpected const mov instruction to merge!");
2158 MachineBasicBlock::iterator E = I->getParent()->end();
2160 MachineBasicBlock::iterator PrevI = prev_nodbg(Update, E);
2161 MachineInstr &MemMI = *I;
2162 unsigned Mask = (1 << 12) * Scale - 1;
2163 unsigned Low = Offset & Mask;
2164 unsigned High = Offset - Low;
2167 MachineInstrBuilder AddMIB, MemMIB;
2168
2169 // Add IndexReg, BaseReg, High (the BaseReg may be SP)
2170 AddMIB =
2171 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(AArch64::ADDXri))
2172 .addDef(IndexReg)
2173 .addUse(BaseReg)
2174 .addImm(High >> 12) // shifted value
2175 .addImm(12); // shift 12
2176 (void)AddMIB;
2177 // Ld/St DestReg, IndexReg, Imm12
2178 unsigned NewOpc = getBaseAddressOpcode(I->getOpcode());
2179 MemMIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2180 .add(getLdStRegOp(MemMI))
2182 .addImm(Low / Scale)
2183 .setMemRefs(I->memoperands())
2184 .setMIFlags(I->mergeFlagsWith(*Update));
2185 (void)MemMIB;
2186
2187 ++NumConstOffsetFolded;
2188 LLVM_DEBUG(dbgs() << "Creating base address load/store.\n");
2189 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2190 LLVM_DEBUG(PrevI->print(dbgs()));
2191 LLVM_DEBUG(dbgs() << " ");
2192 LLVM_DEBUG(Update->print(dbgs()));
2193 LLVM_DEBUG(dbgs() << " ");
2194 LLVM_DEBUG(I->print(dbgs()));
2195 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2196 LLVM_DEBUG(((MachineInstr *)AddMIB)->print(dbgs()));
2197 LLVM_DEBUG(dbgs() << " ");
2198 LLVM_DEBUG(((MachineInstr *)MemMIB)->print(dbgs()));
2199 LLVM_DEBUG(dbgs() << "\n");
2200
2201 // Erase the old instructions for the block.
2202 I->eraseFromParent();
2203 PrevI->eraseFromParent();
2204 Update->eraseFromParent();
2205
2206 return NextI;
2207}
2208
2209bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
2211 unsigned BaseReg, int Offset) {
2212 switch (MI.getOpcode()) {
2213 default:
2214 break;
2215 case AArch64::SUBXri:
2216 case AArch64::ADDXri:
2217 // Make sure it's a vanilla immediate operand, not a relocation or
2218 // anything else we can't handle.
2219 if (!MI.getOperand(2).isImm())
2220 break;
2221 // Watch out for 1 << 12 shifted value.
2222 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
2223 break;
2224
2225 // The update instruction source and destination register must be the
2226 // same as the load/store base register.
2227 if (MI.getOperand(0).getReg() != BaseReg ||
2228 MI.getOperand(1).getReg() != BaseReg)
2229 break;
2230
2231 int UpdateOffset = MI.getOperand(2).getImm();
2232 if (MI.getOpcode() == AArch64::SUBXri)
2233 UpdateOffset = -UpdateOffset;
2234
2235 // The immediate must be a multiple of the scaling factor of the pre/post
2236 // indexed instruction.
2237 int Scale, MinOffset, MaxOffset;
2238 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
2239 if (UpdateOffset % Scale != 0)
2240 break;
2241
2242 // Scaled offset must fit in the instruction immediate.
2243 int ScaledOffset = UpdateOffset / Scale;
2244 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
2245 break;
2246
2247 // If we have a non-zero Offset, we check that it matches the amount
2248 // we're adding to the register.
2249 if (!Offset || Offset == UpdateOffset)
2250 return true;
2251 break;
2252 }
2253 return false;
2254}
2255
2256bool AArch64LoadStoreOpt::isMatchingMovConstInsn(MachineInstr &MemMI,
2258 unsigned IndexReg,
2259 unsigned &Offset) {
2260 // The update instruction source and destination register must be the
2261 // same as the load/store index register.
2262 if (MI.getOpcode() == AArch64::MOVKWi &&
2263 TRI->isSuperOrSubRegisterEq(IndexReg, MI.getOperand(1).getReg())) {
2264
2265 // movz + movk hold a large offset of a Ld/St instruction.
2266 MachineBasicBlock::iterator B = MI.getParent()->begin();
2268 // Skip the scene when the MI is the first instruction of a block.
2269 if (MBBI == B)
2270 return false;
2271 MBBI = prev_nodbg(MBBI, B);
2272 MachineInstr &MovzMI = *MBBI;
2273 if (MovzMI.getOpcode() == AArch64::MOVZWi) {
2274 unsigned Low = MovzMI.getOperand(1).getImm();
2275 unsigned High = MI.getOperand(2).getImm() << MI.getOperand(3).getImm();
2276 Offset = High + Low;
2277 // 12-bit optionally shifted immediates are legal for adds.
2278 return Offset >> 24 == 0;
2279 }
2280 }
2281 return false;
2282}
2283
2284MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
2285 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
2286 MachineBasicBlock::iterator E = I->getParent()->end();
2287 MachineInstr &MemMI = *I;
2289
2291 int MIUnscaledOffset = AArch64InstrInfo::getLdStOffsetOp(MemMI).getImm() *
2292 TII->getMemScale(MemMI);
2293
2294 // Scan forward looking for post-index opportunities. Updating instructions
2295 // can't be formed if the memory instruction doesn't have the offset we're
2296 // looking for.
2297 if (MIUnscaledOffset != UnscaledOffset)
2298 return E;
2299
2300 // If the base register overlaps a source/destination register, we can't
2301 // merge the update. This does not apply to tag store instructions which
2302 // ignore the address part of the source register.
2303 // This does not apply to STGPi as well, which does not have unpredictable
2304 // behavior in this case unlike normal stores, and always performs writeback
2305 // after reading the source register value.
2306 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
2307 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2308 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2309 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2310 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2311 return E;
2312 }
2313 }
2314
2315 // Track which register units have been modified and used between the first
2316 // insn (inclusive) and the second insn.
2317 ModifiedRegUnits.clear();
2318 UsedRegUnits.clear();
2319 MBBI = next_nodbg(MBBI, E);
2320
2321 // We can't post-increment the stack pointer if any instruction between
2322 // the memory access (I) and the increment (MBBI) can access the memory
2323 // region defined by [SP, MBBI].
2324 const bool BaseRegSP = BaseReg == AArch64::SP;
2325 if (BaseRegSP && needsWinCFI(I->getMF())) {
2326 // FIXME: For now, we always block the optimization over SP in windows
2327 // targets as it requires to adjust the unwind/debug info, messing up
2328 // the unwind info can actually cause a miscompile.
2329 return E;
2330 }
2331
2332 for (unsigned Count = 0; MBBI != E && Count < Limit;
2333 MBBI = next_nodbg(MBBI, E)) {
2334 MachineInstr &MI = *MBBI;
2335
2336 // Don't count transient instructions towards the search limit since there
2337 // may be different numbers of them if e.g. debug information is present.
2338 if (!MI.isTransient())
2339 ++Count;
2340
2341 // If we found a match, return it.
2342 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
2343 return MBBI;
2344
2345 // Update the status of what the instruction clobbered and used.
2346 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2347
2348 // Otherwise, if the base register is used or modified, we have no match, so
2349 // return early.
2350 // If we are optimizing SP, do not allow instructions that may load or store
2351 // in between the load and the optimized value update.
2352 if (!ModifiedRegUnits.available(BaseReg) ||
2353 !UsedRegUnits.available(BaseReg) ||
2354 (BaseRegSP && MBBI->mayLoadOrStore()))
2355 return E;
2356 }
2357 return E;
2358}
2359
2360MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
2361 MachineBasicBlock::iterator I, unsigned Limit) {
2362 MachineBasicBlock::iterator B = I->getParent()->begin();
2363 MachineBasicBlock::iterator E = I->getParent()->end();
2364 MachineInstr &MemMI = *I;
2366 MachineFunction &MF = *MemMI.getMF();
2367
2370
2371 // If the load/store is the first instruction in the block, there's obviously
2372 // not any matching update. Ditto if the memory offset isn't zero.
2373 if (MBBI == B || Offset != 0)
2374 return E;
2375 // If the base register overlaps a destination register, we can't
2376 // merge the update.
2377 if (!isTagStore(MemMI)) {
2378 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2379 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2380 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2381 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2382 return E;
2383 }
2384 }
2385
2386 const bool BaseRegSP = BaseReg == AArch64::SP;
2387 if (BaseRegSP && needsWinCFI(I->getMF())) {
2388 // FIXME: For now, we always block the optimization over SP in windows
2389 // targets as it requires to adjust the unwind/debug info, messing up
2390 // the unwind info can actually cause a miscompile.
2391 return E;
2392 }
2393
2394 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2395 unsigned RedZoneSize =
2396 Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
2397
2398 // Track which register units have been modified and used between the first
2399 // insn (inclusive) and the second insn.
2400 ModifiedRegUnits.clear();
2401 UsedRegUnits.clear();
2402 unsigned Count = 0;
2403 bool MemAcessBeforeSPPreInc = false;
2404 do {
2405 MBBI = prev_nodbg(MBBI, B);
2406 MachineInstr &MI = *MBBI;
2407
2408 // Don't count transient instructions towards the search limit since there
2409 // may be different numbers of them if e.g. debug information is present.
2410 if (!MI.isTransient())
2411 ++Count;
2412
2413 // If we found a match, return it.
2414 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset)) {
2415 // Check that the update value is within our red zone limit (which may be
2416 // zero).
2417 if (MemAcessBeforeSPPreInc && MBBI->getOperand(2).getImm() > RedZoneSize)
2418 return E;
2419 return MBBI;
2420 }
2421
2422 // Update the status of what the instruction clobbered and used.
2423 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2424
2425 // Otherwise, if the base register is used or modified, we have no match, so
2426 // return early.
2427 if (!ModifiedRegUnits.available(BaseReg) ||
2428 !UsedRegUnits.available(BaseReg))
2429 return E;
2430 // Keep track if we have a memory access before an SP pre-increment, in this
2431 // case we need to validate later that the update amount respects the red
2432 // zone.
2433 if (BaseRegSP && MBBI->mayLoadOrStore())
2434 MemAcessBeforeSPPreInc = true;
2435 } while (MBBI != B && Count < Limit);
2436 return E;
2437}
2438
2440AArch64LoadStoreOpt::findMatchingConstOffsetBackward(
2441 MachineBasicBlock::iterator I, unsigned Limit, unsigned &Offset) {
2442 MachineBasicBlock::iterator B = I->getParent()->begin();
2443 MachineBasicBlock::iterator E = I->getParent()->end();
2444 MachineInstr &MemMI = *I;
2446
2447 // If the load is the first instruction in the block, there's obviously
2448 // not any matching load or store.
2449 if (MBBI == B)
2450 return E;
2451
2452 // Make sure the IndexReg is killed and the shift amount is zero.
2453 // TODO: Relex this restriction to extend, simplify processing now.
2454 if (!AArch64InstrInfo::getLdStOffsetOp(MemMI).isKill() ||
2456 (AArch64InstrInfo::getLdStAmountOp(MemMI).getImm() != 0))
2457 return E;
2458
2460
2461 // Track which register units have been modified and used between the first
2462 // insn (inclusive) and the second insn.
2463 ModifiedRegUnits.clear();
2464 UsedRegUnits.clear();
2465 unsigned Count = 0;
2466 do {
2467 MBBI = prev_nodbg(MBBI, B);
2468 MachineInstr &MI = *MBBI;
2469
2470 // Don't count transient instructions towards the search limit since there
2471 // may be different numbers of them if e.g. debug information is present.
2472 if (!MI.isTransient())
2473 ++Count;
2474
2475 // If we found a match, return it.
2476 if (isMatchingMovConstInsn(*I, MI, IndexReg, Offset)) {
2477 return MBBI;
2478 }
2479
2480 // Update the status of what the instruction clobbered and used.
2481 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2482
2483 // Otherwise, if the index register is used or modified, we have no match,
2484 // so return early.
2485 if (!ModifiedRegUnits.available(IndexReg) ||
2486 !UsedRegUnits.available(IndexReg))
2487 return E;
2488
2489 } while (MBBI != B && Count < Limit);
2490 return E;
2491}
2492
2493bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
2495 MachineInstr &MI = *MBBI;
2496 // If this is a volatile load, don't mess with it.
2497 if (MI.hasOrderedMemoryRef())
2498 return false;
2499
2500 if (needsWinCFI(MI.getMF()) && MI.getFlag(MachineInstr::FrameDestroy))
2501 return false;
2502
2503 // Make sure this is a reg+imm.
2504 // FIXME: It is possible to extend it to handle reg+reg cases.
2506 return false;
2507
2508 // Look backward up to LdStLimit instructions.
2510 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
2511 ++NumLoadsFromStoresPromoted;
2512 // Promote the load. Keeping the iterator straight is a
2513 // pain, so we let the merge routine tell us what the next instruction
2514 // is after it's done mucking about.
2515 MBBI = promoteLoadFromStore(MBBI, StoreI);
2516 return true;
2517 }
2518 return false;
2519}
2520
2521// Merge adjacent zero stores into a wider store.
2522bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
2524 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
2525 MachineInstr &MI = *MBBI;
2526 MachineBasicBlock::iterator E = MI.getParent()->end();
2527
2528 if (!TII->isCandidateToMergeOrPair(MI))
2529 return false;
2530
2531 // Look ahead up to LdStLimit instructions for a mergable instruction.
2532 LdStPairFlags Flags;
2534 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
2535 if (MergeMI != E) {
2536 ++NumZeroStoresPromoted;
2537
2538 // Keeping the iterator straight is a pain, so we let the merge routine tell
2539 // us what the next instruction is after it's done mucking about.
2540 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
2541 return true;
2542 }
2543 return false;
2544}
2545
2546// Find loads and stores that can be merged into a single load or store pair
2547// instruction.
2548bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
2549 MachineInstr &MI = *MBBI;
2550 MachineBasicBlock::iterator E = MI.getParent()->end();
2551
2552 if (!TII->isCandidateToMergeOrPair(MI))
2553 return false;
2554
2555 // If disable-ldp feature is opted, do not emit ldp.
2556 if (MI.mayLoad() && Subtarget->hasDisableLdp())
2557 return false;
2558
2559 // If disable-stp feature is opted, do not emit stp.
2560 if (MI.mayStore() && Subtarget->hasDisableStp())
2561 return false;
2562
2563 // Early exit if the offset is not possible to match. (6 bits of positive
2564 // range, plus allow an extra one in case we find a later insn that matches
2565 // with Offset-1)
2566 bool IsUnscaled = TII->hasUnscaledLdStOffset(MI);
2568 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
2569 // Allow one more for offset.
2570 if (Offset > 0)
2571 Offset -= OffsetStride;
2572 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
2573 return false;
2574
2575 // Look ahead up to LdStLimit instructions for a pairable instruction.
2576 LdStPairFlags Flags;
2578 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
2579 if (Paired != E) {
2580 // Keeping the iterator straight is a pain, so we let the merge routine tell
2581 // us what the next instruction is after it's done mucking about.
2582 auto Prev = std::prev(MBBI);
2583
2584 // Fetch the memoperand of the load/store that is a candidate for
2585 // combination.
2587 MI.memoperands_empty() ? nullptr : MI.memoperands().front();
2588
2589 // If a load/store arrives and ldp/stp-aligned-only feature is opted, check
2590 // that the alignment of the source pointer is at least double the alignment
2591 // of the type.
2592 if ((MI.mayLoad() && Subtarget->hasLdpAlignedOnly()) ||
2593 (MI.mayStore() && Subtarget->hasStpAlignedOnly())) {
2594 // If there is no size/align information, cancel the transformation.
2595 if (!MemOp || !MemOp->getMemoryType().isValid()) {
2596 NumFailedAlignmentCheck++;
2597 return false;
2598 }
2599
2600 // Get the needed alignments to check them if
2601 // ldp-aligned-only/stp-aligned-only features are opted.
2602 uint64_t MemAlignment = MemOp->getAlign().value();
2603 uint64_t TypeAlignment = Align(MemOp->getSize().getValue()).value();
2604
2605 if (MemAlignment < 2 * TypeAlignment) {
2606 NumFailedAlignmentCheck++;
2607 return false;
2608 }
2609 }
2610
2611 ++NumPairCreated;
2612 if (TII->hasUnscaledLdStOffset(MI))
2613 ++NumUnscaledPairCreated;
2614
2615 MBBI = mergePairedInsns(MBBI, Paired, Flags);
2616 // Collect liveness info for instructions between Prev and the new position
2617 // MBBI.
2618 for (auto I = std::next(Prev); I != MBBI; I++)
2619 updateDefinedRegisters(*I, DefinedInBB, TRI);
2620
2621 return true;
2622 }
2623 return false;
2624}
2625
2626bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
2628 MachineInstr &MI = *MBBI;
2629 MachineBasicBlock::iterator E = MI.getParent()->end();
2631
2632 // Look forward to try to form a post-index instruction. For example,
2633 // ldr x0, [x20]
2634 // add x20, x20, #32
2635 // merged into:
2636 // ldr x0, [x20], #32
2637 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
2638 if (Update != E) {
2639 // Merge the update into the ld/st.
2640 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
2641 return true;
2642 }
2643
2644 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2645 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2646 return false;
2647
2648 // Look back to try to find a pre-index instruction. For example,
2649 // add x0, x0, #8
2650 // ldr x1, [x0]
2651 // merged into:
2652 // ldr x1, [x0, #8]!
2653 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
2654 if (Update != E) {
2655 // Merge the update into the ld/st.
2656 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2657 return true;
2658 }
2659
2660 // The immediate in the load/store is scaled by the size of the memory
2661 // operation. The immediate in the add we're looking for,
2662 // however, is not, so adjust here.
2663 int UnscaledOffset =
2665
2666 // Look forward to try to find a pre-index instruction. For example,
2667 // ldr x1, [x0, #64]
2668 // add x0, x0, #64
2669 // merged into:
2670 // ldr x1, [x0, #64]!
2671 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2672 if (Update != E) {
2673 // Merge the update into the ld/st.
2674 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2675 return true;
2676 }
2677
2678 return false;
2679}
2680
2681bool AArch64LoadStoreOpt::tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI,
2682 int Scale) {
2683 MachineInstr &MI = *MBBI;
2684 MachineBasicBlock::iterator E = MI.getParent()->end();
2686
2687 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2688 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2689 return false;
2690
2691 // Look back to try to find a const offset for index LdSt instruction. For
2692 // example,
2693 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2694 // ldr x1, [x0, x8]
2695 // merged into:
2696 // add x8, x0, a * (1<<12)
2697 // ldr x1, [x8, imm12]
2698 unsigned Offset;
2699 Update = findMatchingConstOffsetBackward(MBBI, LdStConstLimit, Offset);
2700 if (Update != E && (Offset & (Scale - 1)) == 0) {
2701 // Merge the imm12 into the ld/st.
2702 MBBI = mergeConstOffsetInsn(MBBI, Update, Offset, Scale);
2703 return true;
2704 }
2705
2706 return false;
2707}
2708
2709bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
2710 bool EnableNarrowZeroStOpt) {
2711
2712 bool Modified = false;
2713 // Four tranformations to do here:
2714 // 1) Find loads that directly read from stores and promote them by
2715 // replacing with mov instructions. If the store is wider than the load,
2716 // the load will be replaced with a bitfield extract.
2717 // e.g.,
2718 // str w1, [x0, #4]
2719 // ldrh w2, [x0, #6]
2720 // ; becomes
2721 // str w1, [x0, #4]
2722 // lsr w2, w1, #16
2724 MBBI != E;) {
2725 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2726 Modified = true;
2727 else
2728 ++MBBI;
2729 }
2730 // 2) Merge adjacent zero stores into a wider store.
2731 // e.g.,
2732 // strh wzr, [x0]
2733 // strh wzr, [x0, #2]
2734 // ; becomes
2735 // str wzr, [x0]
2736 // e.g.,
2737 // str wzr, [x0]
2738 // str wzr, [x0, #4]
2739 // ; becomes
2740 // str xzr, [x0]
2741 if (EnableNarrowZeroStOpt)
2743 MBBI != E;) {
2744 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2745 Modified = true;
2746 else
2747 ++MBBI;
2748 }
2749 // 3) Find loads and stores that can be merged into a single load or store
2750 // pair instruction.
2751 // e.g.,
2752 // ldr x0, [x2]
2753 // ldr x1, [x2, #8]
2754 // ; becomes
2755 // ldp x0, x1, [x2]
2756
2758 DefinedInBB.clear();
2759 DefinedInBB.addLiveIns(MBB);
2760 }
2761
2763 MBBI != E;) {
2764 // Track currently live registers up to this point, to help with
2765 // searching for a rename register on demand.
2766 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2767 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2768 Modified = true;
2769 else
2770 ++MBBI;
2771 }
2772 // 4) Find base register updates that can be merged into the load or store
2773 // as a base-reg writeback.
2774 // e.g.,
2775 // ldr x0, [x2]
2776 // add x2, x2, #4
2777 // ; becomes
2778 // ldr x0, [x2], #4
2780 MBBI != E;) {
2781 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2782 Modified = true;
2783 else
2784 ++MBBI;
2785 }
2786
2787 // 5) Find a register assigned with a const value that can be combined with
2788 // into the load or store. e.g.,
2789 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2790 // ldr x1, [x0, x8]
2791 // ; becomes
2792 // add x8, x0, a * (1<<12)
2793 // ldr x1, [x8, imm12]
2795 MBBI != E;) {
2796 int Scale;
2797 if (isMergeableIndexLdSt(*MBBI, Scale) && tryToMergeIndexLdSt(MBBI, Scale))
2798 Modified = true;
2799 else
2800 ++MBBI;
2801 }
2802
2803 return Modified;
2804}
2805
2806bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2807 if (skipFunction(Fn.getFunction()))
2808 return false;
2809
2810 Subtarget = &Fn.getSubtarget<AArch64Subtarget>();
2811 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2812 TRI = Subtarget->getRegisterInfo();
2813 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2814
2815 // Resize the modified and used register unit trackers. We do this once
2816 // per function and then clear the register units each time we optimize a load
2817 // or store.
2818 ModifiedRegUnits.init(*TRI);
2819 UsedRegUnits.init(*TRI);
2820 DefinedInBB.init(*TRI);
2821
2822 bool Modified = false;
2823 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2824 for (auto &MBB : Fn) {
2825 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2826 Modified |= M;
2827 }
2828
2829 return Modified;
2830}
2831
2832// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2833// stores near one another? Note: The pre-RA instruction scheduler already has
2834// hooks to try and schedule pairable loads/stores together to improve pairing
2835// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
2836
2837// FIXME: When pairing store instructions it's very possible for this pass to
2838// hoist a store with a KILL marker above another use (without a KILL marker).
2839// The resulting IR is invalid, but nothing uses the KILL markers after this
2840// pass, so it's never caused a problem in practice.
2841
2842/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2843/// load / store optimization pass.
2845 return new AArch64LoadStoreOpt();
2846}
#define Success
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static cl::opt< bool > EnableRenaming("aarch64-load-store-renaming", cl::init(true), cl::Hidden)
static MachineOperand & getLdStRegOp(MachineInstr &MI, unsigned PairedRegOp=0)
static bool isPromotableLoadFromStore(MachineInstr &MI)
static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale, int &MinOffset, int &MaxOffset)
static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride)
static unsigned getMatchingPairOpcode(unsigned Opc)
static bool isMergeableLdStUpdate(MachineInstr &MI)
static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI, LdStPairFlags &Flags, const AArch64InstrInfo *TII)
static std::optional< MCPhysReg > tryToFindRegisterToRename(const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool needsWinCFI(const MachineFunction *MF)
static bool canRenameUntilSecondLoad(MachineInstr &FirstLoad, MachineInstr &SecondLoad, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static std::optional< MCPhysReg > findRenameRegForSameLdStRegPair(std::optional< bool > MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool mayAlias(MachineInstr &MIa, SmallVectorImpl< MachineInstr * > &MemInsns, AliasAnalysis *AA)
static cl::opt< unsigned > LdStLimit("aarch64-load-store-scan-limit", cl::init(20), cl::Hidden)
static bool canRenameMOP(const MachineOperand &MOP, const TargetRegisterInfo *TRI)
static unsigned getPreIndexedOpcode(unsigned Opc)
#define AARCH64_LOAD_STORE_OPT_NAME
static cl::opt< unsigned > UpdateLimit("aarch64-update-scan-limit", cl::init(100), cl::Hidden)
static bool isPromotableZeroStoreInst(MachineInstr &MI)
static unsigned getMatchingWideOpcode(unsigned Opc)
static unsigned getMatchingNonSExtOpcode(unsigned Opc, bool *IsValidLdStrOpc=nullptr)
static MachineBasicBlock::iterator maybeMoveCFI(MachineInstr &MI, MachineBasicBlock::iterator MaybeCFI)
static int alignTo(int Num, int PowOf2)
static bool isTagStore(const MachineInstr &MI)
static unsigned isMatchingStore(MachineInstr &LoadInst, MachineInstr &StoreInst)
static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg, const TargetRegisterInfo *TRI, unsigned Limit, std::function< bool(MachineInstr &, bool)> &Fn)
static bool isRewritableImplicitDef(unsigned Opc)
static unsigned getPostIndexedOpcode(unsigned Opc)
#define DEBUG_TYPE
static cl::opt< unsigned > LdStConstLimit("aarch64-load-store-const-scan-limit", cl::init(10), cl::Hidden)
static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst, MachineInstr &StoreInst, const AArch64InstrInfo *TII)
static bool isPreLdStPairCandidate(MachineInstr &FirstMI, MachineInstr &MI)
static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale)
static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units, const TargetRegisterInfo *TRI)
static bool canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static unsigned getBaseAddressOpcode(unsigned Opc)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:480
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t High
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, DomTreeUpdater *DTU)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static const MachineOperand & getLdStOffsetOp(const MachineInstr &MI)
Returns the immediate offset operator of a load/store.
static const MachineOperand & getLdStAmountOp(const MachineInstr &MI)
Returns the shift amount operator of a load/store.
static bool isPreLdSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load/store.
static bool isPairedLdSt(const MachineInstr &MI)
Returns whether the instruction is a paired load/store.
static int getMemScale(unsigned Opc)
Scaling factor for (scaled or unscaled) load or store.
static const MachineOperand & getLdStBaseOp(const MachineInstr &MI)
Returns the base register operator of a load/store.
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
const AArch64TargetLowering * getTargetLowering() const override
unsigned getRedZoneSize(const Function &F) const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:680
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:30
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
Definition: LiveRegUnits.h:47
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
Definition: LiveRegUnits.h:116
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
Definition: LiveRegUnits.h:73
void addReg(MCPhysReg Reg)
Adds register units covered by physical register Reg.
Definition: LiveRegUnits.h:86
void removeReg(MCPhysReg Reg)
Removes all register units covered by physical register Reg.
Definition: LiveRegUnits.h:102
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
An instruction for reading from memory.
Definition: Instructions.h:174
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:757
OpType getOperation() const
Definition: MCDwarf.h:680
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
reverse_instr_iterator instr_rend()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:346
bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:685
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
Definition: MachineInstr.h:930
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setImplicit(bool Val=true)
int64_t getImm() const
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dump() const
Definition: Pass.cpp:136
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:347
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:503
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:587
void push_back(const T &Elt)
Definition: SmallVector.h:427
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
An instruction for storing to memory.
Definition: Instructions.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition: Value.h:74
self_iterator getIterator()
Definition: ilist_node.h:132
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Define
Register definition.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
constexpr double e
Definition: MathExtras.h:47
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< filter_iterator< ConstMIBundleOperands, bool(*)(const MachineOperand &)> > phys_regs_and_masks(const MachineInstr &MI)
Returns an iterator range over all physical register and mask operands for MI and bundled instruction...
Definition: LiveRegUnits.h:166
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createAArch64LoadStoreOptimizationPass()
createAArch64LoadStoreOptimizationPass - returns an instance of the load / store optimization pass.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
void initializeAArch64LoadStoreOptPass(PassRegistry &)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85