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));
55 typedef struct LdStPairFlags {
56 // If a matching instruction is found, MergeForward is set to true if the
57 // merge is to remove the first instruction and replace the second with
58 // a pair-wise insn, and false if the reverse is true.
61 // SExtIdx gives the index of the result of the load pair that must be
62 // extended. The value of SExtIdx assumes that the paired load produces the
63 // value in this order: (I, returned iterator), i.e., -1 means no value has
64 // to be extended, 0 means I, and 1 means the returned iterator.
67 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
69 void setMergeForward(bool V = true) { MergeForward = V; }
70 bool getMergeForward() const { return MergeForward; }
72 void setSExtIdx(int V) { SExtIdx = V; }
73 int getSExtIdx() const { return SExtIdx; }
77 struct AArch64LoadStoreOpt : public MachineFunctionPass {
79 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
81 const AArch64InstrInfo *TII;
82 const TargetRegisterInfo *TRI;
84 // Scan the instructions looking for a load/store that can be combined
85 // with the current instruction into a load/store pair.
86 // Return the matching instruction if one is found, else MBB->end().
87 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
90 // Merge the two instructions indicated into a single pair-wise instruction.
91 // If MergeForward is true, erase the first instruction and fold its
92 // operation into the second. If false, the reverse. Return the instruction
93 // following the first instruction (which may change during processing).
94 MachineBasicBlock::iterator
95 mergePairedInsns(MachineBasicBlock::iterator I,
96 MachineBasicBlock::iterator Paired,
97 const LdStPairFlags &Flags);
99 // Scan the instruction list to find a base register update that can
100 // be combined with the current instruction (a load or store) using
101 // pre or post indexed addressing with writeback. Scan forwards.
102 MachineBasicBlock::iterator
103 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
106 // Scan the instruction list to find a base register update that can
107 // be combined with the current instruction (a load or store) using
108 // pre or post indexed addressing with writeback. Scan backwards.
109 MachineBasicBlock::iterator
110 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
112 // Merge a pre-index base register update into a ld/st instruction.
113 MachineBasicBlock::iterator
114 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
115 MachineBasicBlock::iterator Update);
117 // Merge a post-index base register update into a ld/st instruction.
118 MachineBasicBlock::iterator
119 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
120 MachineBasicBlock::iterator Update);
122 bool optimizeBlock(MachineBasicBlock &MBB);
124 bool runOnMachineFunction(MachineFunction &Fn) override;
126 const char *getPassName() const override {
127 return "AArch64 load / store optimization pass";
131 int getMemSize(MachineInstr *MemMI);
133 char AArch64LoadStoreOpt::ID = 0;
136 static bool isUnscaledLdst(unsigned Opc) {
140 case AArch64::STURSi:
141 case AArch64::STURDi:
142 case AArch64::STURQi:
143 case AArch64::STURWi:
144 case AArch64::STURXi:
145 case AArch64::LDURSi:
146 case AArch64::LDURDi:
147 case AArch64::LDURQi:
148 case AArch64::LDURWi:
149 case AArch64::LDURXi:
150 case AArch64::LDURSWi:
155 // Size in bytes of the data moved by an unscaled load or store
156 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
157 switch (MemMI->getOpcode()) {
159 llvm_unreachable("Opcode has unknown size!");
160 case AArch64::STRSui:
161 case AArch64::STURSi:
163 case AArch64::STRDui:
164 case AArch64::STURDi:
166 case AArch64::STRQui:
167 case AArch64::STURQi:
169 case AArch64::STRWui:
170 case AArch64::STURWi:
172 case AArch64::STRXui:
173 case AArch64::STURXi:
175 case AArch64::LDRSui:
176 case AArch64::LDURSi:
178 case AArch64::LDRDui:
179 case AArch64::LDURDi:
181 case AArch64::LDRQui:
182 case AArch64::LDURQi:
184 case AArch64::LDRWui:
185 case AArch64::LDURWi:
187 case AArch64::LDRXui:
188 case AArch64::LDURXi:
190 case AArch64::LDRSWui:
191 case AArch64::LDURSWi:
196 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
197 bool *IsValidLdStrOpc = nullptr) {
199 *IsValidLdStrOpc = true;
203 *IsValidLdStrOpc = false;
205 case AArch64::STRDui:
206 case AArch64::STURDi:
207 case AArch64::STRQui:
208 case AArch64::STURQi:
209 case AArch64::STRWui:
210 case AArch64::STURWi:
211 case AArch64::STRXui:
212 case AArch64::STURXi:
213 case AArch64::LDRDui:
214 case AArch64::LDURDi:
215 case AArch64::LDRQui:
216 case AArch64::LDURQi:
217 case AArch64::LDRWui:
218 case AArch64::LDURWi:
219 case AArch64::LDRXui:
220 case AArch64::LDURXi:
221 case AArch64::STRSui:
222 case AArch64::STURSi:
223 case AArch64::LDRSui:
224 case AArch64::LDURSi:
226 case AArch64::LDRSWui:
227 return AArch64::LDRWui;
228 case AArch64::LDURSWi:
229 return AArch64::LDURWi;
233 static unsigned getMatchingPairOpcode(unsigned Opc) {
236 llvm_unreachable("Opcode has no pairwise equivalent!");
237 case AArch64::STRSui:
238 case AArch64::STURSi:
239 return AArch64::STPSi;
240 case AArch64::STRDui:
241 case AArch64::STURDi:
242 return AArch64::STPDi;
243 case AArch64::STRQui:
244 case AArch64::STURQi:
245 return AArch64::STPQi;
246 case AArch64::STRWui:
247 case AArch64::STURWi:
248 return AArch64::STPWi;
249 case AArch64::STRXui:
250 case AArch64::STURXi:
251 return AArch64::STPXi;
252 case AArch64::LDRSui:
253 case AArch64::LDURSi:
254 return AArch64::LDPSi;
255 case AArch64::LDRDui:
256 case AArch64::LDURDi:
257 return AArch64::LDPDi;
258 case AArch64::LDRQui:
259 case AArch64::LDURQi:
260 return AArch64::LDPQi;
261 case AArch64::LDRWui:
262 case AArch64::LDURWi:
263 return AArch64::LDPWi;
264 case AArch64::LDRXui:
265 case AArch64::LDURXi:
266 return AArch64::LDPXi;
267 case AArch64::LDRSWui:
268 case AArch64::LDURSWi:
269 return AArch64::LDPSWi;
273 static unsigned getPreIndexedOpcode(unsigned Opc) {
276 llvm_unreachable("Opcode has no pre-indexed equivalent!");
277 case AArch64::STRSui:
278 return AArch64::STRSpre;
279 case AArch64::STRDui:
280 return AArch64::STRDpre;
281 case AArch64::STRQui:
282 return AArch64::STRQpre;
283 case AArch64::STRWui:
284 return AArch64::STRWpre;
285 case AArch64::STRXui:
286 return AArch64::STRXpre;
287 case AArch64::LDRSui:
288 return AArch64::LDRSpre;
289 case AArch64::LDRDui:
290 return AArch64::LDRDpre;
291 case AArch64::LDRQui:
292 return AArch64::LDRQpre;
293 case AArch64::LDRWui:
294 return AArch64::LDRWpre;
295 case AArch64::LDRXui:
296 return AArch64::LDRXpre;
297 case AArch64::LDRSWui:
298 return AArch64::LDRSWpre;
302 static unsigned getPostIndexedOpcode(unsigned Opc) {
305 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
306 case AArch64::STRSui:
307 return AArch64::STRSpost;
308 case AArch64::STRDui:
309 return AArch64::STRDpost;
310 case AArch64::STRQui:
311 return AArch64::STRQpost;
312 case AArch64::STRWui:
313 return AArch64::STRWpost;
314 case AArch64::STRXui:
315 return AArch64::STRXpost;
316 case AArch64::LDRSui:
317 return AArch64::LDRSpost;
318 case AArch64::LDRDui:
319 return AArch64::LDRDpost;
320 case AArch64::LDRQui:
321 return AArch64::LDRQpost;
322 case AArch64::LDRWui:
323 return AArch64::LDRWpost;
324 case AArch64::LDRXui:
325 return AArch64::LDRXpost;
326 case AArch64::LDRSWui:
327 return AArch64::LDRSWpost;
331 MachineBasicBlock::iterator
332 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
333 MachineBasicBlock::iterator Paired,
334 const LdStPairFlags &Flags) {
335 MachineBasicBlock::iterator NextI = I;
337 // If NextI is the second of the two instructions to be merged, we need
338 // to skip one further. Either way we merge will invalidate the iterator,
339 // and we don't need to scan the new instruction, as it's a pairwise
340 // instruction, which we're not considering for further action anyway.
344 int SExtIdx = Flags.getSExtIdx();
346 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
347 bool IsUnscaled = isUnscaledLdst(Opc);
349 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
351 bool MergeForward = Flags.getMergeForward();
352 unsigned NewOpc = getMatchingPairOpcode(Opc);
353 // Insert our new paired instruction after whichever of the paired
354 // instructions MergeForward indicates.
355 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
356 // Also based on MergeForward is from where we copy the base register operand
357 // so we get the flags compatible with the input code.
358 MachineOperand &BaseRegOp =
359 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
361 // Which register is Rt and which is Rt2 depends on the offset order.
362 MachineInstr *RtMI, *Rt2MI;
363 if (I->getOperand(2).getImm() ==
364 Paired->getOperand(2).getImm() + OffsetStride) {
367 // Here we swapped the assumption made for SExtIdx.
368 // I.e., we turn ldp I, Paired into ldp Paired, I.
369 // Update the index accordingly.
371 SExtIdx = (SExtIdx + 1) % 2;
377 int OffsetImm = RtMI->getOperand(2).getImm();
378 if (IsUnscaled && EnableAArch64UnscaledMemOp)
379 OffsetImm /= OffsetStride;
381 // Construct the new instruction.
382 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
383 I->getDebugLoc(), TII->get(NewOpc))
384 .addOperand(RtMI->getOperand(0))
385 .addOperand(Rt2MI->getOperand(0))
386 .addOperand(BaseRegOp)
390 // FIXME: Do we need/want to copy the mem operands from the source
391 // instructions? Probably. What uses them after this?
393 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
394 DEBUG(I->print(dbgs()));
395 DEBUG(dbgs() << " ");
396 DEBUG(Paired->print(dbgs()));
397 DEBUG(dbgs() << " with instruction:\n ");
400 // Generate the sign extension for the proper result of the ldp.
401 // I.e., with X1, that would be:
402 // %W1<def> = KILL %W1, %X1<imp-def>
403 // %X1<def> = SBFMXri %X1<kill>, 0, 31
404 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
405 // Right now, DstMO has the extended register, since it comes from an
407 unsigned DstRegX = DstMO.getReg();
408 // Get the W variant of that register.
409 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
410 // Update the result of LDP to use the W instead of the X variant.
411 DstMO.setReg(DstRegW);
412 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
413 DEBUG(dbgs() << "\n");
414 // Make the machine verifier happy by providing a definition for
416 // Insert this definition right after the generated LDP, i.e., before
418 MachineInstrBuilder MIBKill =
419 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
420 TII->get(TargetOpcode::KILL), DstRegW)
422 .addReg(DstRegX, RegState::Define);
423 MIBKill->getOperand(2).setImplicit();
424 // Create the sign extension.
425 MachineInstrBuilder MIBSXTW =
426 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
427 TII->get(AArch64::SBFMXri), DstRegX)
432 DEBUG(dbgs() << " Extend operand:\n ");
433 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
434 DEBUG(dbgs() << "\n");
436 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437 DEBUG(dbgs() << "\n");
440 // Erase the old instructions.
441 I->eraseFromParent();
442 Paired->eraseFromParent();
447 /// trackRegDefsUses - Remember what registers the specified instruction uses
449 static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
451 const TargetRegisterInfo *TRI) {
452 for (const MachineOperand &MO : MI->operands()) {
454 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
458 unsigned Reg = MO.getReg();
460 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
461 ModifiedRegs.set(*AI);
463 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
464 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
470 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
471 if (!IsUnscaled && (Offset > 63 || Offset < -64))
474 // Convert the byte-offset used by unscaled into an "element" offset used
475 // by the scaled pair load/store instructions.
476 int ElemOffset = Offset / OffsetStride;
477 if (ElemOffset > 63 || ElemOffset < -64)
483 // Do alignment, specialized to power of 2 and for signed ints,
484 // avoiding having to do a C-style cast from uint_64t to int when
485 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
486 // FIXME: Move this function to include/MathExtras.h?
487 static int alignTo(int Num, int PowOf2) {
488 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
491 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
492 const AArch64InstrInfo *TII) {
493 // One of the instructions must modify memory.
494 if (!MIa->mayStore() && !MIb->mayStore())
497 // Both instructions must be memory operations.
498 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
501 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
504 static bool mayAlias(MachineInstr *MIa,
505 SmallVectorImpl<MachineInstr *> &MemInsns,
506 const AArch64InstrInfo *TII) {
507 for (auto &MIb : MemInsns)
508 if (mayAlias(MIa, MIb, TII))
514 /// findMatchingInsn - Scan the instructions looking for a load/store that can
515 /// be combined with the current instruction into a load/store pair.
516 MachineBasicBlock::iterator
517 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
518 LdStPairFlags &Flags,
520 MachineBasicBlock::iterator E = I->getParent()->end();
521 MachineBasicBlock::iterator MBBI = I;
522 MachineInstr *FirstMI = I;
525 unsigned Opc = FirstMI->getOpcode();
526 bool MayLoad = FirstMI->mayLoad();
527 bool IsUnscaled = isUnscaledLdst(Opc);
528 unsigned Reg = FirstMI->getOperand(0).getReg();
529 unsigned BaseReg = FirstMI->getOperand(1).getReg();
530 int Offset = FirstMI->getOperand(2).getImm();
532 // Early exit if the first instruction modifies the base register.
533 // e.g., ldr x0, [x0]
534 // Early exit if the offset if not possible to match. (6 bits of positive
535 // range, plus allow an extra one in case we find a later insn that matches
537 if (FirstMI->modifiesRegister(BaseReg, TRI))
540 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
541 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
544 // Track which registers have been modified and used between the first insn
545 // (inclusive) and the second insn.
546 BitVector ModifiedRegs, UsedRegs;
547 ModifiedRegs.resize(TRI->getNumRegs());
548 UsedRegs.resize(TRI->getNumRegs());
550 // Remember any instructions that read/write memory between FirstMI and MI.
551 SmallVector<MachineInstr *, 4> MemInsns;
553 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
554 MachineInstr *MI = MBBI;
555 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
556 // optimization by changing how far we scan.
557 if (MI->isDebugValue())
560 // Now that we know this is a real instruction, count it.
563 bool CanMergeOpc = Opc == MI->getOpcode();
564 Flags.setSExtIdx(-1);
566 bool IsValidLdStrOpc;
567 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
568 if (!IsValidLdStrOpc)
570 // Opc will be the first instruction in the pair.
571 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
572 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
575 if (CanMergeOpc && MI->getOperand(2).isImm()) {
576 // If we've found another instruction with the same opcode, check to see
577 // if the base and offset are compatible with our starting instruction.
578 // These instructions all have scaled immediate operands, so we just
579 // check for +1/-1. Make sure to check the new instruction offset is
580 // actually an immediate and not a symbolic reference destined for
583 // Pairwise instructions have a 7-bit signed offset field. Single insns
584 // have a 12-bit unsigned offset field. To be a valid combine, the
585 // final offset must be in range.
586 unsigned MIBaseReg = MI->getOperand(1).getReg();
587 int MIOffset = MI->getOperand(2).getImm();
588 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
589 (Offset + OffsetStride == MIOffset))) {
590 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
591 // If this is a volatile load/store that otherwise matched, stop looking
592 // as something is going on that we don't have enough information to
593 // safely transform. Similarly, stop if we see a hint to avoid pairs.
594 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
596 // If the resultant immediate offset of merging these instructions
597 // is out of range for a pairwise instruction, bail and keep looking.
598 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
599 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
600 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
601 if (MI->mayLoadOrStore())
602 MemInsns.push_back(MI);
605 // If the alignment requirements of the paired (scaled) instruction
606 // can't express the offset of the unscaled input, bail and keep
608 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
609 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
610 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
611 if (MI->mayLoadOrStore())
612 MemInsns.push_back(MI);
615 // If the destination register of the loads is the same register, bail
616 // and keep looking. A load-pair instruction with both destination
617 // registers the same is UNPREDICTABLE and will result in an exception.
618 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
619 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
620 if (MI->mayLoadOrStore())
621 MemInsns.push_back(MI);
625 // If the Rt of the second instruction was not modified or used between
626 // the two instructions and none of the instructions between the second
627 // and first alias with the second, we can combine the second into the
629 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
630 !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
631 !mayAlias(MI, MemInsns, TII)) {
632 Flags.setMergeForward(false);
636 // Likewise, if the Rt of the first instruction is not modified or used
637 // between the two instructions and none of the instructions between the
638 // first and the second alias with the first, we can combine the first
640 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
641 !(FirstMI->mayLoad() &&
642 UsedRegs[FirstMI->getOperand(0).getReg()]) &&
643 !mayAlias(FirstMI, MemInsns, TII)) {
644 Flags.setMergeForward(true);
647 // Unable to combine these instructions due to interference in between.
652 // If the instruction wasn't a matching load or store. Stop searching if we
653 // encounter a call instruction that might modify memory.
657 // Update modified / uses register lists.
658 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
660 // Otherwise, if the base register is modified, we have no match, so
662 if (ModifiedRegs[BaseReg])
665 // Update list of instructions that read/write memory.
666 if (MI->mayLoadOrStore())
667 MemInsns.push_back(MI);
672 MachineBasicBlock::iterator
673 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
674 MachineBasicBlock::iterator Update) {
675 assert((Update->getOpcode() == AArch64::ADDXri ||
676 Update->getOpcode() == AArch64::SUBXri) &&
677 "Unexpected base register update instruction to merge!");
678 MachineBasicBlock::iterator NextI = I;
679 // Return the instruction following the merged instruction, which is
680 // the instruction following our unmerged load. Unless that's the add/sub
681 // instruction we're merging, in which case it's the one after that.
682 if (++NextI == Update)
685 int Value = Update->getOperand(2).getImm();
686 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
687 "Can't merge 1 << 12 offset into pre-indexed load / store");
688 if (Update->getOpcode() == AArch64::SUBXri)
691 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
692 MachineInstrBuilder MIB =
693 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
694 .addOperand(Update->getOperand(0))
695 .addOperand(I->getOperand(0))
696 .addOperand(I->getOperand(1))
700 DEBUG(dbgs() << "Creating pre-indexed load/store.");
701 DEBUG(dbgs() << " Replacing instructions:\n ");
702 DEBUG(I->print(dbgs()));
703 DEBUG(dbgs() << " ");
704 DEBUG(Update->print(dbgs()));
705 DEBUG(dbgs() << " with instruction:\n ");
706 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
707 DEBUG(dbgs() << "\n");
709 // Erase the old instructions for the block.
710 I->eraseFromParent();
711 Update->eraseFromParent();
716 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
717 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
718 assert((Update->getOpcode() == AArch64::ADDXri ||
719 Update->getOpcode() == AArch64::SUBXri) &&
720 "Unexpected base register update instruction to merge!");
721 MachineBasicBlock::iterator NextI = I;
722 // Return the instruction following the merged instruction, which is
723 // the instruction following our unmerged load. Unless that's the add/sub
724 // instruction we're merging, in which case it's the one after that.
725 if (++NextI == Update)
728 int Value = Update->getOperand(2).getImm();
729 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
730 "Can't merge 1 << 12 offset into post-indexed load / store");
731 if (Update->getOpcode() == AArch64::SUBXri)
734 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
735 MachineInstrBuilder MIB =
736 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
737 .addOperand(Update->getOperand(0))
738 .addOperand(I->getOperand(0))
739 .addOperand(I->getOperand(1))
743 DEBUG(dbgs() << "Creating post-indexed load/store.");
744 DEBUG(dbgs() << " Replacing instructions:\n ");
745 DEBUG(I->print(dbgs()));
746 DEBUG(dbgs() << " ");
747 DEBUG(Update->print(dbgs()));
748 DEBUG(dbgs() << " with instruction:\n ");
749 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
750 DEBUG(dbgs() << "\n");
752 // Erase the old instructions for the block.
753 I->eraseFromParent();
754 Update->eraseFromParent();
759 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
761 switch (MI->getOpcode()) {
764 case AArch64::SUBXri:
765 // Negate the offset for a SUB instruction.
768 case AArch64::ADDXri:
769 // Make sure it's a vanilla immediate operand, not a relocation or
770 // anything else we can't handle.
771 if (!MI->getOperand(2).isImm())
773 // Watch out for 1 << 12 shifted value.
774 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
776 // If the instruction has the base register as source and dest and the
777 // immediate will fit in a signed 9-bit integer, then we have a match.
778 if (MI->getOperand(0).getReg() == BaseReg &&
779 MI->getOperand(1).getReg() == BaseReg &&
780 MI->getOperand(2).getImm() <= 255 &&
781 MI->getOperand(2).getImm() >= -256) {
782 // If we have a non-zero Offset, we check that it matches the amount
783 // we're adding to the register.
784 if (!Offset || Offset == MI->getOperand(2).getImm())
792 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
793 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
794 MachineBasicBlock::iterator E = I->getParent()->end();
795 MachineInstr *MemMI = I;
796 MachineBasicBlock::iterator MBBI = I;
797 const MachineFunction &MF = *MemMI->getParent()->getParent();
799 unsigned DestReg = MemMI->getOperand(0).getReg();
800 unsigned BaseReg = MemMI->getOperand(1).getReg();
801 int Offset = MemMI->getOperand(2).getImm() *
802 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
804 // If the base register overlaps the destination register, we can't
806 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
809 // Scan forward looking for post-index opportunities.
810 // Updating instructions can't be formed if the memory insn already
811 // has an offset other than the value we're looking for.
815 // Track which registers have been modified and used between the first insn
816 // (inclusive) and the second insn.
817 BitVector ModifiedRegs, UsedRegs;
818 ModifiedRegs.resize(TRI->getNumRegs());
819 UsedRegs.resize(TRI->getNumRegs());
821 for (unsigned Count = 0; MBBI != E; ++MBBI) {
822 MachineInstr *MI = MBBI;
823 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
824 // optimization by changing how far we scan.
825 if (MI->isDebugValue())
828 // Now that we know this is a real instruction, count it.
831 // If we found a match, return it.
832 if (isMatchingUpdateInsn(MI, BaseReg, Value))
835 // Update the status of what the instruction clobbered and used.
836 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
838 // Otherwise, if the base register is used or modified, we have no match, so
840 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
846 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
847 MachineBasicBlock::iterator I, unsigned Limit) {
848 MachineBasicBlock::iterator B = I->getParent()->begin();
849 MachineBasicBlock::iterator E = I->getParent()->end();
850 MachineInstr *MemMI = I;
851 MachineBasicBlock::iterator MBBI = I;
852 const MachineFunction &MF = *MemMI->getParent()->getParent();
854 unsigned DestReg = MemMI->getOperand(0).getReg();
855 unsigned BaseReg = MemMI->getOperand(1).getReg();
856 int Offset = MemMI->getOperand(2).getImm();
857 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
859 // If the load/store is the first instruction in the block, there's obviously
860 // not any matching update. Ditto if the memory offset isn't zero.
861 if (MBBI == B || Offset != 0)
863 // If the base register overlaps the destination register, we can't
865 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
868 // Track which registers have been modified and used between the first insn
869 // (inclusive) and the second insn.
870 BitVector ModifiedRegs, UsedRegs;
871 ModifiedRegs.resize(TRI->getNumRegs());
872 UsedRegs.resize(TRI->getNumRegs());
874 for (unsigned Count = 0; MBBI != B; --MBBI) {
875 MachineInstr *MI = MBBI;
876 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
877 // optimization by changing how far we scan.
878 if (MI->isDebugValue())
881 // Now that we know this is a real instruction, count it.
884 // If we found a match, return it.
885 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
888 // Update the status of what the instruction clobbered and used.
889 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
891 // Otherwise, if the base register is used or modified, we have no match, so
893 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
899 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
900 bool Modified = false;
901 // Two tranformations to do here:
902 // 1) Find loads and stores that can be merged into a single load or store
909 // 2) Find base register updates that can be merged into the load or store
910 // as a base-reg writeback.
917 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
919 MachineInstr *MI = MBBI;
920 switch (MI->getOpcode()) {
922 // Just move on to the next instruction.
925 case AArch64::STRSui:
926 case AArch64::STRDui:
927 case AArch64::STRQui:
928 case AArch64::STRXui:
929 case AArch64::STRWui:
930 case AArch64::LDRSui:
931 case AArch64::LDRDui:
932 case AArch64::LDRQui:
933 case AArch64::LDRXui:
934 case AArch64::LDRWui:
935 case AArch64::LDRSWui:
936 // do the unscaled versions as well
937 case AArch64::STURSi:
938 case AArch64::STURDi:
939 case AArch64::STURQi:
940 case AArch64::STURWi:
941 case AArch64::STURXi:
942 case AArch64::LDURSi:
943 case AArch64::LDURDi:
944 case AArch64::LDURQi:
945 case AArch64::LDURWi:
946 case AArch64::LDURXi:
947 case AArch64::LDURSWi: {
948 // If this is a volatile load/store, don't mess with it.
949 if (MI->hasOrderedMemoryRef()) {
953 // Make sure this is a reg+imm (as opposed to an address reloc).
954 if (!MI->getOperand(2).isImm()) {
958 // Check if this load/store has a hint to avoid pair formation.
959 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
960 if (TII->isLdStPairSuppressed(MI)) {
964 // Look ahead up to ScanLimit instructions for a pairable instruction.
966 MachineBasicBlock::iterator Paired =
967 findMatchingInsn(MBBI, Flags, ScanLimit);
969 // Merge the loads into a pair. Keeping the iterator straight is a
970 // pain, so we let the merge routine tell us what the next instruction
971 // is after it's done mucking about.
972 MBBI = mergePairedInsns(MBBI, Paired, Flags);
976 if (isUnscaledLdst(MI->getOpcode()))
977 ++NumUnscaledPairCreated;
983 // FIXME: Do the other instructions.
987 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
989 MachineInstr *MI = MBBI;
990 // Do update merging. It's simpler to keep this separate from the above
991 // switch, though not strictly necessary.
992 unsigned Opc = MI->getOpcode();
995 // Just move on to the next instruction.
998 case AArch64::STRSui:
999 case AArch64::STRDui:
1000 case AArch64::STRQui:
1001 case AArch64::STRXui:
1002 case AArch64::STRWui:
1003 case AArch64::LDRSui:
1004 case AArch64::LDRDui:
1005 case AArch64::LDRQui:
1006 case AArch64::LDRXui:
1007 case AArch64::LDRWui:
1008 // do the unscaled versions as well
1009 case AArch64::STURSi:
1010 case AArch64::STURDi:
1011 case AArch64::STURQi:
1012 case AArch64::STURWi:
1013 case AArch64::STURXi:
1014 case AArch64::LDURSi:
1015 case AArch64::LDURDi:
1016 case AArch64::LDURQi:
1017 case AArch64::LDURWi:
1018 case AArch64::LDURXi: {
1019 // Make sure this is a reg+imm (as opposed to an address reloc).
1020 if (!MI->getOperand(2).isImm()) {
1024 // Look ahead up to ScanLimit instructions for a mergable instruction.
1025 MachineBasicBlock::iterator Update =
1026 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1028 // Merge the update into the ld/st.
1029 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1034 // Don't know how to handle pre/post-index versions, so move to the next
1036 if (isUnscaledLdst(Opc)) {
1041 // Look back to try to find a pre-index instruction. For example,
1045 // ldr x1, [x0, #8]!
1046 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1048 // Merge the update into the ld/st.
1049 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1055 // Look forward to try to find a post-index instruction. For example,
1056 // ldr x1, [x0, #64]
1059 // ldr x1, [x0, #64]!
1061 // The immediate in the load/store is scaled by the size of the register
1062 // being loaded. The immediate in the add we're looking for,
1063 // however, is not, so adjust here.
1064 int Value = MI->getOperand(2).getImm() *
1065 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1067 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1069 // Merge the update into the ld/st.
1070 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1076 // Nothing found. Just move to the next instruction.
1080 // FIXME: Do the other instructions.
1087 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1088 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1089 TRI = Fn.getSubtarget().getRegisterInfo();
1091 bool Modified = false;
1092 for (auto &MBB : Fn)
1093 Modified |= optimizeBlock(MBB);
1098 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1099 // loads and stores near one another?
1101 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1102 /// load / store optimization pass.
1103 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1104 return new AArch64LoadStoreOpt();