1 //===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
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/ADT/StringRef.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/IR/DebugLoc.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <iterator>
41 #include <limits>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "aarch64-ldst-opt"
46 
47 STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
48 STATISTIC(NumPostFolded, "Number of post-index updates folded");
49 STATISTIC(NumPreFolded, "Number of pre-index updates folded");
50 STATISTIC(NumUnscaledPairCreated,
51           "Number of load/store from unscaled generated");
52 STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
53 STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
54 
55 // The LdStLimit limits how far we search for load/store pairs.
56 static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
57                                    cl::init(20), cl::Hidden);
58 
59 // The UpdateLimit limits how far we search for update instructions when we form
60 // pre-/post-index instructions.
61 static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
62                                      cl::Hidden);
63 
64 #define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
65 
66 namespace {
67 
68 using LdStPairFlags = struct LdStPairFlags {
69   // If a matching instruction is found, MergeForward is set to true if the
70   // merge is to remove the first instruction and replace the second with
71   // a pair-wise insn, and false if the reverse is true.
72   bool MergeForward = false;
73 
74   // SExtIdx gives the index of the result of the load pair that must be
75   // extended. The value of SExtIdx assumes that the paired load produces the
76   // value in this order: (I, returned iterator), i.e., -1 means no value has
77   // to be extended, 0 means I, and 1 means the returned iterator.
78   int SExtIdx = -1;
79 
80   LdStPairFlags() = default;
81 
82   void setMergeForward(bool V = true) { MergeForward = V; }
83   bool getMergeForward() const { return MergeForward; }
84 
85   void setSExtIdx(int V) { SExtIdx = V; }
86   int getSExtIdx() const { return SExtIdx; }
87 };
88 
89 struct AArch64LoadStoreOpt : public MachineFunctionPass {
90   static char ID;
91 
92   AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
93     initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
94   }
95 
96   AliasAnalysis *AA;
97   const AArch64InstrInfo *TII;
98   const TargetRegisterInfo *TRI;
99   const AArch64Subtarget *Subtarget;
100 
101   // Track which registers have been modified and used.
102   BitVector ModifiedRegs, UsedRegs;
103 
104   void getAnalysisUsage(AnalysisUsage &AU) const override {
105     AU.addRequired<AAResultsWrapperPass>();
106     MachineFunctionPass::getAnalysisUsage(AU);
107   }
108 
109   // Scan the instructions looking for a load/store that can be combined
110   // with the current instruction into a load/store pair.
111   // Return the matching instruction if one is found, else MBB->end().
112   MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
113                                                LdStPairFlags &Flags,
114                                                unsigned Limit,
115                                                bool FindNarrowMerge);
116 
117   // Scan the instructions looking for a store that writes to the address from
118   // which the current load instruction reads. Return true if one is found.
119   bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
120                          MachineBasicBlock::iterator &StoreI);
121 
122   // Merge the two instructions indicated into a wider narrow store instruction.
123   MachineBasicBlock::iterator
124   mergeNarrowZeroStores(MachineBasicBlock::iterator I,
125                         MachineBasicBlock::iterator MergeMI,
126                         const LdStPairFlags &Flags);
127 
128   // Merge the two instructions indicated into a single pair-wise instruction.
129   MachineBasicBlock::iterator
130   mergePairedInsns(MachineBasicBlock::iterator I,
131                    MachineBasicBlock::iterator Paired,
132                    const LdStPairFlags &Flags);
133 
134   // Promote the load that reads directly from the address stored to.
135   MachineBasicBlock::iterator
136   promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
137                        MachineBasicBlock::iterator StoreI);
138 
139   // Scan the instruction list to find a base register update that can
140   // be combined with the current instruction (a load or store) using
141   // pre or post indexed addressing with writeback. Scan forwards.
142   MachineBasicBlock::iterator
143   findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
144                                 int UnscaledOffset, unsigned Limit);
145 
146   // Scan the instruction list to find a base register update that can
147   // be combined with the current instruction (a load or store) using
148   // pre or post indexed addressing with writeback. Scan backwards.
149   MachineBasicBlock::iterator
150   findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
151 
152   // Find an instruction that updates the base register of the ld/st
153   // instruction.
154   bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
155                             unsigned BaseReg, int Offset);
156 
157   // Merge a pre- or post-index base register update into a ld/st instruction.
158   MachineBasicBlock::iterator
159   mergeUpdateInsn(MachineBasicBlock::iterator I,
160                   MachineBasicBlock::iterator Update, bool IsPreIdx);
161 
162   // Find and merge zero store instructions.
163   bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
164 
165   // Find and pair ldr/str instructions.
166   bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
167 
168   // Find and promote load instructions which read directly from store.
169   bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
170 
171   // Find and merge a base register updates before or after a ld/st instruction.
172   bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
173 
174   bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
175 
176   bool runOnMachineFunction(MachineFunction &Fn) override;
177 
178   MachineFunctionProperties getRequiredProperties() const override {
179     return MachineFunctionProperties().set(
180         MachineFunctionProperties::Property::NoVRegs);
181   }
182 
183   StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
184 };
185 
186 char AArch64LoadStoreOpt::ID = 0;
187 
188 } // end anonymous namespace
189 
190 INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
191                 AARCH64_LOAD_STORE_OPT_NAME, false, false)
192 
193 static bool isNarrowStore(unsigned Opc) {
194   switch (Opc) {
195   default:
196     return false;
197   case AArch64::STRBBui:
198   case AArch64::STURBBi:
199   case AArch64::STRHHui:
200   case AArch64::STURHHi:
201     return true;
202   }
203 }
204 
205 // Scaling factor for unscaled load or store.
206 static int getMemScale(MachineInstr &MI) {
207   switch (MI.getOpcode()) {
208   default:
209     llvm_unreachable("Opcode has unknown scale!");
210   case AArch64::LDRBBui:
211   case AArch64::LDURBBi:
212   case AArch64::LDRSBWui:
213   case AArch64::LDURSBWi:
214   case AArch64::STRBBui:
215   case AArch64::STURBBi:
216     return 1;
217   case AArch64::LDRHHui:
218   case AArch64::LDURHHi:
219   case AArch64::LDRSHWui:
220   case AArch64::LDURSHWi:
221   case AArch64::STRHHui:
222   case AArch64::STURHHi:
223     return 2;
224   case AArch64::LDRSui:
225   case AArch64::LDURSi:
226   case AArch64::LDRSWui:
227   case AArch64::LDURSWi:
228   case AArch64::LDRWui:
229   case AArch64::LDURWi:
230   case AArch64::STRSui:
231   case AArch64::STURSi:
232   case AArch64::STRWui:
233   case AArch64::STURWi:
234   case AArch64::LDPSi:
235   case AArch64::LDPSWi:
236   case AArch64::LDPWi:
237   case AArch64::STPSi:
238   case AArch64::STPWi:
239     return 4;
240   case AArch64::LDRDui:
241   case AArch64::LDURDi:
242   case AArch64::LDRXui:
243   case AArch64::LDURXi:
244   case AArch64::STRDui:
245   case AArch64::STURDi:
246   case AArch64::STRXui:
247   case AArch64::STURXi:
248   case AArch64::LDPDi:
249   case AArch64::LDPXi:
250   case AArch64::STPDi:
251   case AArch64::STPXi:
252     return 8;
253   case AArch64::LDRQui:
254   case AArch64::LDURQi:
255   case AArch64::STRQui:
256   case AArch64::STURQi:
257   case AArch64::LDPQi:
258   case AArch64::STPQi:
259     return 16;
260   }
261 }
262 
263 static unsigned getMatchingNonSExtOpcode(unsigned Opc,
264                                          bool *IsValidLdStrOpc = nullptr) {
265   if (IsValidLdStrOpc)
266     *IsValidLdStrOpc = true;
267   switch (Opc) {
268   default:
269     if (IsValidLdStrOpc)
270       *IsValidLdStrOpc = false;
271     return std::numeric_limits<unsigned>::max();
272   case AArch64::STRDui:
273   case AArch64::STURDi:
274   case AArch64::STRQui:
275   case AArch64::STURQi:
276   case AArch64::STRBBui:
277   case AArch64::STURBBi:
278   case AArch64::STRHHui:
279   case AArch64::STURHHi:
280   case AArch64::STRWui:
281   case AArch64::STURWi:
282   case AArch64::STRXui:
283   case AArch64::STURXi:
284   case AArch64::LDRDui:
285   case AArch64::LDURDi:
286   case AArch64::LDRQui:
287   case AArch64::LDURQi:
288   case AArch64::LDRWui:
289   case AArch64::LDURWi:
290   case AArch64::LDRXui:
291   case AArch64::LDURXi:
292   case AArch64::STRSui:
293   case AArch64::STURSi:
294   case AArch64::LDRSui:
295   case AArch64::LDURSi:
296     return Opc;
297   case AArch64::LDRSWui:
298     return AArch64::LDRWui;
299   case AArch64::LDURSWi:
300     return AArch64::LDURWi;
301   }
302 }
303 
304 static unsigned getMatchingWideOpcode(unsigned Opc) {
305   switch (Opc) {
306   default:
307     llvm_unreachable("Opcode has no wide equivalent!");
308   case AArch64::STRBBui:
309     return AArch64::STRHHui;
310   case AArch64::STRHHui:
311     return AArch64::STRWui;
312   case AArch64::STURBBi:
313     return AArch64::STURHHi;
314   case AArch64::STURHHi:
315     return AArch64::STURWi;
316   case AArch64::STURWi:
317     return AArch64::STURXi;
318   case AArch64::STRWui:
319     return AArch64::STRXui;
320   }
321 }
322 
323 static unsigned getMatchingPairOpcode(unsigned Opc) {
324   switch (Opc) {
325   default:
326     llvm_unreachable("Opcode has no pairwise equivalent!");
327   case AArch64::STRSui:
328   case AArch64::STURSi:
329     return AArch64::STPSi;
330   case AArch64::STRDui:
331   case AArch64::STURDi:
332     return AArch64::STPDi;
333   case AArch64::STRQui:
334   case AArch64::STURQi:
335     return AArch64::STPQi;
336   case AArch64::STRWui:
337   case AArch64::STURWi:
338     return AArch64::STPWi;
339   case AArch64::STRXui:
340   case AArch64::STURXi:
341     return AArch64::STPXi;
342   case AArch64::LDRSui:
343   case AArch64::LDURSi:
344     return AArch64::LDPSi;
345   case AArch64::LDRDui:
346   case AArch64::LDURDi:
347     return AArch64::LDPDi;
348   case AArch64::LDRQui:
349   case AArch64::LDURQi:
350     return AArch64::LDPQi;
351   case AArch64::LDRWui:
352   case AArch64::LDURWi:
353     return AArch64::LDPWi;
354   case AArch64::LDRXui:
355   case AArch64::LDURXi:
356     return AArch64::LDPXi;
357   case AArch64::LDRSWui:
358   case AArch64::LDURSWi:
359     return AArch64::LDPSWi;
360   }
361 }
362 
363 static unsigned isMatchingStore(MachineInstr &LoadInst,
364                                 MachineInstr &StoreInst) {
365   unsigned LdOpc = LoadInst.getOpcode();
366   unsigned StOpc = StoreInst.getOpcode();
367   switch (LdOpc) {
368   default:
369     llvm_unreachable("Unsupported load instruction!");
370   case AArch64::LDRBBui:
371     return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
372            StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
373   case AArch64::LDURBBi:
374     return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
375            StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
376   case AArch64::LDRHHui:
377     return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
378            StOpc == AArch64::STRXui;
379   case AArch64::LDURHHi:
380     return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
381            StOpc == AArch64::STURXi;
382   case AArch64::LDRWui:
383     return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
384   case AArch64::LDURWi:
385     return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
386   case AArch64::LDRXui:
387     return StOpc == AArch64::STRXui;
388   case AArch64::LDURXi:
389     return StOpc == AArch64::STURXi;
390   }
391 }
392 
393 static unsigned getPreIndexedOpcode(unsigned Opc) {
394   // FIXME: We don't currently support creating pre-indexed loads/stores when
395   // the load or store is the unscaled version.  If we decide to perform such an
396   // optimization in the future the cases for the unscaled loads/stores will
397   // need to be added here.
398   switch (Opc) {
399   default:
400     llvm_unreachable("Opcode has no pre-indexed equivalent!");
401   case AArch64::STRSui:
402     return AArch64::STRSpre;
403   case AArch64::STRDui:
404     return AArch64::STRDpre;
405   case AArch64::STRQui:
406     return AArch64::STRQpre;
407   case AArch64::STRBBui:
408     return AArch64::STRBBpre;
409   case AArch64::STRHHui:
410     return AArch64::STRHHpre;
411   case AArch64::STRWui:
412     return AArch64::STRWpre;
413   case AArch64::STRXui:
414     return AArch64::STRXpre;
415   case AArch64::LDRSui:
416     return AArch64::LDRSpre;
417   case AArch64::LDRDui:
418     return AArch64::LDRDpre;
419   case AArch64::LDRQui:
420     return AArch64::LDRQpre;
421   case AArch64::LDRBBui:
422     return AArch64::LDRBBpre;
423   case AArch64::LDRHHui:
424     return AArch64::LDRHHpre;
425   case AArch64::LDRWui:
426     return AArch64::LDRWpre;
427   case AArch64::LDRXui:
428     return AArch64::LDRXpre;
429   case AArch64::LDRSWui:
430     return AArch64::LDRSWpre;
431   case AArch64::LDPSi:
432     return AArch64::LDPSpre;
433   case AArch64::LDPSWi:
434     return AArch64::LDPSWpre;
435   case AArch64::LDPDi:
436     return AArch64::LDPDpre;
437   case AArch64::LDPQi:
438     return AArch64::LDPQpre;
439   case AArch64::LDPWi:
440     return AArch64::LDPWpre;
441   case AArch64::LDPXi:
442     return AArch64::LDPXpre;
443   case AArch64::STPSi:
444     return AArch64::STPSpre;
445   case AArch64::STPDi:
446     return AArch64::STPDpre;
447   case AArch64::STPQi:
448     return AArch64::STPQpre;
449   case AArch64::STPWi:
450     return AArch64::STPWpre;
451   case AArch64::STPXi:
452     return AArch64::STPXpre;
453   }
454 }
455 
456 static unsigned getPostIndexedOpcode(unsigned Opc) {
457   switch (Opc) {
458   default:
459     llvm_unreachable("Opcode has no post-indexed wise equivalent!");
460   case AArch64::STRSui:
461   case AArch64::STURSi:
462     return AArch64::STRSpost;
463   case AArch64::STRDui:
464   case AArch64::STURDi:
465     return AArch64::STRDpost;
466   case AArch64::STRQui:
467   case AArch64::STURQi:
468     return AArch64::STRQpost;
469   case AArch64::STRBBui:
470     return AArch64::STRBBpost;
471   case AArch64::STRHHui:
472     return AArch64::STRHHpost;
473   case AArch64::STRWui:
474   case AArch64::STURWi:
475     return AArch64::STRWpost;
476   case AArch64::STRXui:
477   case AArch64::STURXi:
478     return AArch64::STRXpost;
479   case AArch64::LDRSui:
480   case AArch64::LDURSi:
481     return AArch64::LDRSpost;
482   case AArch64::LDRDui:
483   case AArch64::LDURDi:
484     return AArch64::LDRDpost;
485   case AArch64::LDRQui:
486   case AArch64::LDURQi:
487     return AArch64::LDRQpost;
488   case AArch64::LDRBBui:
489     return AArch64::LDRBBpost;
490   case AArch64::LDRHHui:
491     return AArch64::LDRHHpost;
492   case AArch64::LDRWui:
493   case AArch64::LDURWi:
494     return AArch64::LDRWpost;
495   case AArch64::LDRXui:
496   case AArch64::LDURXi:
497     return AArch64::LDRXpost;
498   case AArch64::LDRSWui:
499     return AArch64::LDRSWpost;
500   case AArch64::LDPSi:
501     return AArch64::LDPSpost;
502   case AArch64::LDPSWi:
503     return AArch64::LDPSWpost;
504   case AArch64::LDPDi:
505     return AArch64::LDPDpost;
506   case AArch64::LDPQi:
507     return AArch64::LDPQpost;
508   case AArch64::LDPWi:
509     return AArch64::LDPWpost;
510   case AArch64::LDPXi:
511     return AArch64::LDPXpost;
512   case AArch64::STPSi:
513     return AArch64::STPSpost;
514   case AArch64::STPDi:
515     return AArch64::STPDpost;
516   case AArch64::STPQi:
517     return AArch64::STPQpost;
518   case AArch64::STPWi:
519     return AArch64::STPWpost;
520   case AArch64::STPXi:
521     return AArch64::STPXpost;
522   }
523 }
524 
525 static bool isPairedLdSt(const MachineInstr &MI) {
526   switch (MI.getOpcode()) {
527   default:
528     return false;
529   case AArch64::LDPSi:
530   case AArch64::LDPSWi:
531   case AArch64::LDPDi:
532   case AArch64::LDPQi:
533   case AArch64::LDPWi:
534   case AArch64::LDPXi:
535   case AArch64::STPSi:
536   case AArch64::STPDi:
537   case AArch64::STPQi:
538   case AArch64::STPWi:
539   case AArch64::STPXi:
540     return true;
541   }
542 }
543 
544 static const MachineOperand &getLdStRegOp(const MachineInstr &MI,
545                                           unsigned PairedRegOp = 0) {
546   assert(PairedRegOp < 2 && "Unexpected register operand idx.");
547   unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
548   return MI.getOperand(Idx);
549 }
550 
551 static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
552   unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
553   return MI.getOperand(Idx);
554 }
555 
556 static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
557   unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
558   return MI.getOperand(Idx);
559 }
560 
561 static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
562                                   MachineInstr &StoreInst,
563                                   const AArch64InstrInfo *TII) {
564   assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
565   int LoadSize = getMemScale(LoadInst);
566   int StoreSize = getMemScale(StoreInst);
567   int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
568                              ? getLdStOffsetOp(StoreInst).getImm()
569                              : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
570   int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
571                              ? getLdStOffsetOp(LoadInst).getImm()
572                              : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
573   return (UnscaledStOffset <= UnscaledLdOffset) &&
574          (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
575 }
576 
577 static bool isPromotableZeroStoreInst(MachineInstr &MI) {
578   unsigned Opc = MI.getOpcode();
579   return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
580           isNarrowStore(Opc)) &&
581          getLdStRegOp(MI).getReg() == AArch64::WZR;
582 }
583 
584 static bool isPromotableLoadFromStore(MachineInstr &MI) {
585   switch (MI.getOpcode()) {
586   default:
587     return false;
588   // Scaled instructions.
589   case AArch64::LDRBBui:
590   case AArch64::LDRHHui:
591   case AArch64::LDRWui:
592   case AArch64::LDRXui:
593   // Unscaled instructions.
594   case AArch64::LDURBBi:
595   case AArch64::LDURHHi:
596   case AArch64::LDURWi:
597   case AArch64::LDURXi:
598     return true;
599   }
600 }
601 
602 static bool isMergeableLdStUpdate(MachineInstr &MI) {
603   unsigned Opc = MI.getOpcode();
604   switch (Opc) {
605   default:
606     return false;
607   // Scaled instructions.
608   case AArch64::STRSui:
609   case AArch64::STRDui:
610   case AArch64::STRQui:
611   case AArch64::STRXui:
612   case AArch64::STRWui:
613   case AArch64::STRHHui:
614   case AArch64::STRBBui:
615   case AArch64::LDRSui:
616   case AArch64::LDRDui:
617   case AArch64::LDRQui:
618   case AArch64::LDRXui:
619   case AArch64::LDRWui:
620   case AArch64::LDRHHui:
621   case AArch64::LDRBBui:
622   // Unscaled instructions.
623   case AArch64::STURSi:
624   case AArch64::STURDi:
625   case AArch64::STURQi:
626   case AArch64::STURWi:
627   case AArch64::STURXi:
628   case AArch64::LDURSi:
629   case AArch64::LDURDi:
630   case AArch64::LDURQi:
631   case AArch64::LDURWi:
632   case AArch64::LDURXi:
633   // Paired instructions.
634   case AArch64::LDPSi:
635   case AArch64::LDPSWi:
636   case AArch64::LDPDi:
637   case AArch64::LDPQi:
638   case AArch64::LDPWi:
639   case AArch64::LDPXi:
640   case AArch64::STPSi:
641   case AArch64::STPDi:
642   case AArch64::STPQi:
643   case AArch64::STPWi:
644   case AArch64::STPXi:
645     // Make sure this is a reg+imm (as opposed to an address reloc).
646     if (!getLdStOffsetOp(MI).isImm())
647       return false;
648 
649     return true;
650   }
651 }
652 
653 MachineBasicBlock::iterator
654 AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
655                                            MachineBasicBlock::iterator MergeMI,
656                                            const LdStPairFlags &Flags) {
657   assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
658          "Expected promotable zero stores.");
659 
660   MachineBasicBlock::iterator NextI = I;
661   ++NextI;
662   // If NextI is the second of the two instructions to be merged, we need
663   // to skip one further. Either way we merge will invalidate the iterator,
664   // and we don't need to scan the new instruction, as it's a pairwise
665   // instruction, which we're not considering for further action anyway.
666   if (NextI == MergeMI)
667     ++NextI;
668 
669   unsigned Opc = I->getOpcode();
670   bool IsScaled = !TII->isUnscaledLdSt(Opc);
671   int OffsetStride = IsScaled ? 1 : getMemScale(*I);
672 
673   bool MergeForward = Flags.getMergeForward();
674   // Insert our new paired instruction after whichever of the paired
675   // instructions MergeForward indicates.
676   MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
677   // Also based on MergeForward is from where we copy the base register operand
678   // so we get the flags compatible with the input code.
679   const MachineOperand &BaseRegOp =
680       MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
681 
682   // Which register is Rt and which is Rt2 depends on the offset order.
683   MachineInstr *RtMI;
684   if (getLdStOffsetOp(*I).getImm() ==
685       getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
686     RtMI = &*MergeMI;
687   else
688     RtMI = &*I;
689 
690   int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
691   // Change the scaled offset from small to large type.
692   if (IsScaled) {
693     assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
694     OffsetImm /= 2;
695   }
696 
697   // Construct the new instruction.
698   DebugLoc DL = I->getDebugLoc();
699   MachineBasicBlock *MBB = I->getParent();
700   MachineInstrBuilder MIB;
701   MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
702             .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
703             .add(BaseRegOp)
704             .addImm(OffsetImm)
705             .setMemRefs(I->mergeMemRefsWith(*MergeMI))
706             .setMIFlags(I->mergeFlagsWith(*MergeMI));
707   (void)MIB;
708 
709   DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n    ");
710   DEBUG(I->print(dbgs()));
711   DEBUG(dbgs() << "    ");
712   DEBUG(MergeMI->print(dbgs()));
713   DEBUG(dbgs() << "  with instruction:\n    ");
714   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
715   DEBUG(dbgs() << "\n");
716 
717   // Erase the old instructions.
718   I->eraseFromParent();
719   MergeMI->eraseFromParent();
720   return NextI;
721 }
722 
723 MachineBasicBlock::iterator
724 AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
725                                       MachineBasicBlock::iterator Paired,
726                                       const LdStPairFlags &Flags) {
727   MachineBasicBlock::iterator NextI = I;
728   ++NextI;
729   // If NextI is the second of the two instructions to be merged, we need
730   // to skip one further. Either way we merge will invalidate the iterator,
731   // and we don't need to scan the new instruction, as it's a pairwise
732   // instruction, which we're not considering for further action anyway.
733   if (NextI == Paired)
734     ++NextI;
735 
736   int SExtIdx = Flags.getSExtIdx();
737   unsigned Opc =
738       SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
739   bool IsUnscaled = TII->isUnscaledLdSt(Opc);
740   int OffsetStride = IsUnscaled ? getMemScale(*I) : 1;
741 
742   bool MergeForward = Flags.getMergeForward();
743   // Insert our new paired instruction after whichever of the paired
744   // instructions MergeForward indicates.
745   MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
746   // Also based on MergeForward is from where we copy the base register operand
747   // so we get the flags compatible with the input code.
748   const MachineOperand &BaseRegOp =
749       MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
750 
751   int Offset = getLdStOffsetOp(*I).getImm();
752   int PairedOffset = getLdStOffsetOp(*Paired).getImm();
753   bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
754   if (IsUnscaled != PairedIsUnscaled) {
755     // We're trying to pair instructions that differ in how they are scaled.  If
756     // I is scaled then scale the offset of Paired accordingly.  Otherwise, do
757     // the opposite (i.e., make Paired's offset unscaled).
758     int MemSize = getMemScale(*Paired);
759     if (PairedIsUnscaled) {
760       // If the unscaled offset isn't a multiple of the MemSize, we can't
761       // pair the operations together.
762       assert(!(PairedOffset % getMemScale(*Paired)) &&
763              "Offset should be a multiple of the stride!");
764       PairedOffset /= MemSize;
765     } else {
766       PairedOffset *= MemSize;
767     }
768   }
769 
770   // Which register is Rt and which is Rt2 depends on the offset order.
771   MachineInstr *RtMI, *Rt2MI;
772   if (Offset == PairedOffset + OffsetStride) {
773     RtMI = &*Paired;
774     Rt2MI = &*I;
775     // Here we swapped the assumption made for SExtIdx.
776     // I.e., we turn ldp I, Paired into ldp Paired, I.
777     // Update the index accordingly.
778     if (SExtIdx != -1)
779       SExtIdx = (SExtIdx + 1) % 2;
780   } else {
781     RtMI = &*I;
782     Rt2MI = &*Paired;
783   }
784   int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
785   // Scale the immediate offset, if necessary.
786   if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
787     assert(!(OffsetImm % getMemScale(*RtMI)) &&
788            "Unscaled offset cannot be scaled.");
789     OffsetImm /= getMemScale(*RtMI);
790   }
791 
792   // Construct the new instruction.
793   MachineInstrBuilder MIB;
794   DebugLoc DL = I->getDebugLoc();
795   MachineBasicBlock *MBB = I->getParent();
796   MachineOperand RegOp0 = getLdStRegOp(*RtMI);
797   MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
798   // Kill flags may become invalid when moving stores for pairing.
799   if (RegOp0.isUse()) {
800     if (!MergeForward) {
801       // Clear kill flags on store if moving upwards. Example:
802       //   STRWui %w0, ...
803       //   USE %w1
804       //   STRWui kill %w1  ; need to clear kill flag when moving STRWui upwards
805       RegOp0.setIsKill(false);
806       RegOp1.setIsKill(false);
807     } else {
808       // Clear kill flags of the first stores register. Example:
809       //   STRWui %w1, ...
810       //   USE kill %w1   ; need to clear kill flag when moving STRWui downwards
811       //   STRW %w0
812       unsigned Reg = getLdStRegOp(*I).getReg();
813       for (MachineInstr &MI : make_range(std::next(I), Paired))
814         MI.clearRegisterKills(Reg, TRI);
815     }
816   }
817   MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
818             .add(RegOp0)
819             .add(RegOp1)
820             .add(BaseRegOp)
821             .addImm(OffsetImm)
822             .setMemRefs(I->mergeMemRefsWith(*Paired))
823             .setMIFlags(I->mergeFlagsWith(*Paired));
824 
825   (void)MIB;
826 
827   DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n    ");
828   DEBUG(I->print(dbgs()));
829   DEBUG(dbgs() << "    ");
830   DEBUG(Paired->print(dbgs()));
831   DEBUG(dbgs() << "  with instruction:\n    ");
832   if (SExtIdx != -1) {
833     // Generate the sign extension for the proper result of the ldp.
834     // I.e., with X1, that would be:
835     // %w1 = KILL %w1, implicit-def %x1
836     // %x1 = SBFMXri killed %x1, 0, 31
837     MachineOperand &DstMO = MIB->getOperand(SExtIdx);
838     // Right now, DstMO has the extended register, since it comes from an
839     // extended opcode.
840     unsigned DstRegX = DstMO.getReg();
841     // Get the W variant of that register.
842     unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
843     // Update the result of LDP to use the W instead of the X variant.
844     DstMO.setReg(DstRegW);
845     DEBUG(((MachineInstr *)MIB)->print(dbgs()));
846     DEBUG(dbgs() << "\n");
847     // Make the machine verifier happy by providing a definition for
848     // the X register.
849     // Insert this definition right after the generated LDP, i.e., before
850     // InsertionPoint.
851     MachineInstrBuilder MIBKill =
852         BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
853             .addReg(DstRegW)
854             .addReg(DstRegX, RegState::Define);
855     MIBKill->getOperand(2).setImplicit();
856     // Create the sign extension.
857     MachineInstrBuilder MIBSXTW =
858         BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
859             .addReg(DstRegX)
860             .addImm(0)
861             .addImm(31);
862     (void)MIBSXTW;
863     DEBUG(dbgs() << "  Extend operand:\n    ");
864     DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
865   } else {
866     DEBUG(((MachineInstr *)MIB)->print(dbgs()));
867   }
868   DEBUG(dbgs() << "\n");
869 
870   // Erase the old instructions.
871   I->eraseFromParent();
872   Paired->eraseFromParent();
873 
874   return NextI;
875 }
876 
877 MachineBasicBlock::iterator
878 AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
879                                           MachineBasicBlock::iterator StoreI) {
880   MachineBasicBlock::iterator NextI = LoadI;
881   ++NextI;
882 
883   int LoadSize = getMemScale(*LoadI);
884   int StoreSize = getMemScale(*StoreI);
885   unsigned LdRt = getLdStRegOp(*LoadI).getReg();
886   const MachineOperand &StMO = getLdStRegOp(*StoreI);
887   unsigned StRt = getLdStRegOp(*StoreI).getReg();
888   bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
889 
890   assert((IsStoreXReg ||
891           TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
892          "Unexpected RegClass");
893 
894   MachineInstr *BitExtMI;
895   if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
896     // Remove the load, if the destination register of the loads is the same
897     // register for stored value.
898     if (StRt == LdRt && LoadSize == 8) {
899       for (MachineInstr &MI : make_range(StoreI->getIterator(),
900                                          LoadI->getIterator())) {
901         if (MI.killsRegister(StRt, TRI)) {
902           MI.clearRegisterKills(StRt, TRI);
903           break;
904         }
905       }
906       DEBUG(dbgs() << "Remove load instruction:\n    ");
907       DEBUG(LoadI->print(dbgs()));
908       DEBUG(dbgs() << "\n");
909       LoadI->eraseFromParent();
910       return NextI;
911     }
912     // Replace the load with a mov if the load and store are in the same size.
913     BitExtMI =
914         BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
915                 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
916             .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
917             .add(StMO)
918             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
919             .setMIFlags(LoadI->getFlags());
920   } else {
921     // FIXME: Currently we disable this transformation in big-endian targets as
922     // performance and correctness are verified only in little-endian.
923     if (!Subtarget->isLittleEndian())
924       return NextI;
925     bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
926     assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
927            "Unsupported ld/st match");
928     assert(LoadSize <= StoreSize && "Invalid load size");
929     int UnscaledLdOffset = IsUnscaled
930                                ? getLdStOffsetOp(*LoadI).getImm()
931                                : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
932     int UnscaledStOffset = IsUnscaled
933                                ? getLdStOffsetOp(*StoreI).getImm()
934                                : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
935     int Width = LoadSize * 8;
936     int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
937     int Imms = Immr + Width - 1;
938     unsigned DestReg = IsStoreXReg
939                            ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
940                                                       &AArch64::GPR64RegClass)
941                            : LdRt;
942 
943     assert((UnscaledLdOffset >= UnscaledStOffset &&
944             (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
945            "Invalid offset");
946 
947     Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
948     Imms = Immr + Width - 1;
949     if (UnscaledLdOffset == UnscaledStOffset) {
950       uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
951                                 | ((Immr) << 6)               // immr
952                                 | ((Imms) << 0)               // imms
953           ;
954 
955       BitExtMI =
956           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
957                   TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
958                   DestReg)
959               .add(StMO)
960               .addImm(AndMaskEncoded)
961               .setMIFlags(LoadI->getFlags());
962     } else {
963       BitExtMI =
964           BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
965                   TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
966                   DestReg)
967               .add(StMO)
968               .addImm(Immr)
969               .addImm(Imms)
970               .setMIFlags(LoadI->getFlags());
971     }
972   }
973 
974   // Clear kill flags between store and load.
975   for (MachineInstr &MI : make_range(StoreI->getIterator(),
976                                      BitExtMI->getIterator()))
977     if (MI.killsRegister(StRt, TRI)) {
978       MI.clearRegisterKills(StRt, TRI);
979       break;
980     }
981 
982   DEBUG(dbgs() << "Promoting load by replacing :\n    ");
983   DEBUG(StoreI->print(dbgs()));
984   DEBUG(dbgs() << "    ");
985   DEBUG(LoadI->print(dbgs()));
986   DEBUG(dbgs() << "  with instructions:\n    ");
987   DEBUG(StoreI->print(dbgs()));
988   DEBUG(dbgs() << "    ");
989   DEBUG((BitExtMI)->print(dbgs()));
990   DEBUG(dbgs() << "\n");
991 
992   // Erase the old instructions.
993   LoadI->eraseFromParent();
994   return NextI;
995 }
996 
997 /// trackRegDefsUses - Remember what registers the specified instruction uses
998 /// and modifies.
999 static void trackRegDefsUses(const MachineInstr &MI, BitVector &ModifiedRegs,
1000                              BitVector &UsedRegs,
1001                              const TargetRegisterInfo *TRI) {
1002   for (const MachineOperand &MO : MI.operands()) {
1003     if (MO.isRegMask())
1004       ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1005 
1006     if (!MO.isReg())
1007       continue;
1008     unsigned Reg = MO.getReg();
1009     if (!Reg)
1010       continue;
1011     if (MO.isDef()) {
1012       // WZR/XZR are not modified even when used as a destination register.
1013       if (Reg != AArch64::WZR && Reg != AArch64::XZR)
1014         for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1015           ModifiedRegs.set(*AI);
1016     } else {
1017       assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1018       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1019         UsedRegs.set(*AI);
1020     }
1021   }
1022 }
1023 
1024 static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1025   // Convert the byte-offset used by unscaled into an "element" offset used
1026   // by the scaled pair load/store instructions.
1027   if (IsUnscaled) {
1028     // If the byte-offset isn't a multiple of the stride, there's no point
1029     // trying to match it.
1030     if (Offset % OffsetStride)
1031       return false;
1032     Offset /= OffsetStride;
1033   }
1034   return Offset <= 63 && Offset >= -64;
1035 }
1036 
1037 // Do alignment, specialized to power of 2 and for signed ints,
1038 // avoiding having to do a C-style cast from uint_64t to int when
1039 // using alignTo from include/llvm/Support/MathExtras.h.
1040 // FIXME: Move this function to include/MathExtras.h?
1041 static int alignTo(int Num, int PowOf2) {
1042   return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1043 }
1044 
1045 static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
1046                      AliasAnalysis *AA) {
1047   // One of the instructions must modify memory.
1048   if (!MIa.mayStore() && !MIb.mayStore())
1049     return false;
1050 
1051   // Both instructions must be memory operations.
1052   if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
1053     return false;
1054 
1055   return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
1056 }
1057 
1058 static bool mayAlias(MachineInstr &MIa,
1059                      SmallVectorImpl<MachineInstr *> &MemInsns,
1060                      AliasAnalysis *AA) {
1061   for (MachineInstr *MIb : MemInsns)
1062     if (mayAlias(MIa, *MIb, AA))
1063       return true;
1064 
1065   return false;
1066 }
1067 
1068 bool AArch64LoadStoreOpt::findMatchingStore(
1069     MachineBasicBlock::iterator I, unsigned Limit,
1070     MachineBasicBlock::iterator &StoreI) {
1071   MachineBasicBlock::iterator B = I->getParent()->begin();
1072   MachineBasicBlock::iterator MBBI = I;
1073   MachineInstr &LoadMI = *I;
1074   unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
1075 
1076   // If the load is the first instruction in the block, there's obviously
1077   // not any matching store.
1078   if (MBBI == B)
1079     return false;
1080 
1081   // Track which registers have been modified and used between the first insn
1082   // and the second insn.
1083   ModifiedRegs.reset();
1084   UsedRegs.reset();
1085 
1086   unsigned Count = 0;
1087   do {
1088     --MBBI;
1089     MachineInstr &MI = *MBBI;
1090 
1091     // Don't count transient instructions towards the search limit since there
1092     // may be different numbers of them if e.g. debug information is present.
1093     if (!MI.isTransient())
1094       ++Count;
1095 
1096     // If the load instruction reads directly from the address to which the
1097     // store instruction writes and the stored value is not modified, we can
1098     // promote the load. Since we do not handle stores with pre-/post-index,
1099     // it's unnecessary to check if BaseReg is modified by the store itself.
1100     if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1101         BaseReg == getLdStBaseOp(MI).getReg() &&
1102         isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1103         !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1104       StoreI = MBBI;
1105       return true;
1106     }
1107 
1108     if (MI.isCall())
1109       return false;
1110 
1111     // Update modified / uses register lists.
1112     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1113 
1114     // Otherwise, if the base register is modified, we have no match, so
1115     // return early.
1116     if (ModifiedRegs[BaseReg])
1117       return false;
1118 
1119     // If we encounter a store aliased with the load, return early.
1120     if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
1121       return false;
1122   } while (MBBI != B && Count < Limit);
1123   return false;
1124 }
1125 
1126 // Returns true if FirstMI and MI are candidates for merging or pairing.
1127 // Otherwise, returns false.
1128 static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
1129                                        LdStPairFlags &Flags,
1130                                        const AArch64InstrInfo *TII) {
1131   // If this is volatile or if pairing is suppressed, not a candidate.
1132   if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1133     return false;
1134 
1135   // We should have already checked FirstMI for pair suppression and volatility.
1136   assert(!FirstMI.hasOrderedMemoryRef() &&
1137          !TII->isLdStPairSuppressed(FirstMI) &&
1138          "FirstMI shouldn't get here if either of these checks are true.");
1139 
1140   unsigned OpcA = FirstMI.getOpcode();
1141   unsigned OpcB = MI.getOpcode();
1142 
1143   // Opcodes match: nothing more to check.
1144   if (OpcA == OpcB)
1145     return true;
1146 
1147   // Try to match a sign-extended load/store with a zero-extended load/store.
1148   bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1149   unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1150   assert(IsValidLdStrOpc &&
1151          "Given Opc should be a Load or Store with an immediate");
1152   // OpcA will be the first instruction in the pair.
1153   if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1154     Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1155     return true;
1156   }
1157 
1158   // If the second instruction isn't even a mergable/pairable load/store, bail
1159   // out.
1160   if (!PairIsValidLdStrOpc)
1161     return false;
1162 
1163   // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1164   // offsets.
1165   if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1166     return false;
1167 
1168   // Try to match an unscaled load/store with a scaled load/store.
1169   return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
1170          getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1171 
1172   // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1173 }
1174 
1175 /// Scan the instructions looking for a load/store that can be combined with the
1176 /// current instruction into a wider equivalent or a load/store pair.
1177 MachineBasicBlock::iterator
1178 AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1179                                       LdStPairFlags &Flags, unsigned Limit,
1180                                       bool FindNarrowMerge) {
1181   MachineBasicBlock::iterator E = I->getParent()->end();
1182   MachineBasicBlock::iterator MBBI = I;
1183   MachineInstr &FirstMI = *I;
1184   ++MBBI;
1185 
1186   bool MayLoad = FirstMI.mayLoad();
1187   bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
1188   unsigned Reg = getLdStRegOp(FirstMI).getReg();
1189   unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1190   int Offset = getLdStOffsetOp(FirstMI).getImm();
1191   int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
1192   bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1193 
1194   // Track which registers have been modified and used between the first insn
1195   // (inclusive) and the second insn.
1196   ModifiedRegs.reset();
1197   UsedRegs.reset();
1198 
1199   // Remember any instructions that read/write memory between FirstMI and MI.
1200   SmallVector<MachineInstr *, 4> MemInsns;
1201 
1202   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1203     MachineInstr &MI = *MBBI;
1204 
1205     // Don't count transient instructions towards the search limit since there
1206     // may be different numbers of them if e.g. debug information is present.
1207     if (!MI.isTransient())
1208       ++Count;
1209 
1210     Flags.setSExtIdx(-1);
1211     if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1212         getLdStOffsetOp(MI).isImm()) {
1213       assert(MI.mayLoadOrStore() && "Expected memory operation.");
1214       // If we've found another instruction with the same opcode, check to see
1215       // if the base and offset are compatible with our starting instruction.
1216       // These instructions all have scaled immediate operands, so we just
1217       // check for +1/-1. Make sure to check the new instruction offset is
1218       // actually an immediate and not a symbolic reference destined for
1219       // a relocation.
1220       unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1221       int MIOffset = getLdStOffsetOp(MI).getImm();
1222       bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
1223       if (IsUnscaled != MIIsUnscaled) {
1224         // We're trying to pair instructions that differ in how they are scaled.
1225         // If FirstMI is scaled then scale the offset of MI accordingly.
1226         // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1227         int MemSize = getMemScale(MI);
1228         if (MIIsUnscaled) {
1229           // If the unscaled offset isn't a multiple of the MemSize, we can't
1230           // pair the operations together: bail and keep looking.
1231           if (MIOffset % MemSize) {
1232             trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1233             MemInsns.push_back(&MI);
1234             continue;
1235           }
1236           MIOffset /= MemSize;
1237         } else {
1238           MIOffset *= MemSize;
1239         }
1240       }
1241 
1242       if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1243                                    (Offset + OffsetStride == MIOffset))) {
1244         int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1245         if (FindNarrowMerge) {
1246           // If the alignment requirements of the scaled wide load/store
1247           // instruction can't express the offset of the scaled narrow input,
1248           // bail and keep looking. For promotable zero stores, allow only when
1249           // the stored value is the same (i.e., WZR).
1250           if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1251               (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1252             trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1253             MemInsns.push_back(&MI);
1254             continue;
1255           }
1256         } else {
1257           // Pairwise instructions have a 7-bit signed offset field. Single
1258           // insns have a 12-bit unsigned offset field.  If the resultant
1259           // immediate offset of merging these instructions is out of range for
1260           // a pairwise instruction, bail and keep looking.
1261           if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1262             trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1263             MemInsns.push_back(&MI);
1264             continue;
1265           }
1266           // If the alignment requirements of the paired (scaled) instruction
1267           // can't express the offset of the unscaled input, bail and keep
1268           // looking.
1269           if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1270             trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1271             MemInsns.push_back(&MI);
1272             continue;
1273           }
1274         }
1275         // If the destination register of the loads is the same register, bail
1276         // and keep looking. A load-pair instruction with both destination
1277         // registers the same is UNPREDICTABLE and will result in an exception.
1278         if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
1279           trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1280           MemInsns.push_back(&MI);
1281           continue;
1282         }
1283 
1284         // If the Rt of the second instruction was not modified or used between
1285         // the two instructions and none of the instructions between the second
1286         // and first alias with the second, we can combine the second into the
1287         // first.
1288         if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1289             !(MI.mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
1290             !mayAlias(MI, MemInsns, AA)) {
1291           Flags.setMergeForward(false);
1292           return MBBI;
1293         }
1294 
1295         // Likewise, if the Rt of the first instruction is not modified or used
1296         // between the two instructions and none of the instructions between the
1297         // first and the second alias with the first, we can combine the first
1298         // into the second.
1299         if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
1300             !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
1301             !mayAlias(FirstMI, MemInsns, AA)) {
1302           Flags.setMergeForward(true);
1303           return MBBI;
1304         }
1305         // Unable to combine these instructions due to interference in between.
1306         // Keep looking.
1307       }
1308     }
1309 
1310     // If the instruction wasn't a matching load or store.  Stop searching if we
1311     // encounter a call instruction that might modify memory.
1312     if (MI.isCall())
1313       return E;
1314 
1315     // Update modified / uses register lists.
1316     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1317 
1318     // Otherwise, if the base register is modified, we have no match, so
1319     // return early.
1320     if (ModifiedRegs[BaseReg])
1321       return E;
1322 
1323     // Update list of instructions that read/write memory.
1324     if (MI.mayLoadOrStore())
1325       MemInsns.push_back(&MI);
1326   }
1327   return E;
1328 }
1329 
1330 MachineBasicBlock::iterator
1331 AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1332                                      MachineBasicBlock::iterator Update,
1333                                      bool IsPreIdx) {
1334   assert((Update->getOpcode() == AArch64::ADDXri ||
1335           Update->getOpcode() == AArch64::SUBXri) &&
1336          "Unexpected base register update instruction to merge!");
1337   MachineBasicBlock::iterator NextI = I;
1338   // Return the instruction following the merged instruction, which is
1339   // the instruction following our unmerged load. Unless that's the add/sub
1340   // instruction we're merging, in which case it's the one after that.
1341   if (++NextI == Update)
1342     ++NextI;
1343 
1344   int Value = Update->getOperand(2).getImm();
1345   assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
1346          "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
1347   if (Update->getOpcode() == AArch64::SUBXri)
1348     Value = -Value;
1349 
1350   unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1351                              : getPostIndexedOpcode(I->getOpcode());
1352   MachineInstrBuilder MIB;
1353   if (!isPairedLdSt(*I)) {
1354     // Non-paired instruction.
1355     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1356               .add(getLdStRegOp(*Update))
1357               .add(getLdStRegOp(*I))
1358               .add(getLdStBaseOp(*I))
1359               .addImm(Value)
1360               .setMemRefs(I->memoperands_begin(), I->memoperands_end())
1361               .setMIFlags(I->mergeFlagsWith(*Update));
1362   } else {
1363     // Paired instruction.
1364     int Scale = getMemScale(*I);
1365     MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1366               .add(getLdStRegOp(*Update))
1367               .add(getLdStRegOp(*I, 0))
1368               .add(getLdStRegOp(*I, 1))
1369               .add(getLdStBaseOp(*I))
1370               .addImm(Value / Scale)
1371               .setMemRefs(I->memoperands_begin(), I->memoperands_end())
1372               .setMIFlags(I->mergeFlagsWith(*Update));
1373   }
1374   (void)MIB;
1375 
1376   if (IsPreIdx) {
1377     ++NumPreFolded;
1378     DEBUG(dbgs() << "Creating pre-indexed load/store.");
1379   } else {
1380     ++NumPostFolded;
1381     DEBUG(dbgs() << "Creating post-indexed load/store.");
1382   }
1383   DEBUG(dbgs() << "    Replacing instructions:\n    ");
1384   DEBUG(I->print(dbgs()));
1385   DEBUG(dbgs() << "    ");
1386   DEBUG(Update->print(dbgs()));
1387   DEBUG(dbgs() << "  with instruction:\n    ");
1388   DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1389   DEBUG(dbgs() << "\n");
1390 
1391   // Erase the old instructions for the block.
1392   I->eraseFromParent();
1393   Update->eraseFromParent();
1394 
1395   return NextI;
1396 }
1397 
1398 bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1399                                                MachineInstr &MI,
1400                                                unsigned BaseReg, int Offset) {
1401   switch (MI.getOpcode()) {
1402   default:
1403     break;
1404   case AArch64::SUBXri:
1405   case AArch64::ADDXri:
1406     // Make sure it's a vanilla immediate operand, not a relocation or
1407     // anything else we can't handle.
1408     if (!MI.getOperand(2).isImm())
1409       break;
1410     // Watch out for 1 << 12 shifted value.
1411     if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
1412       break;
1413 
1414     // The update instruction source and destination register must be the
1415     // same as the load/store base register.
1416     if (MI.getOperand(0).getReg() != BaseReg ||
1417         MI.getOperand(1).getReg() != BaseReg)
1418       break;
1419 
1420     bool IsPairedInsn = isPairedLdSt(MemMI);
1421     int UpdateOffset = MI.getOperand(2).getImm();
1422     if (MI.getOpcode() == AArch64::SUBXri)
1423       UpdateOffset = -UpdateOffset;
1424 
1425     // For non-paired load/store instructions, the immediate must fit in a
1426     // signed 9-bit integer.
1427     if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1428       break;
1429 
1430     // For paired load/store instructions, the immediate must be a multiple of
1431     // the scaling factor.  The scaled offset must also fit into a signed 7-bit
1432     // integer.
1433     if (IsPairedInsn) {
1434       int Scale = getMemScale(MemMI);
1435       if (UpdateOffset % Scale != 0)
1436         break;
1437 
1438       int ScaledOffset = UpdateOffset / Scale;
1439       if (ScaledOffset > 63 || ScaledOffset < -64)
1440         break;
1441     }
1442 
1443     // If we have a non-zero Offset, we check that it matches the amount
1444     // we're adding to the register.
1445     if (!Offset || Offset == UpdateOffset)
1446       return true;
1447     break;
1448   }
1449   return false;
1450 }
1451 
1452 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
1453     MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
1454   MachineBasicBlock::iterator E = I->getParent()->end();
1455   MachineInstr &MemMI = *I;
1456   MachineBasicBlock::iterator MBBI = I;
1457 
1458   unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1459   int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
1460 
1461   // Scan forward looking for post-index opportunities.  Updating instructions
1462   // can't be formed if the memory instruction doesn't have the offset we're
1463   // looking for.
1464   if (MIUnscaledOffset != UnscaledOffset)
1465     return E;
1466 
1467   // If the base register overlaps a destination register, we can't
1468   // merge the update.
1469   bool IsPairedInsn = isPairedLdSt(MemMI);
1470   for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1471     unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1472     if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1473       return E;
1474   }
1475 
1476   // Track which registers have been modified and used between the first insn
1477   // (inclusive) and the second insn.
1478   ModifiedRegs.reset();
1479   UsedRegs.reset();
1480   ++MBBI;
1481   for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1482     MachineInstr &MI = *MBBI;
1483 
1484     // Don't count transient instructions towards the search limit since there
1485     // may be different numbers of them if e.g. debug information is present.
1486     if (!MI.isTransient())
1487       ++Count;
1488 
1489     // If we found a match, return it.
1490     if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
1491       return MBBI;
1492 
1493     // Update the status of what the instruction clobbered and used.
1494     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1495 
1496     // Otherwise, if the base register is used or modified, we have no match, so
1497     // return early.
1498     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1499       return E;
1500   }
1501   return E;
1502 }
1503 
1504 MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
1505     MachineBasicBlock::iterator I, unsigned Limit) {
1506   MachineBasicBlock::iterator B = I->getParent()->begin();
1507   MachineBasicBlock::iterator E = I->getParent()->end();
1508   MachineInstr &MemMI = *I;
1509   MachineBasicBlock::iterator MBBI = I;
1510 
1511   unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1512   int Offset = getLdStOffsetOp(MemMI).getImm();
1513 
1514   // If the load/store is the first instruction in the block, there's obviously
1515   // not any matching update. Ditto if the memory offset isn't zero.
1516   if (MBBI == B || Offset != 0)
1517     return E;
1518   // If the base register overlaps a destination register, we can't
1519   // merge the update.
1520   bool IsPairedInsn = isPairedLdSt(MemMI);
1521   for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1522     unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1523     if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1524       return E;
1525   }
1526 
1527   // Track which registers have been modified and used between the first insn
1528   // (inclusive) and the second insn.
1529   ModifiedRegs.reset();
1530   UsedRegs.reset();
1531   unsigned Count = 0;
1532   do {
1533     --MBBI;
1534     MachineInstr &MI = *MBBI;
1535 
1536     // Don't count transient instructions towards the search limit since there
1537     // may be different numbers of them if e.g. debug information is present.
1538     if (!MI.isTransient())
1539       ++Count;
1540 
1541     // If we found a match, return it.
1542     if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
1543       return MBBI;
1544 
1545     // Update the status of what the instruction clobbered and used.
1546     trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1547 
1548     // Otherwise, if the base register is used or modified, we have no match, so
1549     // return early.
1550     if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1551       return E;
1552   } while (MBBI != B && Count < Limit);
1553   return E;
1554 }
1555 
1556 bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1557     MachineBasicBlock::iterator &MBBI) {
1558   MachineInstr &MI = *MBBI;
1559   // If this is a volatile load, don't mess with it.
1560   if (MI.hasOrderedMemoryRef())
1561     return false;
1562 
1563   // Make sure this is a reg+imm.
1564   // FIXME: It is possible to extend it to handle reg+reg cases.
1565   if (!getLdStOffsetOp(MI).isImm())
1566     return false;
1567 
1568   // Look backward up to LdStLimit instructions.
1569   MachineBasicBlock::iterator StoreI;
1570   if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
1571     ++NumLoadsFromStoresPromoted;
1572     // Promote the load. Keeping the iterator straight is a
1573     // pain, so we let the merge routine tell us what the next instruction
1574     // is after it's done mucking about.
1575     MBBI = promoteLoadFromStore(MBBI, StoreI);
1576     return true;
1577   }
1578   return false;
1579 }
1580 
1581 // Merge adjacent zero stores into a wider store.
1582 bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
1583     MachineBasicBlock::iterator &MBBI) {
1584   assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
1585   MachineInstr &MI = *MBBI;
1586   MachineBasicBlock::iterator E = MI.getParent()->end();
1587 
1588   if (!TII->isCandidateToMergeOrPair(MI))
1589     return false;
1590 
1591   // Look ahead up to LdStLimit instructions for a mergable instruction.
1592   LdStPairFlags Flags;
1593   MachineBasicBlock::iterator MergeMI =
1594       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
1595   if (MergeMI != E) {
1596     ++NumZeroStoresPromoted;
1597 
1598     // Keeping the iterator straight is a pain, so we let the merge routine tell
1599     // us what the next instruction is after it's done mucking about.
1600     MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
1601     return true;
1602   }
1603   return false;
1604 }
1605 
1606 // Find loads and stores that can be merged into a single load or store pair
1607 // instruction.
1608 bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1609   MachineInstr &MI = *MBBI;
1610   MachineBasicBlock::iterator E = MI.getParent()->end();
1611 
1612   if (!TII->isCandidateToMergeOrPair(MI))
1613     return false;
1614 
1615   // Early exit if the offset is not possible to match. (6 bits of positive
1616   // range, plus allow an extra one in case we find a later insn that matches
1617   // with Offset-1)
1618   bool IsUnscaled = TII->isUnscaledLdSt(MI);
1619   int Offset = getLdStOffsetOp(MI).getImm();
1620   int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1621   // Allow one more for offset.
1622   if (Offset > 0)
1623     Offset -= OffsetStride;
1624   if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1625     return false;
1626 
1627   // Look ahead up to LdStLimit instructions for a pairable instruction.
1628   LdStPairFlags Flags;
1629   MachineBasicBlock::iterator Paired =
1630       findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
1631   if (Paired != E) {
1632     ++NumPairCreated;
1633     if (TII->isUnscaledLdSt(MI))
1634       ++NumUnscaledPairCreated;
1635     // Keeping the iterator straight is a pain, so we let the merge routine tell
1636     // us what the next instruction is after it's done mucking about.
1637     MBBI = mergePairedInsns(MBBI, Paired, Flags);
1638     return true;
1639   }
1640   return false;
1641 }
1642 
1643 bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1644     (MachineBasicBlock::iterator &MBBI) {
1645   MachineInstr &MI = *MBBI;
1646   MachineBasicBlock::iterator E = MI.getParent()->end();
1647   MachineBasicBlock::iterator Update;
1648 
1649   // Look forward to try to form a post-index instruction. For example,
1650   // ldr x0, [x20]
1651   // add x20, x20, #32
1652   //   merged into:
1653   // ldr x0, [x20], #32
1654   Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1655   if (Update != E) {
1656     // Merge the update into the ld/st.
1657     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1658     return true;
1659   }
1660 
1661   // Don't know how to handle unscaled pre/post-index versions below, so bail.
1662   if (TII->isUnscaledLdSt(MI.getOpcode()))
1663     return false;
1664 
1665   // Look back to try to find a pre-index instruction. For example,
1666   // add x0, x0, #8
1667   // ldr x1, [x0]
1668   //   merged into:
1669   // ldr x1, [x0, #8]!
1670   Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1671   if (Update != E) {
1672     // Merge the update into the ld/st.
1673     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1674     return true;
1675   }
1676 
1677   // The immediate in the load/store is scaled by the size of the memory
1678   // operation. The immediate in the add we're looking for,
1679   // however, is not, so adjust here.
1680   int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
1681 
1682   // Look forward to try to find a post-index instruction. For example,
1683   // ldr x1, [x0, #64]
1684   // add x0, x0, #64
1685   //   merged into:
1686   // ldr x1, [x0, #64]!
1687   Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1688   if (Update != E) {
1689     // Merge the update into the ld/st.
1690     MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1691     return true;
1692   }
1693 
1694   return false;
1695 }
1696 
1697 bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1698                                         bool EnableNarrowZeroStOpt) {
1699   bool Modified = false;
1700   // Four tranformations to do here:
1701   // 1) Find loads that directly read from stores and promote them by
1702   //    replacing with mov instructions. If the store is wider than the load,
1703   //    the load will be replaced with a bitfield extract.
1704   //      e.g.,
1705   //        str w1, [x0, #4]
1706   //        ldrh w2, [x0, #6]
1707   //        ; becomes
1708   //        str w1, [x0, #4]
1709   //        lsr w2, w1, #16
1710   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1711        MBBI != E;) {
1712     if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
1713       Modified = true;
1714     else
1715       ++MBBI;
1716   }
1717   // 2) Merge adjacent zero stores into a wider store.
1718   //      e.g.,
1719   //        strh wzr, [x0]
1720   //        strh wzr, [x0, #2]
1721   //        ; becomes
1722   //        str wzr, [x0]
1723   //      e.g.,
1724   //        str wzr, [x0]
1725   //        str wzr, [x0, #4]
1726   //        ; becomes
1727   //        str xzr, [x0]
1728   if (EnableNarrowZeroStOpt)
1729     for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1730          MBBI != E;) {
1731       if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
1732         Modified = true;
1733       else
1734         ++MBBI;
1735     }
1736   // 3) Find loads and stores that can be merged into a single load or store
1737   //    pair instruction.
1738   //      e.g.,
1739   //        ldr x0, [x2]
1740   //        ldr x1, [x2, #8]
1741   //        ; becomes
1742   //        ldp x0, x1, [x2]
1743   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1744        MBBI != E;) {
1745     if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
1746       Modified = true;
1747     else
1748       ++MBBI;
1749   }
1750   // 4) Find base register updates that can be merged into the load or store
1751   //    as a base-reg writeback.
1752   //      e.g.,
1753   //        ldr x0, [x2]
1754   //        add x2, x2, #4
1755   //        ; becomes
1756   //        ldr x0, [x2], #4
1757   for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1758        MBBI != E;) {
1759     if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
1760       Modified = true;
1761     else
1762       ++MBBI;
1763   }
1764 
1765   return Modified;
1766 }
1767 
1768 bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1769   if (skipFunction(Fn.getFunction()))
1770     return false;
1771 
1772   Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1773   TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1774   TRI = Subtarget->getRegisterInfo();
1775   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1776 
1777   // Resize the modified and used register bitfield trackers.  We do this once
1778   // per function and then clear the bitfield each time we optimize a load or
1779   // store.
1780   ModifiedRegs.resize(TRI->getNumRegs());
1781   UsedRegs.resize(TRI->getNumRegs());
1782 
1783   bool Modified = false;
1784   bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
1785   for (auto &MBB : Fn)
1786     Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt);
1787 
1788   return Modified;
1789 }
1790 
1791 // FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
1792 // stores near one another?  Note: The pre-RA instruction scheduler already has
1793 // hooks to try and schedule pairable loads/stores together to improve pairing
1794 // opportunities.  Thus, pre-RA pairing pass may not be worth the effort.
1795 
1796 // FIXME: When pairing store instructions it's very possible for this pass to
1797 // hoist a store with a KILL marker above another use (without a KILL marker).
1798 // The resulting IR is invalid, but nothing uses the KILL markers after this
1799 // pass, so it's never caused a problem in practice.
1800 
1801 /// createAArch64LoadStoreOptimizationPass - returns an instance of the
1802 /// load / store optimization pass.
1803 FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1804   return new AArch64LoadStoreOpt();
1805 }
1806