Simplify switch as all cases other than default return true. NFC.
[oota-llvm.git] / lib / Target / AArch64 / AArch64LoadStoreOptimizer.cpp
1 //=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that performs load / store related peephole
11 // optimizations. This pass should be run after register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
32 using namespace llvm;
33
34 #define DEBUG_TYPE "aarch64-ldst-opt"
35
36 /// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37 /// load / store instructions to form ldp / stp instructions.
38
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");
44
45 static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46                                    cl::init(20), cl::Hidden);
47
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));
52
53 namespace {
54
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.
59   bool MergeForward;
60
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.
65   int SExtIdx;
66
67   LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
68
69   void setMergeForward(bool V = true) { MergeForward = V; }
70   bool getMergeForward() const { return MergeForward; }
71
72   void setSExtIdx(int V) { SExtIdx = V; }
73   int getSExtIdx() const { return SExtIdx; }
74
75 } LdStPairFlags;
76
77 struct AArch64LoadStoreOpt : public MachineFunctionPass {
78   static char ID;
79   AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
80
81   const AArch64InstrInfo *TII;
82   const TargetRegisterInfo *TRI;
83
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,
88                                                LdStPairFlags &Flags,
89                                                unsigned Limit);
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);
98
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,
104                                 int Value);
105
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);
111
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);
116
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);
121
122   bool optimizeBlock(MachineBasicBlock &MBB);
123
124   bool runOnMachineFunction(MachineFunction &Fn) override;
125
126   const char *getPassName() const override {
127     return "AArch64 load / store optimization pass";
128   }
129
130 private:
131   int getMemSize(MachineInstr *MemMI);
132 };
133 char AArch64LoadStoreOpt::ID = 0;
134 } // namespace
135
136 static bool isUnscaledLdst(unsigned Opc) {
137   switch (Opc) {
138   default:
139     return false;
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:
151     return true;
152   }
153 }
154
155 // Size in bytes of the data moved by an unscaled load or store
156 int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
157   switch (MemMI->getOpcode()) {
158   default:
159     llvm_unreachable("Opcode has unknown size!");
160   case AArch64::STRSui:
161   case AArch64::STURSi:
162     return 4;
163   case AArch64::STRDui:
164   case AArch64::STURDi:
165     return 8;
166   case AArch64::STRQui:
167   case AArch64::STURQi:
168     return 16;
169   case AArch64::STRWui:
170   case AArch64::STURWi:
171     return 4;
172   case AArch64::STRXui:
173   case AArch64::STURXi:
174     return 8;
175   case AArch64::LDRSui:
176   case AArch64::LDURSi:
177     return 4;
178   case AArch64::LDRDui:
179   case AArch64::LDURDi:
180     return 8;
181   case AArch64::LDRQui:
182   case AArch64::LDURQi:
183     return 16;
184   case AArch64::LDRWui:
185   case AArch64::LDURWi:
186     return 4;
187   case AArch64::LDRXui:
188   case AArch64::LDURXi:
189     return 8;
190   case AArch64::LDRSWui:
191   case AArch64::LDURSWi:
192     return 4;
193   }
194 }
195
196 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
197                                          bool *IsValidLdStrOpc = nullptr) {
198   if (IsValidLdStrOpc)
199     *IsValidLdStrOpc = true;
200   switch (Opc) {
201   default:
202     if (IsValidLdStrOpc)
203       *IsValidLdStrOpc = false;
204     return UINT_MAX;
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:
225     return Opc;
226   case AArch64::LDRSWui:
227     return AArch64::LDRWui;
228   case AArch64::LDURSWi:
229     return AArch64::LDURWi;
230   }
231 }
232
233 static unsigned getMatchingPairOpcode(unsigned Opc) {
234   switch (Opc) {
235   default:
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;
270   }
271 }
272
273 static unsigned getPreIndexedOpcode(unsigned Opc) {
274   switch (Opc) {
275   default:
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;
299   }
300 }
301
302 static unsigned getPostIndexedOpcode(unsigned Opc) {
303   switch (Opc) {
304   default:
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;
328   }
329 }
330
331 MachineBasicBlock::iterator
332 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
333                                       MachineBasicBlock::iterator Paired,
334                                       const LdStPairFlags &Flags) {
335   MachineBasicBlock::iterator NextI = I;
336   ++NextI;
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.
341   if (NextI == Paired)
342     ++NextI;
343
344   int SExtIdx = Flags.getSExtIdx();
345   unsigned Opc =
346       SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
347   bool IsUnscaled = isUnscaledLdst(Opc);
348   int OffsetStride =
349       IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
350
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);
360
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) {
365     RtMI = Paired;
366     Rt2MI = I;
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.
370     if (SExtIdx != -1)
371       SExtIdx = (SExtIdx + 1) % 2;
372   } else {
373     RtMI = I;
374     Rt2MI = Paired;
375   }
376   // Handle Unscaled
377   int OffsetImm = RtMI->getOperand(2).getImm();
378   if (IsUnscaled && EnableAArch64UnscaledMemOp)
379     OffsetImm /= OffsetStride;
380
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)
387                                 .addImm(OffsetImm);
388   (void)MIB;
389
390   // FIXME: Do we need/want to copy the mem operands from the source
391   //        instructions? Probably. What uses them after this?
392
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    ");
398
399   if (SExtIdx != -1) {
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
406     // extended opcode.
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
415     // the X register.
416     // Insert this definition right after the generated LDP, i.e., before
417     // InsertionPoint.
418     MachineInstrBuilder MIBKill =
419         BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
420                 TII->get(TargetOpcode::KILL), DstRegW)
421             .addReg(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)
428             .addReg(DstRegX)
429             .addImm(0)
430             .addImm(31);
431     (void)MIBSXTW;
432     DEBUG(dbgs() << "  Extend operand:\n    ");
433     DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
434     DEBUG(dbgs() << "\n");
435   } else {
436     DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437     DEBUG(dbgs() << "\n");
438   }
439
440   // Erase the old instructions.
441   I->eraseFromParent();
442   Paired->eraseFromParent();
443
444   return NextI;
445 }
446
447 /// trackRegDefsUses - Remember what registers the specified instruction uses
448 /// and modifies.
449 static void trackRegDefsUses(MachineInstr *MI, BitVector &ModifiedRegs,
450                              BitVector &UsedRegs,
451                              const TargetRegisterInfo *TRI) {
452   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
453     MachineOperand &MO = MI->getOperand(i);
454     if (MO.isRegMask())
455       ModifiedRegs.setBitsNotInMask(MO.getRegMask());
456
457     if (!MO.isReg())
458       continue;
459     unsigned Reg = MO.getReg();
460     if (MO.isDef()) {
461       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
462         ModifiedRegs.set(*AI);
463     } else {
464       assert(MO.isUse() && "Reg operand not a def and not a use?!?");
465       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
466         UsedRegs.set(*AI);
467     }
468   }
469 }
470
471 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
472   if (!IsUnscaled && (Offset > 63 || Offset < -64))
473     return false;
474   if (IsUnscaled) {
475     // Convert the byte-offset used by unscaled into an "element" offset used
476     // by the scaled pair load/store instructions.
477     int ElemOffset = Offset / OffsetStride;
478     if (ElemOffset > 63 || ElemOffset < -64)
479       return false;
480   }
481   return true;
482 }
483
484 // Do alignment, specialized to power of 2 and for signed ints,
485 // avoiding having to do a C-style cast from uint_64t to int when
486 // using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
487 // FIXME: Move this function to include/MathExtras.h?
488 static int alignTo(int Num, int PowOf2) {
489   return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
490 }
491
492 static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
493                      const AArch64InstrInfo *TII) {
494   // One of the instructions must modify memory.
495   if (!MIa->mayStore() && !MIb->mayStore())
496     return false;
497
498   // Both instructions must be memory operations.
499   if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
500     return false;
501
502   return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
503 }
504
505 static bool mayAlias(MachineInstr *MIa,
506                      SmallVectorImpl<MachineInstr *> &MemInsns,
507                      const AArch64InstrInfo *TII) {
508   for (auto &MIb : MemInsns)
509     if (mayAlias(MIa, MIb, TII))
510       return true;
511
512   return false;
513 }
514
515 /// findMatchingInsn - Scan the instructions looking for a load/store that can
516 /// be combined with the current instruction into a load/store pair.
517 MachineBasicBlock::iterator
518 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
519                                       LdStPairFlags &Flags,
520                                       unsigned Limit) {
521   MachineBasicBlock::iterator E = I->getParent()->end();
522   MachineBasicBlock::iterator MBBI = I;
523   MachineInstr *FirstMI = I;
524   ++MBBI;
525
526   unsigned Opc = FirstMI->getOpcode();
527   bool MayLoad = FirstMI->mayLoad();
528   bool IsUnscaled = isUnscaledLdst(Opc);
529   unsigned Reg = FirstMI->getOperand(0).getReg();
530   unsigned BaseReg = FirstMI->getOperand(1).getReg();
531   int Offset = FirstMI->getOperand(2).getImm();
532
533   // Early exit if the first instruction modifies the base register.
534   // e.g., ldr x0, [x0]
535   // Early exit if the offset if not possible to match. (6 bits of positive
536   // range, plus allow an extra one in case we find a later insn that matches
537   // with Offset-1
538   if (FirstMI->modifiesRegister(BaseReg, TRI))
539     return E;
540   int OffsetStride =
541       IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
542   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
543     return E;
544
545   // Track which registers have been modified and used between the first insn
546   // (inclusive) and the second insn.
547   BitVector ModifiedRegs, UsedRegs;
548   ModifiedRegs.resize(TRI->getNumRegs());
549   UsedRegs.resize(TRI->getNumRegs());
550
551   // Remember any instructions that read/write memory between FirstMI and MI.
552   SmallVector<MachineInstr *, 4> MemInsns;
553
554   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
555     MachineInstr *MI = MBBI;
556     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
557     // optimization by changing how far we scan.
558     if (MI->isDebugValue())
559       continue;
560
561     // Now that we know this is a real instruction, count it.
562     ++Count;
563
564     bool CanMergeOpc = Opc == MI->getOpcode();
565     Flags.setSExtIdx(-1);
566     if (!CanMergeOpc) {
567       bool IsValidLdStrOpc;
568       unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
569       if (!IsValidLdStrOpc)
570         continue;
571       // Opc will be the first instruction in the pair.
572       Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
573       CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
574     }
575
576     if (CanMergeOpc && MI->getOperand(2).isImm()) {
577       // If we've found another instruction with the same opcode, check to see
578       // if the base and offset are compatible with our starting instruction.
579       // These instructions all have scaled immediate operands, so we just
580       // check for +1/-1. Make sure to check the new instruction offset is
581       // actually an immediate and not a symbolic reference destined for
582       // a relocation.
583       //
584       // Pairwise instructions have a 7-bit signed offset field. Single insns
585       // have a 12-bit unsigned offset field. To be a valid combine, the
586       // final offset must be in range.
587       unsigned MIBaseReg = MI->getOperand(1).getReg();
588       int MIOffset = MI->getOperand(2).getImm();
589       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
590                                    (Offset + OffsetStride == MIOffset))) {
591         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
592         // If this is a volatile load/store that otherwise matched, stop looking
593         // as something is going on that we don't have enough information to
594         // safely transform. Similarly, stop if we see a hint to avoid pairs.
595         if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
596           return E;
597         // If the resultant immediate offset of merging these instructions
598         // is out of range for a pairwise instruction, bail and keep looking.
599         bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
600         if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
601           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
602           if (MI->mayLoadOrStore())
603             MemInsns.push_back(MI);
604           continue;
605         }
606         // If the alignment requirements of the paired (scaled) instruction
607         // can't express the offset of the unscaled input, bail and keep
608         // looking.
609         if (IsUnscaled && EnableAArch64UnscaledMemOp &&
610             (alignTo(MinOffset, OffsetStride) != MinOffset)) {
611           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
612           if (MI->mayLoadOrStore())
613             MemInsns.push_back(MI);
614           continue;
615         }
616         // If the destination register of the loads is the same register, bail
617         // and keep looking. A load-pair instruction with both destination
618         // registers the same is UNPREDICTABLE and will result in an exception.
619         if (MayLoad && Reg == MI->getOperand(0).getReg()) {
620           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
621           if (MI->mayLoadOrStore())
622             MemInsns.push_back(MI);
623           continue;
624         }
625
626         // If the Rt of the second instruction was not modified or used between
627         // the two instructions and none of the instructions between the second
628         // and first alias with the second, we can combine the second into the
629         // first.
630         if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
631             !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
632             !mayAlias(MI, MemInsns, TII)) {
633           Flags.setMergeForward(false);
634           return MBBI;
635         }
636
637         // Likewise, if the Rt of the first instruction is not modified or used
638         // between the two instructions and none of the instructions between the
639         // first and the second alias with the first, we can combine the first
640         // into the second.
641         if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
642             !(FirstMI->mayLoad() &&
643               UsedRegs[FirstMI->getOperand(0).getReg()]) &&
644             !mayAlias(FirstMI, MemInsns, TII)) {
645           Flags.setMergeForward(true);
646           return MBBI;
647         }
648         // Unable to combine these instructions due to interference in between.
649         // Keep looking.
650       }
651     }
652
653     // If the instruction wasn't a matching load or store.  Stop searching if we
654     // encounter a call instruction that might modify memory.
655     if (MI->isCall())
656       return E;
657
658     // Update modified / uses register lists.
659     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
660
661     // Otherwise, if the base register is modified, we have no match, so
662     // return early.
663     if (ModifiedRegs[BaseReg])
664       return E;
665
666     // Update list of instructions that read/write memory.
667     if (MI->mayLoadOrStore())
668       MemInsns.push_back(MI);
669   }
670   return E;
671 }
672
673 MachineBasicBlock::iterator
674 AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
675                                            MachineBasicBlock::iterator Update) {
676   assert((Update->getOpcode() == AArch64::ADDXri ||
677           Update->getOpcode() == AArch64::SUBXri) &&
678          "Unexpected base register update instruction to merge!");
679   MachineBasicBlock::iterator NextI = I;
680   // Return the instruction following the merged instruction, which is
681   // the instruction following our unmerged load. Unless that's the add/sub
682   // instruction we're merging, in which case it's the one after that.
683   if (++NextI == Update)
684     ++NextI;
685
686   int Value = Update->getOperand(2).getImm();
687   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
688          "Can't merge 1 << 12 offset into pre-indexed load / store");
689   if (Update->getOpcode() == AArch64::SUBXri)
690     Value = -Value;
691
692   unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
693   MachineInstrBuilder MIB =
694       BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
695           .addOperand(Update->getOperand(0))
696           .addOperand(I->getOperand(0))
697           .addOperand(I->getOperand(1))
698           .addImm(Value);
699   (void)MIB;
700
701   DEBUG(dbgs() << "Creating pre-indexed load/store.");
702   DEBUG(dbgs() << "    Replacing instructions:\n    ");
703   DEBUG(I->print(dbgs()));
704   DEBUG(dbgs() << "    ");
705   DEBUG(Update->print(dbgs()));
706   DEBUG(dbgs() << "  with instruction:\n    ");
707   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
708   DEBUG(dbgs() << "\n");
709
710   // Erase the old instructions for the block.
711   I->eraseFromParent();
712   Update->eraseFromParent();
713
714   return NextI;
715 }
716
717 MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
718     MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
719   assert((Update->getOpcode() == AArch64::ADDXri ||
720           Update->getOpcode() == AArch64::SUBXri) &&
721          "Unexpected base register update instruction to merge!");
722   MachineBasicBlock::iterator NextI = I;
723   // Return the instruction following the merged instruction, which is
724   // the instruction following our unmerged load. Unless that's the add/sub
725   // instruction we're merging, in which case it's the one after that.
726   if (++NextI == Update)
727     ++NextI;
728
729   int Value = Update->getOperand(2).getImm();
730   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
731          "Can't merge 1 << 12 offset into post-indexed load / store");
732   if (Update->getOpcode() == AArch64::SUBXri)
733     Value = -Value;
734
735   unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
736   MachineInstrBuilder MIB =
737       BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
738           .addOperand(Update->getOperand(0))
739           .addOperand(I->getOperand(0))
740           .addOperand(I->getOperand(1))
741           .addImm(Value);
742   (void)MIB;
743
744   DEBUG(dbgs() << "Creating post-indexed load/store.");
745   DEBUG(dbgs() << "    Replacing instructions:\n    ");
746   DEBUG(I->print(dbgs()));
747   DEBUG(dbgs() << "    ");
748   DEBUG(Update->print(dbgs()));
749   DEBUG(dbgs() << "  with instruction:\n    ");
750   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
751   DEBUG(dbgs() << "\n");
752
753   // Erase the old instructions for the block.
754   I->eraseFromParent();
755   Update->eraseFromParent();
756
757   return NextI;
758 }
759
760 static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
761                                  int Offset) {
762   switch (MI->getOpcode()) {
763   default:
764     break;
765   case AArch64::SUBXri:
766     // Negate the offset for a SUB instruction.
767     Offset *= -1;
768   // FALLTHROUGH
769   case AArch64::ADDXri:
770     // Make sure it's a vanilla immediate operand, not a relocation or
771     // anything else we can't handle.
772     if (!MI->getOperand(2).isImm())
773       break;
774     // Watch out for 1 << 12 shifted value.
775     if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
776       break;
777     // If the instruction has the base register as source and dest and the
778     // immediate will fit in a signed 9-bit integer, then we have a match.
779     if (MI->getOperand(0).getReg() == BaseReg &&
780         MI->getOperand(1).getReg() == BaseReg &&
781         MI->getOperand(2).getImm() <= 255 &&
782         MI->getOperand(2).getImm() >= -256) {
783       // If we have a non-zero Offset, we check that it matches the amount
784       // we're adding to the register.
785       if (!Offset || Offset == MI->getOperand(2).getImm())
786         return true;
787     }
788     break;
789   }
790   return false;
791 }
792
793 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
794     MachineBasicBlock::iterator I, unsigned Limit, int Value) {
795   MachineBasicBlock::iterator E = I->getParent()->end();
796   MachineInstr *MemMI = I;
797   MachineBasicBlock::iterator MBBI = I;
798   const MachineFunction &MF = *MemMI->getParent()->getParent();
799
800   unsigned DestReg = MemMI->getOperand(0).getReg();
801   unsigned BaseReg = MemMI->getOperand(1).getReg();
802   int Offset = MemMI->getOperand(2).getImm() *
803                TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
804
805   // If the base register overlaps the destination register, we can't
806   // merge the update.
807   if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
808     return E;
809
810   // Scan forward looking for post-index opportunities.
811   // Updating instructions can't be formed if the memory insn already
812   // has an offset other than the value we're looking for.
813   if (Offset != Value)
814     return E;
815
816   // Track which registers have been modified and used between the first insn
817   // (inclusive) and the second insn.
818   BitVector ModifiedRegs, UsedRegs;
819   ModifiedRegs.resize(TRI->getNumRegs());
820   UsedRegs.resize(TRI->getNumRegs());
821   ++MBBI;
822   for (unsigned Count = 0; MBBI != E; ++MBBI) {
823     MachineInstr *MI = MBBI;
824     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
825     // optimization by changing how far we scan.
826     if (MI->isDebugValue())
827       continue;
828
829     // Now that we know this is a real instruction, count it.
830     ++Count;
831
832     // If we found a match, return it.
833     if (isMatchingUpdateInsn(MI, BaseReg, Value))
834       return MBBI;
835
836     // Update the status of what the instruction clobbered and used.
837     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
838
839     // Otherwise, if the base register is used or modified, we have no match, so
840     // return early.
841     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
842       return E;
843   }
844   return E;
845 }
846
847 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
848     MachineBasicBlock::iterator I, unsigned Limit) {
849   MachineBasicBlock::iterator B = I->getParent()->begin();
850   MachineBasicBlock::iterator E = I->getParent()->end();
851   MachineInstr *MemMI = I;
852   MachineBasicBlock::iterator MBBI = I;
853   const MachineFunction &MF = *MemMI->getParent()->getParent();
854
855   unsigned DestReg = MemMI->getOperand(0).getReg();
856   unsigned BaseReg = MemMI->getOperand(1).getReg();
857   int Offset = MemMI->getOperand(2).getImm();
858   unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
859
860   // If the load/store is the first instruction in the block, there's obviously
861   // not any matching update. Ditto if the memory offset isn't zero.
862   if (MBBI == B || Offset != 0)
863     return E;
864   // If the base register overlaps the destination register, we can't
865   // merge the update.
866   if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
867     return E;
868
869   // Track which registers have been modified and used between the first insn
870   // (inclusive) and the second insn.
871   BitVector ModifiedRegs, UsedRegs;
872   ModifiedRegs.resize(TRI->getNumRegs());
873   UsedRegs.resize(TRI->getNumRegs());
874   --MBBI;
875   for (unsigned Count = 0; MBBI != B; --MBBI) {
876     MachineInstr *MI = MBBI;
877     // Skip DBG_VALUE instructions. Otherwise debug info can affect the
878     // optimization by changing how far we scan.
879     if (MI->isDebugValue())
880       continue;
881
882     // Now that we know this is a real instruction, count it.
883     ++Count;
884
885     // If we found a match, return it.
886     if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
887       return MBBI;
888
889     // Update the status of what the instruction clobbered and used.
890     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
891
892     // Otherwise, if the base register is used or modified, we have no match, so
893     // return early.
894     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
895       return E;
896   }
897   return E;
898 }
899
900 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
901   bool Modified = false;
902   // Two tranformations to do here:
903   // 1) Find loads and stores that can be merged into a single load or store
904   //    pair instruction.
905   //      e.g.,
906   //        ldr x0, [x2]
907   //        ldr x1, [x2, #8]
908   //        ; becomes
909   //        ldp x0, x1, [x2]
910   // 2) Find base register updates that can be merged into the load or store
911   //    as a base-reg writeback.
912   //      e.g.,
913   //        ldr x0, [x2]
914   //        add x2, x2, #4
915   //        ; becomes
916   //        ldr x0, [x2], #4
917
918   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
919        MBBI != E;) {
920     MachineInstr *MI = MBBI;
921     switch (MI->getOpcode()) {
922     default:
923       // Just move on to the next instruction.
924       ++MBBI;
925       break;
926     case AArch64::STRSui:
927     case AArch64::STRDui:
928     case AArch64::STRQui:
929     case AArch64::STRXui:
930     case AArch64::STRWui:
931     case AArch64::LDRSui:
932     case AArch64::LDRDui:
933     case AArch64::LDRQui:
934     case AArch64::LDRXui:
935     case AArch64::LDRWui:
936     case AArch64::LDRSWui:
937     // do the unscaled versions as well
938     case AArch64::STURSi:
939     case AArch64::STURDi:
940     case AArch64::STURQi:
941     case AArch64::STURWi:
942     case AArch64::STURXi:
943     case AArch64::LDURSi:
944     case AArch64::LDURDi:
945     case AArch64::LDURQi:
946     case AArch64::LDURWi:
947     case AArch64::LDURXi:
948     case AArch64::LDURSWi: {
949       // If this is a volatile load/store, don't mess with it.
950       if (MI->hasOrderedMemoryRef()) {
951         ++MBBI;
952         break;
953       }
954       // Make sure this is a reg+imm (as opposed to an address reloc).
955       if (!MI->getOperand(2).isImm()) {
956         ++MBBI;
957         break;
958       }
959       // Check if this load/store has a hint to avoid pair formation.
960       // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
961       if (TII->isLdStPairSuppressed(MI)) {
962         ++MBBI;
963         break;
964       }
965       // Look ahead up to ScanLimit instructions for a pairable instruction.
966       LdStPairFlags Flags;
967       MachineBasicBlock::iterator Paired =
968           findMatchingInsn(MBBI, Flags, ScanLimit);
969       if (Paired != E) {
970         // Merge the loads into a pair. Keeping the iterator straight is a
971         // pain, so we let the merge routine tell us what the next instruction
972         // is after it's done mucking about.
973         MBBI = mergePairedInsns(MBBI, Paired, Flags);
974
975         Modified = true;
976         ++NumPairCreated;
977         if (isUnscaledLdst(MI->getOpcode()))
978           ++NumUnscaledPairCreated;
979         break;
980       }
981       ++MBBI;
982       break;
983     }
984       // FIXME: Do the other instructions.
985     }
986   }
987
988   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
989        MBBI != E;) {
990     MachineInstr *MI = MBBI;
991     // Do update merging. It's simpler to keep this separate from the above
992     // switch, though not strictly necessary.
993     unsigned Opc = MI->getOpcode();
994     switch (Opc) {
995     default:
996       // Just move on to the next instruction.
997       ++MBBI;
998       break;
999     case AArch64::STRSui:
1000     case AArch64::STRDui:
1001     case AArch64::STRQui:
1002     case AArch64::STRXui:
1003     case AArch64::STRWui:
1004     case AArch64::LDRSui:
1005     case AArch64::LDRDui:
1006     case AArch64::LDRQui:
1007     case AArch64::LDRXui:
1008     case AArch64::LDRWui:
1009     // do the unscaled versions as well
1010     case AArch64::STURSi:
1011     case AArch64::STURDi:
1012     case AArch64::STURQi:
1013     case AArch64::STURWi:
1014     case AArch64::STURXi:
1015     case AArch64::LDURSi:
1016     case AArch64::LDURDi:
1017     case AArch64::LDURQi:
1018     case AArch64::LDURWi:
1019     case AArch64::LDURXi: {
1020       // Make sure this is a reg+imm (as opposed to an address reloc).
1021       if (!MI->getOperand(2).isImm()) {
1022         ++MBBI;
1023         break;
1024       }
1025       // Look ahead up to ScanLimit instructions for a mergable instruction.
1026       MachineBasicBlock::iterator Update =
1027           findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1028       if (Update != E) {
1029         // Merge the update into the ld/st.
1030         MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1031         Modified = true;
1032         ++NumPostFolded;
1033         break;
1034       }
1035       // Don't know how to handle pre/post-index versions, so move to the next
1036       // instruction.
1037       if (isUnscaledLdst(Opc)) {
1038         ++MBBI;
1039         break;
1040       }
1041
1042       // Look back to try to find a pre-index instruction. For example,
1043       // add x0, x0, #8
1044       // ldr x1, [x0]
1045       //   merged into:
1046       // ldr x1, [x0, #8]!
1047       Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1048       if (Update != E) {
1049         // Merge the update into the ld/st.
1050         MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1051         Modified = true;
1052         ++NumPreFolded;
1053         break;
1054       }
1055
1056       // Look forward to try to find a post-index instruction. For example,
1057       // ldr x1, [x0, #64]
1058       // add x0, x0, #64
1059       //   merged into:
1060       // ldr x1, [x0, #64]!
1061
1062       // The immediate in the load/store is scaled by the size of the register
1063       // being loaded. The immediate in the add we're looking for,
1064       // however, is not, so adjust here.
1065       int Value = MI->getOperand(2).getImm() *
1066                   TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1067                       ->getSize();
1068       Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1069       if (Update != E) {
1070         // Merge the update into the ld/st.
1071         MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1072         Modified = true;
1073         ++NumPreFolded;
1074         break;
1075       }
1076
1077       // Nothing found. Just move to the next instruction.
1078       ++MBBI;
1079       break;
1080     }
1081       // FIXME: Do the other instructions.
1082     }
1083   }
1084
1085   return Modified;
1086 }
1087
1088 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1089   TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1090   TRI = Fn.getSubtarget().getRegisterInfo();
1091
1092   bool Modified = false;
1093   for (auto &MBB : Fn)
1094     Modified |= optimizeBlock(MBB);
1095
1096   return Modified;
1097 }
1098
1099 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1100 // loads and stores near one another?
1101
1102 /// createARMLoadStoreOptimizationPass - returns an instance of the load / store
1103 /// optimization pass.
1104 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1105   return new AArch64LoadStoreOpt();
1106 }