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 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37 STATISTIC(NumPostFolded, "Number of post-index updates folded");
38 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39 STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
41 STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
42 STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
44 // The LdStLimit limits how far we search for load/store pairs.
45 static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
46 cl::init(20), cl::Hidden);
48 // The UpdateLimit limits how far we search for update instructions when we form
49 // pre-/post-index instructions.
50 static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
53 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
57 typedef struct LdStPairFlags {
58 // If a matching instruction is found, MergeForward is set to true if the
59 // merge is to remove the first instruction and replace the second with
60 // a pair-wise insn, and false if the reverse is true.
63 // SExtIdx gives the index of the result of the load pair that must be
64 // extended. The value of SExtIdx assumes that the paired load produces the
65 // value in this order: (I, returned iterator), i.e., -1 means no value has
66 // to be extended, 0 means I, and 1 means the returned iterator.
69 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
71 void setMergeForward(bool V = true) { MergeForward = V; }
72 bool getMergeForward() const { return MergeForward; }
74 void setSExtIdx(int V) { SExtIdx = V; }
75 int getSExtIdx() const { return SExtIdx; }
79 struct AArch64LoadStoreOpt : public MachineFunctionPass {
81 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
82 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
85 const AArch64InstrInfo *TII;
86 const TargetRegisterInfo *TRI;
87 const AArch64Subtarget *Subtarget;
89 // Track which registers have been modified and used.
90 BitVector ModifiedRegs, UsedRegs;
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 bool FindNarrowMerge);
100 // Scan the instructions looking for a store that writes to the address from
101 // which the current load instruction reads. Return true if one is found.
102 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
103 MachineBasicBlock::iterator &StoreI);
105 // Merge the two instructions indicated into a wider narrow store instruction.
106 MachineBasicBlock::iterator
107 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
108 MachineBasicBlock::iterator MergeMI,
109 const LdStPairFlags &Flags);
111 // Merge the two instructions indicated into a single pair-wise instruction.
112 MachineBasicBlock::iterator
113 mergePairedInsns(MachineBasicBlock::iterator I,
114 MachineBasicBlock::iterator Paired,
115 const LdStPairFlags &Flags);
117 // Promote the load that reads directly from the address stored to.
118 MachineBasicBlock::iterator
119 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
120 MachineBasicBlock::iterator StoreI);
122 // Scan the instruction list to find a base register update that can
123 // be combined with the current instruction (a load or store) using
124 // pre or post indexed addressing with writeback. Scan forwards.
125 MachineBasicBlock::iterator
126 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
127 int UnscaledOffset, unsigned Limit);
129 // Scan the instruction list to find a base register update that can
130 // be combined with the current instruction (a load or store) using
131 // pre or post indexed addressing with writeback. Scan backwards.
132 MachineBasicBlock::iterator
133 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
135 // Find an instruction that updates the base register of the ld/st
137 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
138 unsigned BaseReg, int Offset);
140 // Merge a pre- or post-index base register update into a ld/st instruction.
141 MachineBasicBlock::iterator
142 mergeUpdateInsn(MachineBasicBlock::iterator I,
143 MachineBasicBlock::iterator Update, bool IsPreIdx);
145 // Find and merge zero store instructions.
146 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
148 // Find and pair ldr/str instructions.
149 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
151 // Find and promote load instructions which read directly from store.
152 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
154 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
156 bool runOnMachineFunction(MachineFunction &Fn) override;
158 MachineFunctionProperties getRequiredProperties() const override {
159 return MachineFunctionProperties().set(
160 MachineFunctionProperties::Property::NoVRegs);
163 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
165 char AArch64LoadStoreOpt::ID = 0;
168 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
169 AARCH64_LOAD_STORE_OPT_NAME, false, false)
171 static bool isNarrowStore(unsigned Opc) {
175 case AArch64::STRBBui:
176 case AArch64::STURBBi:
177 case AArch64::STRHHui:
178 case AArch64::STURHHi:
183 // Scaling factor for unscaled load or store.
184 static int getMemScale(MachineInstr &MI) {
185 switch (MI.getOpcode()) {
187 llvm_unreachable("Opcode has unknown scale!");
188 case AArch64::LDRBBui:
189 case AArch64::LDURBBi:
190 case AArch64::LDRSBWui:
191 case AArch64::LDURSBWi:
192 case AArch64::STRBBui:
193 case AArch64::STURBBi:
195 case AArch64::LDRHHui:
196 case AArch64::LDURHHi:
197 case AArch64::LDRSHWui:
198 case AArch64::LDURSHWi:
199 case AArch64::STRHHui:
200 case AArch64::STURHHi:
202 case AArch64::LDRSui:
203 case AArch64::LDURSi:
204 case AArch64::LDRSWui:
205 case AArch64::LDURSWi:
206 case AArch64::LDRWui:
207 case AArch64::LDURWi:
208 case AArch64::STRSui:
209 case AArch64::STURSi:
210 case AArch64::STRWui:
211 case AArch64::STURWi:
213 case AArch64::LDPSWi:
218 case AArch64::LDRDui:
219 case AArch64::LDURDi:
220 case AArch64::LDRXui:
221 case AArch64::LDURXi:
222 case AArch64::STRDui:
223 case AArch64::STURDi:
224 case AArch64::STRXui:
225 case AArch64::STURXi:
231 case AArch64::LDRQui:
232 case AArch64::LDURQi:
233 case AArch64::STRQui:
234 case AArch64::STURQi:
241 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
242 bool *IsValidLdStrOpc = nullptr) {
244 *IsValidLdStrOpc = true;
248 *IsValidLdStrOpc = false;
250 case AArch64::STRDui:
251 case AArch64::STURDi:
252 case AArch64::STRQui:
253 case AArch64::STURQi:
254 case AArch64::STRBBui:
255 case AArch64::STURBBi:
256 case AArch64::STRHHui:
257 case AArch64::STURHHi:
258 case AArch64::STRWui:
259 case AArch64::STURWi:
260 case AArch64::STRXui:
261 case AArch64::STURXi:
262 case AArch64::LDRDui:
263 case AArch64::LDURDi:
264 case AArch64::LDRQui:
265 case AArch64::LDURQi:
266 case AArch64::LDRWui:
267 case AArch64::LDURWi:
268 case AArch64::LDRXui:
269 case AArch64::LDURXi:
270 case AArch64::STRSui:
271 case AArch64::STURSi:
272 case AArch64::LDRSui:
273 case AArch64::LDURSi:
275 case AArch64::LDRSWui:
276 return AArch64::LDRWui;
277 case AArch64::LDURSWi:
278 return AArch64::LDURWi;
282 static unsigned getMatchingWideOpcode(unsigned Opc) {
285 llvm_unreachable("Opcode has no wide equivalent!");
286 case AArch64::STRBBui:
287 return AArch64::STRHHui;
288 case AArch64::STRHHui:
289 return AArch64::STRWui;
290 case AArch64::STURBBi:
291 return AArch64::STURHHi;
292 case AArch64::STURHHi:
293 return AArch64::STURWi;
294 case AArch64::STURWi:
295 return AArch64::STURXi;
296 case AArch64::STRWui:
297 return AArch64::STRXui;
301 static unsigned getMatchingPairOpcode(unsigned Opc) {
304 llvm_unreachable("Opcode has no pairwise equivalent!");
305 case AArch64::STRSui:
306 case AArch64::STURSi:
307 return AArch64::STPSi;
308 case AArch64::STRDui:
309 case AArch64::STURDi:
310 return AArch64::STPDi;
311 case AArch64::STRQui:
312 case AArch64::STURQi:
313 return AArch64::STPQi;
314 case AArch64::STRWui:
315 case AArch64::STURWi:
316 return AArch64::STPWi;
317 case AArch64::STRXui:
318 case AArch64::STURXi:
319 return AArch64::STPXi;
320 case AArch64::LDRSui:
321 case AArch64::LDURSi:
322 return AArch64::LDPSi;
323 case AArch64::LDRDui:
324 case AArch64::LDURDi:
325 return AArch64::LDPDi;
326 case AArch64::LDRQui:
327 case AArch64::LDURQi:
328 return AArch64::LDPQi;
329 case AArch64::LDRWui:
330 case AArch64::LDURWi:
331 return AArch64::LDPWi;
332 case AArch64::LDRXui:
333 case AArch64::LDURXi:
334 return AArch64::LDPXi;
335 case AArch64::LDRSWui:
336 case AArch64::LDURSWi:
337 return AArch64::LDPSWi;
341 static unsigned isMatchingStore(MachineInstr &LoadInst,
342 MachineInstr &StoreInst) {
343 unsigned LdOpc = LoadInst.getOpcode();
344 unsigned StOpc = StoreInst.getOpcode();
347 llvm_unreachable("Unsupported load instruction!");
348 case AArch64::LDRBBui:
349 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
350 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
351 case AArch64::LDURBBi:
352 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
353 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
354 case AArch64::LDRHHui:
355 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
356 StOpc == AArch64::STRXui;
357 case AArch64::LDURHHi:
358 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
359 StOpc == AArch64::STURXi;
360 case AArch64::LDRWui:
361 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
362 case AArch64::LDURWi:
363 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
364 case AArch64::LDRXui:
365 return StOpc == AArch64::STRXui;
366 case AArch64::LDURXi:
367 return StOpc == AArch64::STURXi;
371 static unsigned getPreIndexedOpcode(unsigned Opc) {
374 llvm_unreachable("Opcode has no pre-indexed equivalent!");
375 case AArch64::STRSui:
376 return AArch64::STRSpre;
377 case AArch64::STRDui:
378 return AArch64::STRDpre;
379 case AArch64::STRQui:
380 return AArch64::STRQpre;
381 case AArch64::STRBBui:
382 return AArch64::STRBBpre;
383 case AArch64::STRHHui:
384 return AArch64::STRHHpre;
385 case AArch64::STRWui:
386 return AArch64::STRWpre;
387 case AArch64::STRXui:
388 return AArch64::STRXpre;
389 case AArch64::LDRSui:
390 return AArch64::LDRSpre;
391 case AArch64::LDRDui:
392 return AArch64::LDRDpre;
393 case AArch64::LDRQui:
394 return AArch64::LDRQpre;
395 case AArch64::LDRBBui:
396 return AArch64::LDRBBpre;
397 case AArch64::LDRHHui:
398 return AArch64::LDRHHpre;
399 case AArch64::LDRWui:
400 return AArch64::LDRWpre;
401 case AArch64::LDRXui:
402 return AArch64::LDRXpre;
403 case AArch64::LDRSWui:
404 return AArch64::LDRSWpre;
406 return AArch64::LDPSpre;
407 case AArch64::LDPSWi:
408 return AArch64::LDPSWpre;
410 return AArch64::LDPDpre;
412 return AArch64::LDPQpre;
414 return AArch64::LDPWpre;
416 return AArch64::LDPXpre;
418 return AArch64::STPSpre;
420 return AArch64::STPDpre;
422 return AArch64::STPQpre;
424 return AArch64::STPWpre;
426 return AArch64::STPXpre;
430 static unsigned getPostIndexedOpcode(unsigned Opc) {
433 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
434 case AArch64::STRSui:
435 return AArch64::STRSpost;
436 case AArch64::STRDui:
437 return AArch64::STRDpost;
438 case AArch64::STRQui:
439 return AArch64::STRQpost;
440 case AArch64::STRBBui:
441 return AArch64::STRBBpost;
442 case AArch64::STRHHui:
443 return AArch64::STRHHpost;
444 case AArch64::STRWui:
445 return AArch64::STRWpost;
446 case AArch64::STRXui:
447 return AArch64::STRXpost;
448 case AArch64::LDRSui:
449 return AArch64::LDRSpost;
450 case AArch64::LDRDui:
451 return AArch64::LDRDpost;
452 case AArch64::LDRQui:
453 return AArch64::LDRQpost;
454 case AArch64::LDRBBui:
455 return AArch64::LDRBBpost;
456 case AArch64::LDRHHui:
457 return AArch64::LDRHHpost;
458 case AArch64::LDRWui:
459 return AArch64::LDRWpost;
460 case AArch64::LDRXui:
461 return AArch64::LDRXpost;
462 case AArch64::LDRSWui:
463 return AArch64::LDRSWpost;
465 return AArch64::LDPSpost;
466 case AArch64::LDPSWi:
467 return AArch64::LDPSWpost;
469 return AArch64::LDPDpost;
471 return AArch64::LDPQpost;
473 return AArch64::LDPWpost;
475 return AArch64::LDPXpost;
477 return AArch64::STPSpost;
479 return AArch64::STPDpost;
481 return AArch64::STPQpost;
483 return AArch64::STPWpost;
485 return AArch64::STPXpost;
489 static bool isPairedLdSt(const MachineInstr &MI) {
490 switch (MI.getOpcode()) {
494 case AArch64::LDPSWi:
508 static const MachineOperand &getLdStRegOp(const MachineInstr &MI,
509 unsigned PairedRegOp = 0) {
510 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
511 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
512 return MI.getOperand(Idx);
515 static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
516 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
517 return MI.getOperand(Idx);
520 static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
521 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
522 return MI.getOperand(Idx);
525 static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
526 MachineInstr &StoreInst,
527 const AArch64InstrInfo *TII) {
528 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
529 int LoadSize = getMemScale(LoadInst);
530 int StoreSize = getMemScale(StoreInst);
531 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
532 ? getLdStOffsetOp(StoreInst).getImm()
533 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
534 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
535 ? getLdStOffsetOp(LoadInst).getImm()
536 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
537 return (UnscaledStOffset <= UnscaledLdOffset) &&
538 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
541 static bool isPromotableZeroStoreInst(MachineInstr &MI) {
542 unsigned Opc = MI.getOpcode();
543 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
544 isNarrowStore(Opc)) &&
545 getLdStRegOp(MI).getReg() == AArch64::WZR;
548 MachineBasicBlock::iterator
549 AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
550 MachineBasicBlock::iterator MergeMI,
551 const LdStPairFlags &Flags) {
552 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
553 "Expected promotable zero stores.");
555 MachineBasicBlock::iterator NextI = I;
557 // If NextI is the second of the two instructions to be merged, we need
558 // to skip one further. Either way we merge will invalidate the iterator,
559 // and we don't need to scan the new instruction, as it's a pairwise
560 // instruction, which we're not considering for further action anyway.
561 if (NextI == MergeMI)
564 unsigned Opc = I->getOpcode();
565 bool IsScaled = !TII->isUnscaledLdSt(Opc);
566 int OffsetStride = IsScaled ? 1 : getMemScale(*I);
568 bool MergeForward = Flags.getMergeForward();
569 // Insert our new paired instruction after whichever of the paired
570 // instructions MergeForward indicates.
571 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
572 // Also based on MergeForward is from where we copy the base register operand
573 // so we get the flags compatible with the input code.
574 const MachineOperand &BaseRegOp =
575 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
577 // Which register is Rt and which is Rt2 depends on the offset order.
579 if (getLdStOffsetOp(*I).getImm() ==
580 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
585 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
586 // Change the scaled offset from small to large type.
588 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
592 // Construct the new instruction.
593 DebugLoc DL = I->getDebugLoc();
594 MachineBasicBlock *MBB = I->getParent();
595 MachineInstrBuilder MIB;
596 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
597 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
598 .addOperand(BaseRegOp)
600 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
603 DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
604 DEBUG(I->print(dbgs()));
605 DEBUG(dbgs() << " ");
606 DEBUG(MergeMI->print(dbgs()));
607 DEBUG(dbgs() << " with instruction:\n ");
608 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
609 DEBUG(dbgs() << "\n");
611 // Erase the old instructions.
612 I->eraseFromParent();
613 MergeMI->eraseFromParent();
617 MachineBasicBlock::iterator
618 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
619 MachineBasicBlock::iterator Paired,
620 const LdStPairFlags &Flags) {
621 MachineBasicBlock::iterator NextI = I;
623 // If NextI is the second of the two instructions to be merged, we need
624 // to skip one further. Either way we merge will invalidate the iterator,
625 // and we don't need to scan the new instruction, as it's a pairwise
626 // instruction, which we're not considering for further action anyway.
630 int SExtIdx = Flags.getSExtIdx();
632 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
633 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
634 int OffsetStride = IsUnscaled ? getMemScale(*I) : 1;
636 bool MergeForward = Flags.getMergeForward();
637 // Insert our new paired instruction after whichever of the paired
638 // instructions MergeForward indicates.
639 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
640 // Also based on MergeForward is from where we copy the base register operand
641 // so we get the flags compatible with the input code.
642 const MachineOperand &BaseRegOp =
643 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
645 int Offset = getLdStOffsetOp(*I).getImm();
646 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
647 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
648 if (IsUnscaled != PairedIsUnscaled) {
649 // We're trying to pair instructions that differ in how they are scaled. If
650 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
651 // the opposite (i.e., make Paired's offset unscaled).
652 int MemSize = getMemScale(*Paired);
653 if (PairedIsUnscaled) {
654 // If the unscaled offset isn't a multiple of the MemSize, we can't
655 // pair the operations together.
656 assert(!(PairedOffset % getMemScale(*Paired)) &&
657 "Offset should be a multiple of the stride!");
658 PairedOffset /= MemSize;
660 PairedOffset *= MemSize;
664 // Which register is Rt and which is Rt2 depends on the offset order.
665 MachineInstr *RtMI, *Rt2MI;
666 if (Offset == PairedOffset + OffsetStride) {
669 // Here we swapped the assumption made for SExtIdx.
670 // I.e., we turn ldp I, Paired into ldp Paired, I.
671 // Update the index accordingly.
673 SExtIdx = (SExtIdx + 1) % 2;
678 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
679 // Scale the immediate offset, if necessary.
680 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
681 assert(!(OffsetImm % getMemScale(*RtMI)) &&
682 "Unscaled offset cannot be scaled.");
683 OffsetImm /= getMemScale(*RtMI);
686 // Construct the new instruction.
687 MachineInstrBuilder MIB;
688 DebugLoc DL = I->getDebugLoc();
689 MachineBasicBlock *MBB = I->getParent();
690 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
691 .addOperand(getLdStRegOp(*RtMI))
692 .addOperand(getLdStRegOp(*Rt2MI))
693 .addOperand(BaseRegOp)
695 .setMemRefs(I->mergeMemRefsWith(*Paired));
699 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
700 DEBUG(I->print(dbgs()));
701 DEBUG(dbgs() << " ");
702 DEBUG(Paired->print(dbgs()));
703 DEBUG(dbgs() << " with instruction:\n ");
705 // Generate the sign extension for the proper result of the ldp.
706 // I.e., with X1, that would be:
707 // %W1<def> = KILL %W1, %X1<imp-def>
708 // %X1<def> = SBFMXri %X1<kill>, 0, 31
709 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
710 // Right now, DstMO has the extended register, since it comes from an
712 unsigned DstRegX = DstMO.getReg();
713 // Get the W variant of that register.
714 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
715 // Update the result of LDP to use the W instead of the X variant.
716 DstMO.setReg(DstRegW);
717 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
718 DEBUG(dbgs() << "\n");
719 // Make the machine verifier happy by providing a definition for
721 // Insert this definition right after the generated LDP, i.e., before
723 MachineInstrBuilder MIBKill =
724 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
726 .addReg(DstRegX, RegState::Define);
727 MIBKill->getOperand(2).setImplicit();
728 // Create the sign extension.
729 MachineInstrBuilder MIBSXTW =
730 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
735 DEBUG(dbgs() << " Extend operand:\n ");
736 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
738 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
740 DEBUG(dbgs() << "\n");
742 // Erase the old instructions.
743 I->eraseFromParent();
744 Paired->eraseFromParent();
749 MachineBasicBlock::iterator
750 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
751 MachineBasicBlock::iterator StoreI) {
752 MachineBasicBlock::iterator NextI = LoadI;
755 int LoadSize = getMemScale(*LoadI);
756 int StoreSize = getMemScale(*StoreI);
757 unsigned LdRt = getLdStRegOp(*LoadI).getReg();
758 unsigned StRt = getLdStRegOp(*StoreI).getReg();
759 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
761 assert((IsStoreXReg ||
762 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
763 "Unexpected RegClass");
765 MachineInstr *BitExtMI;
766 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
767 // Remove the load, if the destination register of the loads is the same
768 // register for stored value.
769 if (StRt == LdRt && LoadSize == 8) {
770 StoreI->clearRegisterKills(StRt, TRI);
771 DEBUG(dbgs() << "Remove load instruction:\n ");
772 DEBUG(LoadI->print(dbgs()));
773 DEBUG(dbgs() << "\n");
774 LoadI->eraseFromParent();
777 // Replace the load with a mov if the load and store are in the same size.
779 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
780 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
781 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
783 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
785 // FIXME: Currently we disable this transformation in big-endian targets as
786 // performance and correctness are verified only in little-endian.
787 if (!Subtarget->isLittleEndian())
789 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
790 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
791 "Unsupported ld/st match");
792 assert(LoadSize <= StoreSize && "Invalid load size");
793 int UnscaledLdOffset = IsUnscaled
794 ? getLdStOffsetOp(*LoadI).getImm()
795 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
796 int UnscaledStOffset = IsUnscaled
797 ? getLdStOffsetOp(*StoreI).getImm()
798 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
799 int Width = LoadSize * 8;
800 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
801 int Imms = Immr + Width - 1;
802 unsigned DestReg = IsStoreXReg
803 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
804 &AArch64::GPR64RegClass)
807 assert((UnscaledLdOffset >= UnscaledStOffset &&
808 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
811 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
812 Imms = Immr + Width - 1;
813 if (UnscaledLdOffset == UnscaledStOffset) {
814 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
815 | ((Immr) << 6) // immr
816 | ((Imms) << 0) // imms
820 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
821 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
824 .addImm(AndMaskEncoded);
827 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
828 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
835 StoreI->clearRegisterKills(StRt, TRI);
839 DEBUG(dbgs() << "Promoting load by replacing :\n ");
840 DEBUG(StoreI->print(dbgs()));
841 DEBUG(dbgs() << " ");
842 DEBUG(LoadI->print(dbgs()));
843 DEBUG(dbgs() << " with instructions:\n ");
844 DEBUG(StoreI->print(dbgs()));
845 DEBUG(dbgs() << " ");
846 DEBUG((BitExtMI)->print(dbgs()));
847 DEBUG(dbgs() << "\n");
849 // Erase the old instructions.
850 LoadI->eraseFromParent();
854 /// trackRegDefsUses - Remember what registers the specified instruction uses
856 static void trackRegDefsUses(const MachineInstr &MI, BitVector &ModifiedRegs,
858 const TargetRegisterInfo *TRI) {
859 for (const MachineOperand &MO : MI.operands()) {
861 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
865 unsigned Reg = MO.getReg();
869 // WZR/XZR are not modified even when used as a destination register.
870 if (Reg != AArch64::WZR && Reg != AArch64::XZR)
871 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
872 ModifiedRegs.set(*AI);
874 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
875 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
881 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
882 // Convert the byte-offset used by unscaled into an "element" offset used
883 // by the scaled pair load/store instructions.
885 // If the byte-offset isn't a multiple of the stride, there's no point
886 // trying to match it.
887 if (Offset % OffsetStride)
889 Offset /= OffsetStride;
891 return Offset <= 63 && Offset >= -64;
894 // Do alignment, specialized to power of 2 and for signed ints,
895 // avoiding having to do a C-style cast from uint_64t to int when
896 // using alignTo from include/llvm/Support/MathExtras.h.
897 // FIXME: Move this function to include/MathExtras.h?
898 static int alignTo(int Num, int PowOf2) {
899 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
902 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
903 const AArch64InstrInfo *TII) {
904 // One of the instructions must modify memory.
905 if (!MIa.mayStore() && !MIb.mayStore())
908 // Both instructions must be memory operations.
909 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
912 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
915 static bool mayAlias(MachineInstr &MIa,
916 SmallVectorImpl<MachineInstr *> &MemInsns,
917 const AArch64InstrInfo *TII) {
918 for (MachineInstr *MIb : MemInsns)
919 if (mayAlias(MIa, *MIb, TII))
925 bool AArch64LoadStoreOpt::findMatchingStore(
926 MachineBasicBlock::iterator I, unsigned Limit,
927 MachineBasicBlock::iterator &StoreI) {
928 MachineBasicBlock::iterator B = I->getParent()->begin();
929 MachineBasicBlock::iterator MBBI = I;
930 MachineInstr &LoadMI = *I;
931 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
933 // If the load is the first instruction in the block, there's obviously
934 // not any matching store.
938 // Track which registers have been modified and used between the first insn
939 // and the second insn.
940 ModifiedRegs.reset();
946 MachineInstr &MI = *MBBI;
948 // Don't count transient instructions towards the search limit since there
949 // may be different numbers of them if e.g. debug information is present.
950 if (!MI.isTransient())
953 // If the load instruction reads directly from the address to which the
954 // store instruction writes and the stored value is not modified, we can
955 // promote the load. Since we do not handle stores with pre-/post-index,
956 // it's unnecessary to check if BaseReg is modified by the store itself.
957 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
958 BaseReg == getLdStBaseOp(MI).getReg() &&
959 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
960 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
968 // Update modified / uses register lists.
969 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
971 // Otherwise, if the base register is modified, we have no match, so
973 if (ModifiedRegs[BaseReg])
976 // If we encounter a store aliased with the load, return early.
977 if (MI.mayStore() && mayAlias(LoadMI, MI, TII))
979 } while (MBBI != B && Count < Limit);
983 // Returns true if FirstMI and MI are candidates for merging or pairing.
984 // Otherwise, returns false.
985 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
986 LdStPairFlags &Flags,
987 const AArch64InstrInfo *TII) {
988 // If this is volatile or if pairing is suppressed, not a candidate.
989 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
992 // We should have already checked FirstMI for pair suppression and volatility.
993 assert(!FirstMI.hasOrderedMemoryRef() &&
994 !TII->isLdStPairSuppressed(FirstMI) &&
995 "FirstMI shouldn't get here if either of these checks are true.");
997 unsigned OpcA = FirstMI.getOpcode();
998 unsigned OpcB = MI.getOpcode();
1000 // Opcodes match: nothing more to check.
1004 // Try to match a sign-extended load/store with a zero-extended load/store.
1005 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1006 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1007 assert(IsValidLdStrOpc &&
1008 "Given Opc should be a Load or Store with an immediate");
1009 // OpcA will be the first instruction in the pair.
1010 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1011 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1015 // If the second instruction isn't even a mergable/pairable load/store, bail
1017 if (!PairIsValidLdStrOpc)
1020 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1022 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1025 // Try to match an unscaled load/store with a scaled load/store.
1026 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1027 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1029 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1032 /// Scan the instructions looking for a load/store that can be combined with the
1033 /// current instruction into a wider equivalent or a load/store pair.
1034 MachineBasicBlock::iterator
1035 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1036 LdStPairFlags &Flags, unsigned Limit,
1037 bool FindNarrowMerge) {
1038 MachineBasicBlock::iterator E = I->getParent()->end();
1039 MachineBasicBlock::iterator MBBI = I;
1040 MachineInstr &FirstMI = *I;
1043 bool MayLoad = FirstMI.mayLoad();
1044 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1045 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1046 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1047 int Offset = getLdStOffsetOp(FirstMI).getImm();
1048 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
1049 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1051 // Track which registers have been modified and used between the first insn
1052 // (inclusive) and the second insn.
1053 ModifiedRegs.reset();
1056 // Remember any instructions that read/write memory between FirstMI and MI.
1057 SmallVector<MachineInstr *, 4> MemInsns;
1059 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1060 MachineInstr &MI = *MBBI;
1062 // Don't count transient instructions towards the search limit since there
1063 // may be different numbers of them if e.g. debug information is present.
1064 if (!MI.isTransient())
1067 Flags.setSExtIdx(-1);
1068 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1069 getLdStOffsetOp(MI).isImm()) {
1070 assert(MI.mayLoadOrStore() && "Expected memory operation.");
1071 // If we've found another instruction with the same opcode, check to see
1072 // if the base and offset are compatible with our starting instruction.
1073 // These instructions all have scaled immediate operands, so we just
1074 // check for +1/-1. Make sure to check the new instruction offset is
1075 // actually an immediate and not a symbolic reference destined for
1077 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1078 int MIOffset = getLdStOffsetOp(MI).getImm();
1079 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1080 if (IsUnscaled != MIIsUnscaled) {
1081 // We're trying to pair instructions that differ in how they are scaled.
1082 // If FirstMI is scaled then scale the offset of MI accordingly.
1083 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1084 int MemSize = getMemScale(MI);
1086 // If the unscaled offset isn't a multiple of the MemSize, we can't
1087 // pair the operations together: bail and keep looking.
1088 if (MIOffset % MemSize) {
1089 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1090 MemInsns.push_back(&MI);
1093 MIOffset /= MemSize;
1095 MIOffset *= MemSize;
1099 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1100 (Offset + OffsetStride == MIOffset))) {
1101 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1102 if (FindNarrowMerge) {
1103 // If the alignment requirements of the scaled wide load/store
1104 // instruction can't express the offset of the scaled narrow input,
1105 // bail and keep looking. For promotable zero stores, allow only when
1106 // the stored value is the same (i.e., WZR).
1107 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1108 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1109 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1110 MemInsns.push_back(&MI);
1114 // Pairwise instructions have a 7-bit signed offset field. Single
1115 // insns have a 12-bit unsigned offset field. If the resultant
1116 // immediate offset of merging these instructions is out of range for
1117 // a pairwise instruction, bail and keep looking.
1118 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1119 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1120 MemInsns.push_back(&MI);
1123 // If the alignment requirements of the paired (scaled) instruction
1124 // can't express the offset of the unscaled input, bail and keep
1126 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1127 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1128 MemInsns.push_back(&MI);
1132 // If the destination register of the loads is the same register, bail
1133 // and keep looking. A load-pair instruction with both destination
1134 // registers the same is UNPREDICTABLE and will result in an exception.
1135 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1136 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1137 MemInsns.push_back(&MI);
1141 // If the Rt of the second instruction was not modified or used between
1142 // the two instructions and none of the instructions between the second
1143 // and first alias with the second, we can combine the second into the
1145 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1146 !(MI.mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
1147 !mayAlias(MI, MemInsns, TII)) {
1148 Flags.setMergeForward(false);
1152 // Likewise, if the Rt of the first instruction is not modified or used
1153 // between the two instructions and none of the instructions between the
1154 // first and the second alias with the first, we can combine the first
1156 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
1157 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
1158 !mayAlias(FirstMI, MemInsns, TII)) {
1159 Flags.setMergeForward(true);
1162 // Unable to combine these instructions due to interference in between.
1167 // If the instruction wasn't a matching load or store. Stop searching if we
1168 // encounter a call instruction that might modify memory.
1172 // Update modified / uses register lists.
1173 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1175 // Otherwise, if the base register is modified, we have no match, so
1177 if (ModifiedRegs[BaseReg])
1180 // Update list of instructions that read/write memory.
1181 if (MI.mayLoadOrStore())
1182 MemInsns.push_back(&MI);
1187 MachineBasicBlock::iterator
1188 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1189 MachineBasicBlock::iterator Update,
1191 assert((Update->getOpcode() == AArch64::ADDXri ||
1192 Update->getOpcode() == AArch64::SUBXri) &&
1193 "Unexpected base register update instruction to merge!");
1194 MachineBasicBlock::iterator NextI = I;
1195 // Return the instruction following the merged instruction, which is
1196 // the instruction following our unmerged load. Unless that's the add/sub
1197 // instruction we're merging, in which case it's the one after that.
1198 if (++NextI == Update)
1201 int Value = Update->getOperand(2).getImm();
1202 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1203 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1204 if (Update->getOpcode() == AArch64::SUBXri)
1207 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1208 : getPostIndexedOpcode(I->getOpcode());
1209 MachineInstrBuilder MIB;
1210 if (!isPairedLdSt(*I)) {
1211 // Non-paired instruction.
1212 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1213 .addOperand(getLdStRegOp(*Update))
1214 .addOperand(getLdStRegOp(*I))
1215 .addOperand(getLdStBaseOp(*I))
1217 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
1219 // Paired instruction.
1220 int Scale = getMemScale(*I);
1221 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1222 .addOperand(getLdStRegOp(*Update))
1223 .addOperand(getLdStRegOp(*I, 0))
1224 .addOperand(getLdStRegOp(*I, 1))
1225 .addOperand(getLdStBaseOp(*I))
1226 .addImm(Value / Scale)
1227 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
1232 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1234 DEBUG(dbgs() << "Creating post-indexed load/store.");
1235 DEBUG(dbgs() << " Replacing instructions:\n ");
1236 DEBUG(I->print(dbgs()));
1237 DEBUG(dbgs() << " ");
1238 DEBUG(Update->print(dbgs()));
1239 DEBUG(dbgs() << " with instruction:\n ");
1240 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1241 DEBUG(dbgs() << "\n");
1243 // Erase the old instructions for the block.
1244 I->eraseFromParent();
1245 Update->eraseFromParent();
1250 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1252 unsigned BaseReg, int Offset) {
1253 switch (MI.getOpcode()) {
1256 case AArch64::SUBXri:
1257 case AArch64::ADDXri:
1258 // Make sure it's a vanilla immediate operand, not a relocation or
1259 // anything else we can't handle.
1260 if (!MI.getOperand(2).isImm())
1262 // Watch out for 1 << 12 shifted value.
1263 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1266 // The update instruction source and destination register must be the
1267 // same as the load/store base register.
1268 if (MI.getOperand(0).getReg() != BaseReg ||
1269 MI.getOperand(1).getReg() != BaseReg)
1272 bool IsPairedInsn = isPairedLdSt(MemMI);
1273 int UpdateOffset = MI.getOperand(2).getImm();
1274 if (MI.getOpcode() == AArch64::SUBXri)
1275 UpdateOffset = -UpdateOffset;
1277 // For non-paired load/store instructions, the immediate must fit in a
1278 // signed 9-bit integer.
1279 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1282 // For paired load/store instructions, the immediate must be a multiple of
1283 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1286 int Scale = getMemScale(MemMI);
1287 if (UpdateOffset % Scale != 0)
1290 int ScaledOffset = UpdateOffset / Scale;
1291 if (ScaledOffset > 63 || ScaledOffset < -64)
1295 // If we have a non-zero Offset, we check that it matches the amount
1296 // we're adding to the register.
1297 if (!Offset || Offset == UpdateOffset)
1304 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1305 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1306 MachineBasicBlock::iterator E = I->getParent()->end();
1307 MachineInstr &MemMI = *I;
1308 MachineBasicBlock::iterator MBBI = I;
1310 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1311 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
1313 // Scan forward looking for post-index opportunities. Updating instructions
1314 // can't be formed if the memory instruction doesn't have the offset we're
1316 if (MIUnscaledOffset != UnscaledOffset)
1319 // If the base register overlaps a destination register, we can't
1320 // merge the update.
1321 bool IsPairedInsn = isPairedLdSt(MemMI);
1322 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1323 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1324 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1328 // Track which registers have been modified and used between the first insn
1329 // (inclusive) and the second insn.
1330 ModifiedRegs.reset();
1333 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1334 MachineInstr &MI = *MBBI;
1336 // Don't count transient instructions towards the search limit since there
1337 // may be different numbers of them if e.g. debug information is present.
1338 if (!MI.isTransient())
1341 // If we found a match, return it.
1342 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1345 // Update the status of what the instruction clobbered and used.
1346 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1348 // Otherwise, if the base register is used or modified, we have no match, so
1350 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1356 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1357 MachineBasicBlock::iterator I, unsigned Limit) {
1358 MachineBasicBlock::iterator B = I->getParent()->begin();
1359 MachineBasicBlock::iterator E = I->getParent()->end();
1360 MachineInstr &MemMI = *I;
1361 MachineBasicBlock::iterator MBBI = I;
1363 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1364 int Offset = getLdStOffsetOp(MemMI).getImm();
1366 // If the load/store is the first instruction in the block, there's obviously
1367 // not any matching update. Ditto if the memory offset isn't zero.
1368 if (MBBI == B || Offset != 0)
1370 // If the base register overlaps a destination register, we can't
1371 // merge the update.
1372 bool IsPairedInsn = isPairedLdSt(MemMI);
1373 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1374 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1375 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1379 // Track which registers have been modified and used between the first insn
1380 // (inclusive) and the second insn.
1381 ModifiedRegs.reset();
1386 MachineInstr &MI = *MBBI;
1388 // Don't count transient instructions towards the search limit since there
1389 // may be different numbers of them if e.g. debug information is present.
1390 if (!MI.isTransient())
1393 // If we found a match, return it.
1394 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1397 // Update the status of what the instruction clobbered and used.
1398 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1400 // Otherwise, if the base register is used or modified, we have no match, so
1402 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1404 } while (MBBI != B && Count < Limit);
1408 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1409 MachineBasicBlock::iterator &MBBI) {
1410 MachineInstr &MI = *MBBI;
1411 // If this is a volatile load, don't mess with it.
1412 if (MI.hasOrderedMemoryRef())
1415 // Make sure this is a reg+imm.
1416 // FIXME: It is possible to extend it to handle reg+reg cases.
1417 if (!getLdStOffsetOp(MI).isImm())
1420 // Look backward up to LdStLimit instructions.
1421 MachineBasicBlock::iterator StoreI;
1422 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1423 ++NumLoadsFromStoresPromoted;
1424 // Promote the load. Keeping the iterator straight is a
1425 // pain, so we let the merge routine tell us what the next instruction
1426 // is after it's done mucking about.
1427 MBBI = promoteLoadFromStore(MBBI, StoreI);
1433 // Merge adjacent zero stores into a wider store.
1434 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1435 MachineBasicBlock::iterator &MBBI) {
1436 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1437 MachineInstr &MI = *MBBI;
1438 MachineBasicBlock::iterator E = MI.getParent()->end();
1440 if (!TII->isCandidateToMergeOrPair(MI))
1443 // Look ahead up to LdStLimit instructions for a mergable instruction.
1444 LdStPairFlags Flags;
1445 MachineBasicBlock::iterator MergeMI =
1446 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1448 ++NumZeroStoresPromoted;
1450 // Keeping the iterator straight is a pain, so we let the merge routine tell
1451 // us what the next instruction is after it's done mucking about.
1452 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1458 // Find loads and stores that can be merged into a single load or store pair
1460 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1461 MachineInstr &MI = *MBBI;
1462 MachineBasicBlock::iterator E = MI.getParent()->end();
1464 if (!TII->isCandidateToMergeOrPair(MI))
1467 // Early exit if the offset is not possible to match. (6 bits of positive
1468 // range, plus allow an extra one in case we find a later insn that matches
1470 bool IsUnscaled = TII->isUnscaledLdSt(MI);
1471 int Offset = getLdStOffsetOp(MI).getImm();
1472 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1473 // Allow one more for offset.
1475 Offset -= OffsetStride;
1476 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1479 // Look ahead up to LdStLimit instructions for a pairable instruction.
1480 LdStPairFlags Flags;
1481 MachineBasicBlock::iterator Paired =
1482 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1485 if (TII->isUnscaledLdSt(MI))
1486 ++NumUnscaledPairCreated;
1487 // Keeping the iterator straight is a pain, so we let the merge routine tell
1488 // us what the next instruction is after it's done mucking about.
1489 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1495 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1496 bool EnableNarrowZeroStOpt) {
1497 bool Modified = false;
1498 // Four tranformations to do here:
1499 // 1) Find loads that directly read from stores and promote them by
1500 // replacing with mov instructions. If the store is wider than the load,
1501 // the load will be replaced with a bitfield extract.
1504 // ldrh w2, [x0, #6]
1508 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1510 MachineInstr &MI = *MBBI;
1511 switch (MI.getOpcode()) {
1513 // Just move on to the next instruction.
1516 // Scaled instructions.
1517 case AArch64::LDRBBui:
1518 case AArch64::LDRHHui:
1519 case AArch64::LDRWui:
1520 case AArch64::LDRXui:
1521 // Unscaled instructions.
1522 case AArch64::LDURBBi:
1523 case AArch64::LDURHHi:
1524 case AArch64::LDURWi:
1525 case AArch64::LDURXi: {
1526 if (tryToPromoteLoadFromStore(MBBI)) {
1535 // 2) Merge adjacent zero stores into a wider store.
1538 // strh wzr, [x0, #2]
1543 // str wzr, [x0, #4]
1546 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1547 EnableNarrowZeroStOpt && MBBI != E;) {
1548 if (isPromotableZeroStoreInst(*MBBI)) {
1549 if (tryToMergeZeroStInst(MBBI)) {
1557 // 3) Find loads and stores that can be merged into a single load or store
1558 // pair instruction.
1564 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1566 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
1571 // 4) Find base register updates that can be merged into the load or store
1572 // as a base-reg writeback.
1578 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1580 MachineInstr &MI = *MBBI;
1581 // Do update merging. It's simpler to keep this separate from the above
1582 // switchs, though not strictly necessary.
1583 unsigned Opc = MI.getOpcode();
1586 // Just move on to the next instruction.
1589 // Scaled instructions.
1590 case AArch64::STRSui:
1591 case AArch64::STRDui:
1592 case AArch64::STRQui:
1593 case AArch64::STRXui:
1594 case AArch64::STRWui:
1595 case AArch64::STRHHui:
1596 case AArch64::STRBBui:
1597 case AArch64::LDRSui:
1598 case AArch64::LDRDui:
1599 case AArch64::LDRQui:
1600 case AArch64::LDRXui:
1601 case AArch64::LDRWui:
1602 case AArch64::LDRHHui:
1603 case AArch64::LDRBBui:
1604 // Unscaled instructions.
1605 case AArch64::STURSi:
1606 case AArch64::STURDi:
1607 case AArch64::STURQi:
1608 case AArch64::STURWi:
1609 case AArch64::STURXi:
1610 case AArch64::LDURSi:
1611 case AArch64::LDURDi:
1612 case AArch64::LDURQi:
1613 case AArch64::LDURWi:
1614 case AArch64::LDURXi:
1615 // Paired instructions.
1616 case AArch64::LDPSi:
1617 case AArch64::LDPSWi:
1618 case AArch64::LDPDi:
1619 case AArch64::LDPQi:
1620 case AArch64::LDPWi:
1621 case AArch64::LDPXi:
1622 case AArch64::STPSi:
1623 case AArch64::STPDi:
1624 case AArch64::STPQi:
1625 case AArch64::STPWi:
1626 case AArch64::STPXi: {
1627 // Make sure this is a reg+imm (as opposed to an address reloc).
1628 if (!getLdStOffsetOp(MI).isImm()) {
1632 // Look forward to try to form a post-index instruction. For example,
1634 // add x20, x20, #32
1636 // ldr x0, [x20], #32
1637 MachineBasicBlock::iterator Update =
1638 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1640 // Merge the update into the ld/st.
1641 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1646 // Don't know how to handle pre/post-index versions, so move to the next
1648 if (TII->isUnscaledLdSt(Opc)) {
1653 // Look back to try to find a pre-index instruction. For example,
1657 // ldr x1, [x0, #8]!
1658 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1660 // Merge the update into the ld/st.
1661 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1666 // The immediate in the load/store is scaled by the size of the memory
1667 // operation. The immediate in the add we're looking for,
1668 // however, is not, so adjust here.
1669 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
1671 // Look forward to try to find a post-index instruction. For example,
1672 // ldr x1, [x0, #64]
1675 // ldr x1, [x0, #64]!
1676 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1678 // Merge the update into the ld/st.
1679 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1685 // Nothing found. Just move to the next instruction.
1695 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1696 if (skipFunction(*Fn.getFunction()))
1699 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1700 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1701 TRI = Subtarget->getRegisterInfo();
1703 // Resize the modified and used register bitfield trackers. We do this once
1704 // per function and then clear the bitfield each time we optimize a load or
1706 ModifiedRegs.resize(TRI->getNumRegs());
1707 UsedRegs.resize(TRI->getNumRegs());
1709 bool Modified = false;
1710 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
1711 for (auto &MBB : Fn)
1712 Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt);
1717 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
1718 // stores near one another? Note: The pre-RA instruction scheduler already has
1719 // hooks to try and schedule pairable loads/stores together to improve pairing
1720 // opportunities. Thus, pre-RA pairing pass may not be worth the effort.
1722 // FIXME: When pairing store instructions it's very possible for this pass to
1723 // hoist a store with a KILL marker above another use (without a KILL marker).
1724 // The resulting IR is invalid, but nothing uses the KILL markers after this
1725 // pass, so it's never caused a problem in practice.
1727 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1728 /// load / store optimization pass.
1729 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1730 return new AArch64LoadStoreOpt();