1 //=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that performs load / store related peephole
11 // optimizations. This pass should be run after register allocation.
13 //===----------------------------------------------------------------------===//
15 #include "AArch64InstrInfo.h"
16 #include "AArch64Subtarget.h"
17 #include "MCTargetDesc/AArch64AddressingModes.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
34 #define DEBUG_TYPE "aarch64-ldst-opt"
36 /// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37 /// load / store instructions to form ldp / stp instructions.
39 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
40 STATISTIC(NumPostFolded, "Number of post-index updates folded");
41 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
42 STATISTIC(NumUnscaledPairCreated,
43 "Number of load/store from unscaled generated");
45 static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46 cl::init(20), cl::Hidden);
48 // Place holder while testing unscaled load/store combining
49 static cl::opt<bool> EnableAArch64UnscaledMemOp(
50 "aarch64-unscaled-mem-op", cl::Hidden,
51 cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
54 void initializeAArch64LoadStoreOptPass(PassRegistry &);
57 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
61 typedef struct LdStPairFlags {
62 // If a matching instruction is found, MergeForward is set to true if the
63 // merge is to remove the first instruction and replace the second with
64 // a pair-wise insn, and false if the reverse is true.
67 // SExtIdx gives the index of the result of the load pair that must be
68 // extended. The value of SExtIdx assumes that the paired load produces the
69 // value in this order: (I, returned iterator), i.e., -1 means no value has
70 // to be extended, 0 means I, and 1 means the returned iterator.
73 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75 void setMergeForward(bool V = true) { MergeForward = V; }
76 bool getMergeForward() const { return MergeForward; }
78 void setSExtIdx(int V) { SExtIdx = V; }
79 int getSExtIdx() const { return SExtIdx; }
83 struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
86 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
89 const AArch64InstrInfo *TII;
90 const TargetRegisterInfo *TRI;
92 // Scan the instructions looking for a load/store that can be combined
93 // with the current instruction into a load/store pair.
94 // Return the matching instruction if one is found, else MBB->end().
95 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
98 // Merge the two instructions indicated into a single pair-wise instruction.
99 // If MergeForward is true, erase the first instruction and fold its
100 // operation into the second. If false, the reverse. Return the instruction
101 // following the first instruction (which may change during processing).
102 MachineBasicBlock::iterator
103 mergePairedInsns(MachineBasicBlock::iterator I,
104 MachineBasicBlock::iterator Paired,
105 const LdStPairFlags &Flags);
107 // Scan the instruction list to find a base register update that can
108 // be combined with the current instruction (a load or store) using
109 // pre or post indexed addressing with writeback. Scan forwards.
110 MachineBasicBlock::iterator
111 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
114 // Scan the instruction list to find a base register update that can
115 // be combined with the current instruction (a load or store) using
116 // pre or post indexed addressing with writeback. Scan backwards.
117 MachineBasicBlock::iterator
118 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
120 // Merge a pre- or post-index base register update into a ld/st instruction.
121 MachineBasicBlock::iterator
122 mergeUpdateInsn(MachineBasicBlock::iterator I,
123 MachineBasicBlock::iterator Update, bool IsPreIdx);
125 bool optimizeBlock(MachineBasicBlock &MBB);
127 bool runOnMachineFunction(MachineFunction &Fn) override;
129 const char *getPassName() const override {
130 return AARCH64_LOAD_STORE_OPT_NAME;
133 char AArch64LoadStoreOpt::ID = 0;
136 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
137 AARCH64_LOAD_STORE_OPT_NAME, false, false)
139 static bool isUnscaledLdSt(unsigned Opc) {
143 case AArch64::STURSi:
144 case AArch64::STURDi:
145 case AArch64::STURQi:
146 case AArch64::STURWi:
147 case AArch64::STURXi:
148 case AArch64::LDURSi:
149 case AArch64::LDURDi:
150 case AArch64::LDURQi:
151 case AArch64::LDURWi:
152 case AArch64::LDURXi:
153 case AArch64::LDURSWi:
158 static bool isUnscaledLdSt(MachineInstr *MI) {
159 return isUnscaledLdSt(MI->getOpcode());
162 // Size in bytes of the data moved by an unscaled load or store
163 static int getMemSize(MachineInstr *MI) {
164 switch (MI->getOpcode()) {
166 llvm_unreachable("Opcode has unknown size!");
167 case AArch64::STRSui:
168 case AArch64::STURSi:
170 case AArch64::STRDui:
171 case AArch64::STURDi:
173 case AArch64::STRQui:
174 case AArch64::STURQi:
176 case AArch64::STRWui:
177 case AArch64::STURWi:
179 case AArch64::STRXui:
180 case AArch64::STURXi:
182 case AArch64::LDRSui:
183 case AArch64::LDURSi:
185 case AArch64::LDRDui:
186 case AArch64::LDURDi:
188 case AArch64::LDRQui:
189 case AArch64::LDURQi:
191 case AArch64::LDRWui:
192 case AArch64::LDURWi:
194 case AArch64::LDRXui:
195 case AArch64::LDURXi:
197 case AArch64::LDRSWui:
198 case AArch64::LDURSWi:
203 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
204 bool *IsValidLdStrOpc = nullptr) {
206 *IsValidLdStrOpc = true;
210 *IsValidLdStrOpc = false;
212 case AArch64::STRDui:
213 case AArch64::STURDi:
214 case AArch64::STRQui:
215 case AArch64::STURQi:
216 case AArch64::STRWui:
217 case AArch64::STURWi:
218 case AArch64::STRXui:
219 case AArch64::STURXi:
220 case AArch64::LDRDui:
221 case AArch64::LDURDi:
222 case AArch64::LDRQui:
223 case AArch64::LDURQi:
224 case AArch64::LDRWui:
225 case AArch64::LDURWi:
226 case AArch64::LDRXui:
227 case AArch64::LDURXi:
228 case AArch64::STRSui:
229 case AArch64::STURSi:
230 case AArch64::LDRSui:
231 case AArch64::LDURSi:
233 case AArch64::LDRSWui:
234 return AArch64::LDRWui;
235 case AArch64::LDURSWi:
236 return AArch64::LDURWi;
240 static unsigned getMatchingPairOpcode(unsigned Opc) {
243 llvm_unreachable("Opcode has no pairwise equivalent!");
244 case AArch64::STRSui:
245 case AArch64::STURSi:
246 return AArch64::STPSi;
247 case AArch64::STRDui:
248 case AArch64::STURDi:
249 return AArch64::STPDi;
250 case AArch64::STRQui:
251 case AArch64::STURQi:
252 return AArch64::STPQi;
253 case AArch64::STRWui:
254 case AArch64::STURWi:
255 return AArch64::STPWi;
256 case AArch64::STRXui:
257 case AArch64::STURXi:
258 return AArch64::STPXi;
259 case AArch64::LDRSui:
260 case AArch64::LDURSi:
261 return AArch64::LDPSi;
262 case AArch64::LDRDui:
263 case AArch64::LDURDi:
264 return AArch64::LDPDi;
265 case AArch64::LDRQui:
266 case AArch64::LDURQi:
267 return AArch64::LDPQi;
268 case AArch64::LDRWui:
269 case AArch64::LDURWi:
270 return AArch64::LDPWi;
271 case AArch64::LDRXui:
272 case AArch64::LDURXi:
273 return AArch64::LDPXi;
274 case AArch64::LDRSWui:
275 case AArch64::LDURSWi:
276 return AArch64::LDPSWi;
280 static unsigned getPreIndexedOpcode(unsigned Opc) {
283 llvm_unreachable("Opcode has no pre-indexed equivalent!");
284 case AArch64::STRSui:
285 return AArch64::STRSpre;
286 case AArch64::STRDui:
287 return AArch64::STRDpre;
288 case AArch64::STRQui:
289 return AArch64::STRQpre;
290 case AArch64::STRWui:
291 return AArch64::STRWpre;
292 case AArch64::STRXui:
293 return AArch64::STRXpre;
294 case AArch64::LDRSui:
295 return AArch64::LDRSpre;
296 case AArch64::LDRDui:
297 return AArch64::LDRDpre;
298 case AArch64::LDRQui:
299 return AArch64::LDRQpre;
300 case AArch64::LDRWui:
301 return AArch64::LDRWpre;
302 case AArch64::LDRXui:
303 return AArch64::LDRXpre;
304 case AArch64::LDRSWui:
305 return AArch64::LDRSWpre;
309 static unsigned getPostIndexedOpcode(unsigned Opc) {
312 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
313 case AArch64::STRSui:
314 return AArch64::STRSpost;
315 case AArch64::STRDui:
316 return AArch64::STRDpost;
317 case AArch64::STRQui:
318 return AArch64::STRQpost;
319 case AArch64::STRWui:
320 return AArch64::STRWpost;
321 case AArch64::STRXui:
322 return AArch64::STRXpost;
323 case AArch64::LDRSui:
324 return AArch64::LDRSpost;
325 case AArch64::LDRDui:
326 return AArch64::LDRDpost;
327 case AArch64::LDRQui:
328 return AArch64::LDRQpost;
329 case AArch64::LDRWui:
330 return AArch64::LDRWpost;
331 case AArch64::LDRXui:
332 return AArch64::LDRXpost;
333 case AArch64::LDRSWui:
334 return AArch64::LDRSWpost;
338 static const MachineOperand &getLdStRegOp(const MachineInstr *MI) {
339 return MI->getOperand(0);
342 static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
343 return MI->getOperand(1);
346 static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
347 return MI->getOperand(2);
350 MachineBasicBlock::iterator
351 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
352 MachineBasicBlock::iterator Paired,
353 const LdStPairFlags &Flags) {
354 MachineBasicBlock::iterator NextI = I;
356 // If NextI is the second of the two instructions to be merged, we need
357 // to skip one further. Either way we merge will invalidate the iterator,
358 // and we don't need to scan the new instruction, as it's a pairwise
359 // instruction, which we're not considering for further action anyway.
363 int SExtIdx = Flags.getSExtIdx();
365 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
366 bool IsUnscaled = isUnscaledLdSt(Opc);
368 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
370 bool MergeForward = Flags.getMergeForward();
371 unsigned NewOpc = getMatchingPairOpcode(Opc);
372 // Insert our new paired instruction after whichever of the paired
373 // instructions MergeForward indicates.
374 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
375 // Also based on MergeForward is from where we copy the base register operand
376 // so we get the flags compatible with the input code.
377 const MachineOperand &BaseRegOp =
378 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
380 // Which register is Rt and which is Rt2 depends on the offset order.
381 MachineInstr *RtMI, *Rt2MI;
382 if (getLdStOffsetOp(I).getImm() ==
383 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
386 // Here we swapped the assumption made for SExtIdx.
387 // I.e., we turn ldp I, Paired into ldp Paired, I.
388 // Update the index accordingly.
390 SExtIdx = (SExtIdx + 1) % 2;
396 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
397 if (IsUnscaled && EnableAArch64UnscaledMemOp)
398 OffsetImm /= OffsetStride;
400 // Construct the new instruction.
401 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
402 I->getDebugLoc(), TII->get(NewOpc))
403 .addOperand(getLdStRegOp(RtMI))
404 .addOperand(getLdStRegOp(Rt2MI))
405 .addOperand(BaseRegOp)
409 // FIXME: Do we need/want to copy the mem operands from the source
410 // instructions? Probably. What uses them after this?
412 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
413 DEBUG(I->print(dbgs()));
414 DEBUG(dbgs() << " ");
415 DEBUG(Paired->print(dbgs()));
416 DEBUG(dbgs() << " with instruction:\n ");
419 // Generate the sign extension for the proper result of the ldp.
420 // I.e., with X1, that would be:
421 // %W1<def> = KILL %W1, %X1<imp-def>
422 // %X1<def> = SBFMXri %X1<kill>, 0, 31
423 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
424 // Right now, DstMO has the extended register, since it comes from an
426 unsigned DstRegX = DstMO.getReg();
427 // Get the W variant of that register.
428 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
429 // Update the result of LDP to use the W instead of the X variant.
430 DstMO.setReg(DstRegW);
431 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
432 DEBUG(dbgs() << "\n");
433 // Make the machine verifier happy by providing a definition for
435 // Insert this definition right after the generated LDP, i.e., before
437 MachineInstrBuilder MIBKill =
438 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
439 TII->get(TargetOpcode::KILL), DstRegW)
441 .addReg(DstRegX, RegState::Define);
442 MIBKill->getOperand(2).setImplicit();
443 // Create the sign extension.
444 MachineInstrBuilder MIBSXTW =
445 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
446 TII->get(AArch64::SBFMXri), DstRegX)
451 DEBUG(dbgs() << " Extend operand:\n ");
452 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
453 DEBUG(dbgs() << "\n");
455 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
456 DEBUG(dbgs() << "\n");
459 // Erase the old instructions.
460 I->eraseFromParent();
461 Paired->eraseFromParent();
466 /// trackRegDefsUses - Remember what registers the specified instruction uses
468 static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
470 const TargetRegisterInfo *TRI) {
471 for (const MachineOperand &MO : MI->operands()) {
473 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
477 unsigned Reg = MO.getReg();
479 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
480 ModifiedRegs.set(*AI);
482 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
483 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
489 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
490 // Convert the byte-offset used by unscaled into an "element" offset used
491 // by the scaled pair load/store instructions.
493 Offset /= OffsetStride;
495 return Offset <= 63 && Offset >= -64;
498 // Do alignment, specialized to power of 2 and for signed ints,
499 // avoiding having to do a C-style cast from uint_64t to int when
500 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
501 // FIXME: Move this function to include/MathExtras.h?
502 static int alignTo(int Num, int PowOf2) {
503 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
506 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
507 const AArch64InstrInfo *TII) {
508 // One of the instructions must modify memory.
509 if (!MIa->mayStore() && !MIb->mayStore())
512 // Both instructions must be memory operations.
513 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
516 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
519 static bool mayAlias(MachineInstr *MIa,
520 SmallVectorImpl<MachineInstr *> &MemInsns,
521 const AArch64InstrInfo *TII) {
522 for (auto &MIb : MemInsns)
523 if (mayAlias(MIa, MIb, TII))
529 /// findMatchingInsn - Scan the instructions looking for a load/store that can
530 /// be combined with the current instruction into a load/store pair.
531 MachineBasicBlock::iterator
532 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
533 LdStPairFlags &Flags,
535 MachineBasicBlock::iterator E = I->getParent()->end();
536 MachineBasicBlock::iterator MBBI = I;
537 MachineInstr *FirstMI = I;
540 unsigned Opc = FirstMI->getOpcode();
541 bool MayLoad = FirstMI->mayLoad();
542 bool IsUnscaled = isUnscaledLdSt(FirstMI);
543 unsigned Reg = getLdStRegOp(FirstMI).getReg();
544 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
545 int Offset = getLdStOffsetOp(FirstMI).getImm();
547 // Early exit if the first instruction modifies the base register.
548 // e.g., ldr x0, [x0]
549 if (FirstMI->modifiesRegister(BaseReg, TRI))
552 // Early exit if the offset if not possible to match. (6 bits of positive
553 // range, plus allow an extra one in case we find a later insn that matches
556 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
557 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
560 // Track which registers have been modified and used between the first insn
561 // (inclusive) and the second insn.
562 BitVector ModifiedRegs, UsedRegs;
563 ModifiedRegs.resize(TRI->getNumRegs());
564 UsedRegs.resize(TRI->getNumRegs());
566 // Remember any instructions that read/write memory between FirstMI and MI.
567 SmallVector<MachineInstr *, 4> MemInsns;
569 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
570 MachineInstr *MI = MBBI;
571 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
572 // optimization by changing how far we scan.
573 if (MI->isDebugValue())
576 // Now that we know this is a real instruction, count it.
579 bool CanMergeOpc = Opc == MI->getOpcode();
580 Flags.setSExtIdx(-1);
582 bool IsValidLdStrOpc;
583 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
584 assert(IsValidLdStrOpc &&
585 "Given Opc should be a Load or Store with an immediate");
586 // Opc will be the first instruction in the pair.
587 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
588 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
591 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
592 assert(MI->mayLoadOrStore() && "Expected memory operation.");
593 // If we've found another instruction with the same opcode, check to see
594 // if the base and offset are compatible with our starting instruction.
595 // These instructions all have scaled immediate operands, so we just
596 // check for +1/-1. Make sure to check the new instruction offset is
597 // actually an immediate and not a symbolic reference destined for
600 // Pairwise instructions have a 7-bit signed offset field. Single insns
601 // have a 12-bit unsigned offset field. To be a valid combine, the
602 // final offset must be in range.
603 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
604 int MIOffset = getLdStOffsetOp(MI).getImm();
605 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
606 (Offset + OffsetStride == MIOffset))) {
607 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
608 // If this is a volatile load/store that otherwise matched, stop looking
609 // as something is going on that we don't have enough information to
610 // safely transform. Similarly, stop if we see a hint to avoid pairs.
611 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
613 // If the resultant immediate offset of merging these instructions
614 // is out of range for a pairwise instruction, bail and keep looking.
615 bool MIIsUnscaled = isUnscaledLdSt(MI);
616 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
617 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
618 MemInsns.push_back(MI);
621 // If the alignment requirements of the paired (scaled) instruction
622 // can't express the offset of the unscaled input, bail and keep
624 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
625 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
626 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
627 MemInsns.push_back(MI);
630 // If the destination register of the loads is the same register, bail
631 // and keep looking. A load-pair instruction with both destination
632 // registers the same is UNPREDICTABLE and will result in an exception.
633 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
634 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
635 MemInsns.push_back(MI);
639 // If the Rt of the second instruction was not modified or used between
640 // the two instructions and none of the instructions between the second
641 // and first alias with the second, we can combine the second into the
643 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
644 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
645 !mayAlias(MI, MemInsns, TII)) {
646 Flags.setMergeForward(false);
650 // Likewise, if the Rt of the first instruction is not modified or used
651 // between the two instructions and none of the instructions between the
652 // first and the second alias with the first, we can combine the first
654 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
655 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
656 !mayAlias(FirstMI, MemInsns, TII)) {
657 Flags.setMergeForward(true);
660 // Unable to combine these instructions due to interference in between.
665 // If the instruction wasn't a matching load or store. Stop searching if we
666 // encounter a call instruction that might modify memory.
670 // Update modified / uses register lists.
671 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
673 // Otherwise, if the base register is modified, we have no match, so
675 if (ModifiedRegs[BaseReg])
678 // Update list of instructions that read/write memory.
679 if (MI->mayLoadOrStore())
680 MemInsns.push_back(MI);
685 MachineBasicBlock::iterator
686 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
687 MachineBasicBlock::iterator Update,
689 assert((Update->getOpcode() == AArch64::ADDXri ||
690 Update->getOpcode() == AArch64::SUBXri) &&
691 "Unexpected base register update instruction to merge!");
692 MachineBasicBlock::iterator NextI = I;
693 // Return the instruction following the merged instruction, which is
694 // the instruction following our unmerged load. Unless that's the add/sub
695 // instruction we're merging, in which case it's the one after that.
696 if (++NextI == Update)
699 int Value = Update->getOperand(2).getImm();
700 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
701 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
702 if (Update->getOpcode() == AArch64::SUBXri)
705 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
706 : getPostIndexedOpcode(I->getOpcode());
707 MachineInstrBuilder MIB =
708 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
709 .addOperand(getLdStRegOp(Update))
710 .addOperand(getLdStRegOp(I))
711 .addOperand(getLdStBaseOp(I))
716 DEBUG(dbgs() << "Creating pre-indexed load/store.");
718 DEBUG(dbgs() << "Creating post-indexed load/store.");
719 DEBUG(dbgs() << " Replacing instructions:\n ");
720 DEBUG(I->print(dbgs()));
721 DEBUG(dbgs() << " ");
722 DEBUG(Update->print(dbgs()));
723 DEBUG(dbgs() << " with instruction:\n ");
724 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
725 DEBUG(dbgs() << "\n");
727 // Erase the old instructions for the block.
728 I->eraseFromParent();
729 Update->eraseFromParent();
734 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
736 switch (MI->getOpcode()) {
739 case AArch64::SUBXri:
740 // Negate the offset for a SUB instruction.
743 case AArch64::ADDXri:
744 // Make sure it's a vanilla immediate operand, not a relocation or
745 // anything else we can't handle.
746 if (!MI->getOperand(2).isImm())
748 // Watch out for 1 << 12 shifted value.
749 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
751 // If the instruction has the base register as source and dest and the
752 // immediate will fit in a signed 9-bit integer, then we have a match.
753 if (getLdStRegOp(MI).getReg() == BaseReg &&
754 getLdStBaseOp(MI).getReg() == BaseReg &&
755 getLdStOffsetOp(MI).getImm() <= 255 &&
756 getLdStOffsetOp(MI).getImm() >= -256) {
757 // If we have a non-zero Offset, we check that it matches the amount
758 // we're adding to the register.
759 if (!Offset || Offset == MI->getOperand(2).getImm())
767 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
768 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
769 MachineBasicBlock::iterator E = I->getParent()->end();
770 MachineInstr *MemMI = I;
771 MachineBasicBlock::iterator MBBI = I;
772 const MachineFunction &MF = *MemMI->getParent()->getParent();
774 unsigned DestReg = getLdStRegOp(MemMI).getReg();
775 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
776 int Offset = getLdStOffsetOp(MemMI).getImm() *
777 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
779 // If the base register overlaps the destination register, we can't
781 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
784 // Scan forward looking for post-index opportunities.
785 // Updating instructions can't be formed if the memory insn already
786 // has an offset other than the value we're looking for.
790 // Track which registers have been modified and used between the first insn
791 // (inclusive) and the second insn.
792 BitVector ModifiedRegs, UsedRegs;
793 ModifiedRegs.resize(TRI->getNumRegs());
794 UsedRegs.resize(TRI->getNumRegs());
796 for (unsigned Count = 0; MBBI != E; ++MBBI) {
797 MachineInstr *MI = MBBI;
798 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
799 // optimization by changing how far we scan.
800 if (MI->isDebugValue())
803 // Now that we know this is a real instruction, count it.
806 // If we found a match, return it.
807 if (isMatchingUpdateInsn(MI, BaseReg, Value))
810 // Update the status of what the instruction clobbered and used.
811 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
813 // Otherwise, if the base register is used or modified, we have no match, so
815 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
821 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
822 MachineBasicBlock::iterator I, unsigned Limit) {
823 MachineBasicBlock::iterator B = I->getParent()->begin();
824 MachineBasicBlock::iterator E = I->getParent()->end();
825 MachineInstr *MemMI = I;
826 MachineBasicBlock::iterator MBBI = I;
827 const MachineFunction &MF = *MemMI->getParent()->getParent();
829 unsigned DestReg = getLdStRegOp(MemMI).getReg();
830 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
831 int Offset = getLdStOffsetOp(MemMI).getImm();
832 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
834 // If the load/store is the first instruction in the block, there's obviously
835 // not any matching update. Ditto if the memory offset isn't zero.
836 if (MBBI == B || Offset != 0)
838 // If the base register overlaps the destination register, we can't
840 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
843 // Track which registers have been modified and used between the first insn
844 // (inclusive) and the second insn.
845 BitVector ModifiedRegs, UsedRegs;
846 ModifiedRegs.resize(TRI->getNumRegs());
847 UsedRegs.resize(TRI->getNumRegs());
849 for (unsigned Count = 0; MBBI != B; --MBBI) {
850 MachineInstr *MI = MBBI;
851 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
852 // optimization by changing how far we scan.
853 if (MI->isDebugValue())
856 // Now that we know this is a real instruction, count it.
859 // If we found a match, return it.
860 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
863 // Update the status of what the instruction clobbered and used.
864 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
866 // Otherwise, if the base register is used or modified, we have no match, so
868 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
874 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
875 bool Modified = false;
876 // Two tranformations to do here:
877 // 1) Find loads and stores that can be merged into a single load or store
884 // 2) Find base register updates that can be merged into the load or store
885 // as a base-reg writeback.
892 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
894 MachineInstr *MI = MBBI;
895 switch (MI->getOpcode()) {
897 // Just move on to the next instruction.
900 case AArch64::STRSui:
901 case AArch64::STRDui:
902 case AArch64::STRQui:
903 case AArch64::STRXui:
904 case AArch64::STRWui:
905 case AArch64::LDRSui:
906 case AArch64::LDRDui:
907 case AArch64::LDRQui:
908 case AArch64::LDRXui:
909 case AArch64::LDRWui:
910 case AArch64::LDRSWui:
911 // do the unscaled versions as well
912 case AArch64::STURSi:
913 case AArch64::STURDi:
914 case AArch64::STURQi:
915 case AArch64::STURWi:
916 case AArch64::STURXi:
917 case AArch64::LDURSi:
918 case AArch64::LDURDi:
919 case AArch64::LDURQi:
920 case AArch64::LDURWi:
921 case AArch64::LDURXi:
922 case AArch64::LDURSWi: {
923 // If this is a volatile load/store, don't mess with it.
924 if (MI->hasOrderedMemoryRef()) {
928 // Make sure this is a reg+imm (as opposed to an address reloc).
929 if (!getLdStOffsetOp(MI).isImm()) {
933 // Check if this load/store has a hint to avoid pair formation.
934 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
935 if (TII->isLdStPairSuppressed(MI)) {
939 // Look ahead up to ScanLimit instructions for a pairable instruction.
941 MachineBasicBlock::iterator Paired =
942 findMatchingInsn(MBBI, Flags, ScanLimit);
945 if (isUnscaledLdSt(MI))
946 ++NumUnscaledPairCreated;
948 // Merge the loads into a pair. Keeping the iterator straight is a
949 // pain, so we let the merge routine tell us what the next instruction
950 // is after it's done mucking about.
951 MBBI = mergePairedInsns(MBBI, Paired, Flags);
958 // FIXME: Do the other instructions.
962 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
964 MachineInstr *MI = MBBI;
965 // Do update merging. It's simpler to keep this separate from the above
966 // switch, though not strictly necessary.
967 unsigned Opc = MI->getOpcode();
970 // Just move on to the next instruction.
973 case AArch64::STRSui:
974 case AArch64::STRDui:
975 case AArch64::STRQui:
976 case AArch64::STRXui:
977 case AArch64::STRWui:
978 case AArch64::LDRSui:
979 case AArch64::LDRDui:
980 case AArch64::LDRQui:
981 case AArch64::LDRXui:
982 case AArch64::LDRWui:
983 // do the unscaled versions as well
984 case AArch64::STURSi:
985 case AArch64::STURDi:
986 case AArch64::STURQi:
987 case AArch64::STURWi:
988 case AArch64::STURXi:
989 case AArch64::LDURSi:
990 case AArch64::LDURDi:
991 case AArch64::LDURQi:
992 case AArch64::LDURWi:
993 case AArch64::LDURXi: {
994 // Make sure this is a reg+imm (as opposed to an address reloc).
995 if (!getLdStOffsetOp(MI).isImm()) {
999 // Look ahead up to ScanLimit instructions for a mergable instruction.
1000 MachineBasicBlock::iterator Update =
1001 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1003 // Merge the update into the ld/st.
1004 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1009 // Don't know how to handle pre/post-index versions, so move to the next
1011 if (isUnscaledLdSt(Opc)) {
1016 // Look back to try to find a pre-index instruction. For example,
1020 // ldr x1, [x0, #8]!
1021 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1023 // Merge the update into the ld/st.
1024 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1030 // Look forward to try to find a post-index instruction. For example,
1031 // ldr x1, [x0, #64]
1034 // ldr x1, [x0, #64]!
1036 // The immediate in the load/store is scaled by the size of the register
1037 // being loaded. The immediate in the add we're looking for,
1038 // however, is not, so adjust here.
1039 int Value = MI->getOperand(2).getImm() *
1040 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1042 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1044 // Merge the update into the ld/st.
1045 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1051 // Nothing found. Just move to the next instruction.
1055 // FIXME: Do the other instructions.
1062 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1063 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1064 TRI = Fn.getSubtarget().getRegisterInfo();
1066 bool Modified = false;
1067 for (auto &MBB : Fn)
1068 Modified |= optimizeBlock(MBB);
1073 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1074 // loads and stores near one another?
1076 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1077 /// load / store optimization pass.
1078 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1079 return new AArch64LoadStoreOpt();