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