1 //===-- ARMLoadStoreOptimizer.cpp - ARM 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 /// \file 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 "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "ThumbRegisterInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/RegisterClassInfo.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/LivePhysRegs.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "arm-ldst-opt"
50 
51 STATISTIC(NumLDMGened , "Number of ldm instructions generated");
52 STATISTIC(NumSTMGened , "Number of stm instructions generated");
53 STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
54 STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
55 STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
56 STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
57 STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
58 STATISTIC(NumLDRD2LDM,  "Number of ldrd instructions turned back into ldm");
59 STATISTIC(NumSTRD2STM,  "Number of strd instructions turned back into stm");
60 STATISTIC(NumLDRD2LDR,  "Number of ldrd instructions turned back into ldr's");
61 STATISTIC(NumSTRD2STR,  "Number of strd instructions turned back into str's");
62 
63 /// This switch disables formation of double/multi instructions that could
64 /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
65 /// disabled. This can be used to create libraries that are robust even when
66 /// users provoke undefined behaviour by supplying misaligned pointers.
67 /// \see mayCombineMisaligned()
68 static cl::opt<bool>
69 AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
70     cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
71 
72 #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
73 
74 namespace {
75   /// Post- register allocation pass the combine load / store instructions to
76   /// form ldm / stm instructions.
77   struct ARMLoadStoreOpt : public MachineFunctionPass {
78     static char ID;
79     ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
80 
81     const MachineFunction *MF;
82     const TargetInstrInfo *TII;
83     const TargetRegisterInfo *TRI;
84     const ARMSubtarget *STI;
85     const TargetLowering *TL;
86     ARMFunctionInfo *AFI;
87     LivePhysRegs LiveRegs;
88     RegisterClassInfo RegClassInfo;
89     MachineBasicBlock::const_iterator LiveRegPos;
90     bool LiveRegsValid;
91     bool RegClassInfoValid;
92     bool isThumb1, isThumb2;
93 
94     bool runOnMachineFunction(MachineFunction &Fn) override;
95 
96     MachineFunctionProperties getRequiredProperties() const override {
97       return MachineFunctionProperties().set(
98           MachineFunctionProperties::Property::NoVRegs);
99     }
100 
101     StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
102 
103   private:
104     /// A set of load/store MachineInstrs with same base register sorted by
105     /// offset.
106     struct MemOpQueueEntry {
107       MachineInstr *MI;
108       int Offset;        ///< Load/Store offset.
109       unsigned Position; ///< Position as counted from end of basic block.
110       MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
111           : MI(&MI), Offset(Offset), Position(Position) {}
112     };
113     typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
114 
115     /// A set of MachineInstrs that fulfill (nearly all) conditions to get
116     /// merged into a LDM/STM.
117     struct MergeCandidate {
118       /// List of instructions ordered by load/store offset.
119       SmallVector<MachineInstr*, 4> Instrs;
120       /// Index in Instrs of the instruction being latest in the schedule.
121       unsigned LatestMIIdx;
122       /// Index in Instrs of the instruction being earliest in the schedule.
123       unsigned EarliestMIIdx;
124       /// Index into the basic block where the merged instruction will be
125       /// inserted. (See MemOpQueueEntry.Position)
126       unsigned InsertPos;
127       /// Whether the instructions can be merged into a ldm/stm instruction.
128       bool CanMergeToLSMulti;
129       /// Whether the instructions can be merged into a ldrd/strd instruction.
130       bool CanMergeToLSDouble;
131     };
132     SpecificBumpPtrAllocator<MergeCandidate> Allocator;
133     SmallVector<const MergeCandidate*,4> Candidates;
134     SmallVector<MachineInstr*,4> MergeBaseCandidates;
135 
136     void moveLiveRegsBefore(const MachineBasicBlock &MBB,
137                             MachineBasicBlock::const_iterator Before);
138     unsigned findFreeReg(const TargetRegisterClass &RegClass);
139     void UpdateBaseRegUses(MachineBasicBlock &MBB,
140                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
141                            unsigned Base, unsigned WordOffset,
142                            ARMCC::CondCodes Pred, unsigned PredReg);
143     MachineInstr *CreateLoadStoreMulti(
144         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
145         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
146         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
147         ArrayRef<std::pair<unsigned, bool>> Regs);
148     MachineInstr *CreateLoadStoreDouble(
149         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
150         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
151         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
152         ArrayRef<std::pair<unsigned, bool>> Regs) const;
153     void FormCandidates(const MemOpQueue &MemOps);
154     MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
155     bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
156                              MachineBasicBlock::iterator &MBBI);
157     bool MergeBaseUpdateLoadStore(MachineInstr *MI);
158     bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
159     bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
160     bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
161     bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
162     bool CombineMovBx(MachineBasicBlock &MBB);
163   };
164   char ARMLoadStoreOpt::ID = 0;
165 }
166 
167 INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,
168                 false)
169 
170 static bool definesCPSR(const MachineInstr &MI) {
171   for (const auto &MO : MI.operands()) {
172     if (!MO.isReg())
173       continue;
174     if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
175       // If the instruction has live CPSR def, then it's not safe to fold it
176       // into load / store.
177       return true;
178   }
179 
180   return false;
181 }
182 
183 static int getMemoryOpOffset(const MachineInstr &MI) {
184   unsigned Opcode = MI.getOpcode();
185   bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
186   unsigned NumOperands = MI.getDesc().getNumOperands();
187   unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
188 
189   if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
190       Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
191       Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
192       Opcode == ARM::LDRi12   || Opcode == ARM::STRi12)
193     return OffField;
194 
195   // Thumb1 immediate offsets are scaled by 4
196   if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
197       Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
198     return OffField * 4;
199 
200   int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
201     : ARM_AM::getAM5Offset(OffField) * 4;
202   ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
203     : ARM_AM::getAM5Op(OffField);
204 
205   if (Op == ARM_AM::sub)
206     return -Offset;
207 
208   return Offset;
209 }
210 
211 static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
212   return MI.getOperand(1);
213 }
214 
215 static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
216   return MI.getOperand(0);
217 }
218 
219 static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
220   switch (Opcode) {
221   default: llvm_unreachable("Unhandled opcode!");
222   case ARM::LDRi12:
223     ++NumLDMGened;
224     switch (Mode) {
225     default: llvm_unreachable("Unhandled submode!");
226     case ARM_AM::ia: return ARM::LDMIA;
227     case ARM_AM::da: return ARM::LDMDA;
228     case ARM_AM::db: return ARM::LDMDB;
229     case ARM_AM::ib: return ARM::LDMIB;
230     }
231   case ARM::STRi12:
232     ++NumSTMGened;
233     switch (Mode) {
234     default: llvm_unreachable("Unhandled submode!");
235     case ARM_AM::ia: return ARM::STMIA;
236     case ARM_AM::da: return ARM::STMDA;
237     case ARM_AM::db: return ARM::STMDB;
238     case ARM_AM::ib: return ARM::STMIB;
239     }
240   case ARM::tLDRi:
241   case ARM::tLDRspi:
242     // tLDMIA is writeback-only - unless the base register is in the input
243     // reglist.
244     ++NumLDMGened;
245     switch (Mode) {
246     default: llvm_unreachable("Unhandled submode!");
247     case ARM_AM::ia: return ARM::tLDMIA;
248     }
249   case ARM::tSTRi:
250   case ARM::tSTRspi:
251     // There is no non-writeback tSTMIA either.
252     ++NumSTMGened;
253     switch (Mode) {
254     default: llvm_unreachable("Unhandled submode!");
255     case ARM_AM::ia: return ARM::tSTMIA_UPD;
256     }
257   case ARM::t2LDRi8:
258   case ARM::t2LDRi12:
259     ++NumLDMGened;
260     switch (Mode) {
261     default: llvm_unreachable("Unhandled submode!");
262     case ARM_AM::ia: return ARM::t2LDMIA;
263     case ARM_AM::db: return ARM::t2LDMDB;
264     }
265   case ARM::t2STRi8:
266   case ARM::t2STRi12:
267     ++NumSTMGened;
268     switch (Mode) {
269     default: llvm_unreachable("Unhandled submode!");
270     case ARM_AM::ia: return ARM::t2STMIA;
271     case ARM_AM::db: return ARM::t2STMDB;
272     }
273   case ARM::VLDRS:
274     ++NumVLDMGened;
275     switch (Mode) {
276     default: llvm_unreachable("Unhandled submode!");
277     case ARM_AM::ia: return ARM::VLDMSIA;
278     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
279     }
280   case ARM::VSTRS:
281     ++NumVSTMGened;
282     switch (Mode) {
283     default: llvm_unreachable("Unhandled submode!");
284     case ARM_AM::ia: return ARM::VSTMSIA;
285     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
286     }
287   case ARM::VLDRD:
288     ++NumVLDMGened;
289     switch (Mode) {
290     default: llvm_unreachable("Unhandled submode!");
291     case ARM_AM::ia: return ARM::VLDMDIA;
292     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
293     }
294   case ARM::VSTRD:
295     ++NumVSTMGened;
296     switch (Mode) {
297     default: llvm_unreachable("Unhandled submode!");
298     case ARM_AM::ia: return ARM::VSTMDIA;
299     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
300     }
301   }
302 }
303 
304 static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
305   switch (Opcode) {
306   default: llvm_unreachable("Unhandled opcode!");
307   case ARM::LDMIA_RET:
308   case ARM::LDMIA:
309   case ARM::LDMIA_UPD:
310   case ARM::STMIA:
311   case ARM::STMIA_UPD:
312   case ARM::tLDMIA:
313   case ARM::tLDMIA_UPD:
314   case ARM::tSTMIA_UPD:
315   case ARM::t2LDMIA_RET:
316   case ARM::t2LDMIA:
317   case ARM::t2LDMIA_UPD:
318   case ARM::t2STMIA:
319   case ARM::t2STMIA_UPD:
320   case ARM::VLDMSIA:
321   case ARM::VLDMSIA_UPD:
322   case ARM::VSTMSIA:
323   case ARM::VSTMSIA_UPD:
324   case ARM::VLDMDIA:
325   case ARM::VLDMDIA_UPD:
326   case ARM::VSTMDIA:
327   case ARM::VSTMDIA_UPD:
328     return ARM_AM::ia;
329 
330   case ARM::LDMDA:
331   case ARM::LDMDA_UPD:
332   case ARM::STMDA:
333   case ARM::STMDA_UPD:
334     return ARM_AM::da;
335 
336   case ARM::LDMDB:
337   case ARM::LDMDB_UPD:
338   case ARM::STMDB:
339   case ARM::STMDB_UPD:
340   case ARM::t2LDMDB:
341   case ARM::t2LDMDB_UPD:
342   case ARM::t2STMDB:
343   case ARM::t2STMDB_UPD:
344   case ARM::VLDMSDB_UPD:
345   case ARM::VSTMSDB_UPD:
346   case ARM::VLDMDDB_UPD:
347   case ARM::VSTMDDB_UPD:
348     return ARM_AM::db;
349 
350   case ARM::LDMIB:
351   case ARM::LDMIB_UPD:
352   case ARM::STMIB:
353   case ARM::STMIB_UPD:
354     return ARM_AM::ib;
355   }
356 }
357 
358 static bool isT1i32Load(unsigned Opc) {
359   return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
360 }
361 
362 static bool isT2i32Load(unsigned Opc) {
363   return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
364 }
365 
366 static bool isi32Load(unsigned Opc) {
367   return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
368 }
369 
370 static bool isT1i32Store(unsigned Opc) {
371   return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
372 }
373 
374 static bool isT2i32Store(unsigned Opc) {
375   return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
376 }
377 
378 static bool isi32Store(unsigned Opc) {
379   return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
380 }
381 
382 static bool isLoadSingle(unsigned Opc) {
383   return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
384 }
385 
386 static unsigned getImmScale(unsigned Opc) {
387   switch (Opc) {
388   default: llvm_unreachable("Unhandled opcode!");
389   case ARM::tLDRi:
390   case ARM::tSTRi:
391   case ARM::tLDRspi:
392   case ARM::tSTRspi:
393     return 1;
394   case ARM::tLDRHi:
395   case ARM::tSTRHi:
396     return 2;
397   case ARM::tLDRBi:
398   case ARM::tSTRBi:
399     return 4;
400   }
401 }
402 
403 static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
404   switch (MI->getOpcode()) {
405   default: return 0;
406   case ARM::LDRi12:
407   case ARM::STRi12:
408   case ARM::tLDRi:
409   case ARM::tSTRi:
410   case ARM::tLDRspi:
411   case ARM::tSTRspi:
412   case ARM::t2LDRi8:
413   case ARM::t2LDRi12:
414   case ARM::t2STRi8:
415   case ARM::t2STRi12:
416   case ARM::VLDRS:
417   case ARM::VSTRS:
418     return 4;
419   case ARM::VLDRD:
420   case ARM::VSTRD:
421     return 8;
422   case ARM::LDMIA:
423   case ARM::LDMDA:
424   case ARM::LDMDB:
425   case ARM::LDMIB:
426   case ARM::STMIA:
427   case ARM::STMDA:
428   case ARM::STMDB:
429   case ARM::STMIB:
430   case ARM::tLDMIA:
431   case ARM::tLDMIA_UPD:
432   case ARM::tSTMIA_UPD:
433   case ARM::t2LDMIA:
434   case ARM::t2LDMDB:
435   case ARM::t2STMIA:
436   case ARM::t2STMDB:
437   case ARM::VLDMSIA:
438   case ARM::VSTMSIA:
439     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
440   case ARM::VLDMDIA:
441   case ARM::VSTMDIA:
442     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
443   }
444 }
445 
446 /// Update future uses of the base register with the offset introduced
447 /// due to writeback. This function only works on Thumb1.
448 void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
449                                         MachineBasicBlock::iterator MBBI,
450                                         const DebugLoc &DL, unsigned Base,
451                                         unsigned WordOffset,
452                                         ARMCC::CondCodes Pred,
453                                         unsigned PredReg) {
454   assert(isThumb1 && "Can only update base register uses for Thumb1!");
455   // Start updating any instructions with immediate offsets. Insert a SUB before
456   // the first non-updateable instruction (if any).
457   for (; MBBI != MBB.end(); ++MBBI) {
458     bool InsertSub = false;
459     unsigned Opc = MBBI->getOpcode();
460 
461     if (MBBI->readsRegister(Base)) {
462       int Offset;
463       bool IsLoad =
464         Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
465       bool IsStore =
466         Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
467 
468       if (IsLoad || IsStore) {
469         // Loads and stores with immediate offsets can be updated, but only if
470         // the new offset isn't negative.
471         // The MachineOperand containing the offset immediate is the last one
472         // before predicates.
473         MachineOperand &MO =
474           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
475         // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
476         Offset = MO.getImm() - WordOffset * getImmScale(Opc);
477 
478         // If storing the base register, it needs to be reset first.
479         unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
480 
481         if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
482           MO.setImm(Offset);
483         else
484           InsertSub = true;
485 
486       } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
487                  !definesCPSR(*MBBI)) {
488         // SUBS/ADDS using this register, with a dead def of the CPSR.
489         // Merge it with the update; if the merged offset is too large,
490         // insert a new sub instead.
491         MachineOperand &MO =
492           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
493         Offset = (Opc == ARM::tSUBi8) ?
494           MO.getImm() + WordOffset * 4 :
495           MO.getImm() - WordOffset * 4 ;
496         if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
497           // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
498           // Offset == 0.
499           MO.setImm(Offset);
500           // The base register has now been reset, so exit early.
501           return;
502         } else {
503           InsertSub = true;
504         }
505 
506       } else {
507         // Can't update the instruction.
508         InsertSub = true;
509       }
510 
511     } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
512       // Since SUBS sets the condition flags, we can't place the base reset
513       // after an instruction that has a live CPSR def.
514       // The base register might also contain an argument for a function call.
515       InsertSub = true;
516     }
517 
518     if (InsertSub) {
519       // An instruction above couldn't be updated, so insert a sub.
520       BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
521           .add(t1CondCodeOp(true))
522           .addReg(Base)
523           .addImm(WordOffset * 4)
524           .addImm(Pred)
525           .addReg(PredReg);
526       return;
527     }
528 
529     if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
530       // Register got killed. Stop updating.
531       return;
532   }
533 
534   // End of block was reached.
535   if (MBB.succ_size() > 0) {
536     // FIXME: Because of a bug, live registers are sometimes missing from
537     // the successor blocks' live-in sets. This means we can't trust that
538     // information and *always* have to reset at the end of a block.
539     // See PR21029.
540     if (MBBI != MBB.end()) --MBBI;
541     BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
542         .add(t1CondCodeOp(true))
543         .addReg(Base)
544         .addImm(WordOffset * 4)
545         .addImm(Pred)
546         .addReg(PredReg);
547   }
548 }
549 
550 /// Return the first register of class \p RegClass that is not in \p Regs.
551 unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
552   if (!RegClassInfoValid) {
553     RegClassInfo.runOnMachineFunction(*MF);
554     RegClassInfoValid = true;
555   }
556 
557   for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
558     if (!LiveRegs.contains(Reg))
559       return Reg;
560   return 0;
561 }
562 
563 /// Compute live registers just before instruction \p Before (in normal schedule
564 /// direction). Computes backwards so multiple queries in the same block must
565 /// come in reverse order.
566 void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
567     MachineBasicBlock::const_iterator Before) {
568   // Initialize if we never queried in this block.
569   if (!LiveRegsValid) {
570     LiveRegs.init(*TRI);
571     LiveRegs.addLiveOuts(MBB);
572     LiveRegPos = MBB.end();
573     LiveRegsValid = true;
574   }
575   // Move backward just before the "Before" position.
576   while (LiveRegPos != Before) {
577     --LiveRegPos;
578     LiveRegs.stepBackward(*LiveRegPos);
579   }
580 }
581 
582 static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
583                         unsigned Reg) {
584   for (const std::pair<unsigned, bool> &R : Regs)
585     if (R.first == Reg)
586       return true;
587   return false;
588 }
589 
590 /// Create and insert a LDM or STM with Base as base register and registers in
591 /// Regs as the register operands that would be loaded / stored.  It returns
592 /// true if the transformation is done.
593 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
594     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
595     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
596     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
597     ArrayRef<std::pair<unsigned, bool>> Regs) {
598   unsigned NumRegs = Regs.size();
599   assert(NumRegs > 1);
600 
601   // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
602   // Compute liveness information for that register to make the decision.
603   bool SafeToClobberCPSR = !isThumb1 ||
604     (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
605      MachineBasicBlock::LQR_Dead);
606 
607   bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
608 
609   // Exception: If the base register is in the input reglist, Thumb1 LDM is
610   // non-writeback.
611   // It's also not possible to merge an STR of the base register in Thumb1.
612   if (isThumb1 && isi32Load(Opcode) && ContainsReg(Regs, Base)) {
613     assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
614     if (Opcode == ARM::tLDRi) {
615       Writeback = false;
616     } else if (Opcode == ARM::tSTRi) {
617       return nullptr;
618     }
619   }
620 
621   ARM_AM::AMSubMode Mode = ARM_AM::ia;
622   // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
623   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
624   bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
625 
626   if (Offset == 4 && haveIBAndDA) {
627     Mode = ARM_AM::ib;
628   } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
629     Mode = ARM_AM::da;
630   } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
631     // VLDM/VSTM do not support DB mode without also updating the base reg.
632     Mode = ARM_AM::db;
633   } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
634     // Check if this is a supported opcode before inserting instructions to
635     // calculate a new base register.
636     if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
637 
638     // If starting offset isn't zero, insert a MI to materialize a new base.
639     // But only do so if it is cost effective, i.e. merging more than two
640     // loads / stores.
641     if (NumRegs <= 2)
642       return nullptr;
643 
644     // On Thumb1, it's not worth materializing a new base register without
645     // clobbering the CPSR (i.e. not using ADDS/SUBS).
646     if (!SafeToClobberCPSR)
647       return nullptr;
648 
649     unsigned NewBase;
650     if (isi32Load(Opcode)) {
651       // If it is a load, then just use one of the destination registers
652       // as the new base. Will no longer be writeback in Thumb1.
653       NewBase = Regs[NumRegs-1].first;
654       Writeback = false;
655     } else {
656       // Find a free register that we can use as scratch register.
657       moveLiveRegsBefore(MBB, InsertBefore);
658       // The merged instruction does not exist yet but will use several Regs if
659       // it is a Store.
660       if (!isLoadSingle(Opcode))
661         for (const std::pair<unsigned, bool> &R : Regs)
662           LiveRegs.addReg(R.first);
663 
664       NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
665       if (NewBase == 0)
666         return nullptr;
667     }
668 
669     int BaseOpc =
670       isThumb2 ? ARM::t2ADDri :
671       (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
672       (isThumb1 && Offset < 8) ? ARM::tADDi3 :
673       isThumb1 ? ARM::tADDi8  : ARM::ADDri;
674 
675     if (Offset < 0) {
676       Offset = - Offset;
677       BaseOpc =
678         isThumb2 ? ARM::t2SUBri :
679         (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
680         isThumb1 ? ARM::tSUBi8  : ARM::SUBri;
681     }
682 
683     if (!TL->isLegalAddImmediate(Offset))
684       // FIXME: Try add with register operand?
685       return nullptr; // Probably not worth it then.
686 
687     // We can only append a kill flag to the add/sub input if the value is not
688     // used in the register list of the stm as well.
689     bool KillOldBase = BaseKill &&
690       (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
691 
692     if (isThumb1) {
693       // Thumb1: depending on immediate size, use either
694       //   ADDS NewBase, Base, #imm3
695       // or
696       //   MOV  NewBase, Base
697       //   ADDS NewBase, #imm8.
698       if (Base != NewBase &&
699           (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
700         // Need to insert a MOV to the new base first.
701         if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
702             !STI->hasV6Ops()) {
703           // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
704           if (Pred != ARMCC::AL)
705             return nullptr;
706           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
707             .addReg(Base, getKillRegState(KillOldBase));
708         } else
709           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
710             .addReg(Base, getKillRegState(KillOldBase))
711             .addImm(Pred).addReg(PredReg);
712 
713         // The following ADDS/SUBS becomes an update.
714         Base = NewBase;
715         KillOldBase = true;
716       }
717       if (BaseOpc == ARM::tADDrSPi) {
718         assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
719         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
720           .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset/4)
721           .addImm(Pred).addReg(PredReg);
722       } else
723         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
724             .add(t1CondCodeOp(true))
725             .addReg(Base, getKillRegState(KillOldBase))
726             .addImm(Offset)
727             .addImm(Pred)
728             .addReg(PredReg);
729     } else {
730       BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
731         .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
732         .addImm(Pred).addReg(PredReg).addReg(0);
733     }
734     Base = NewBase;
735     BaseKill = true; // New base is always killed straight away.
736   }
737 
738   bool isDef = isLoadSingle(Opcode);
739 
740   // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
741   // base register writeback.
742   Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
743   if (!Opcode)
744     return nullptr;
745 
746   // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
747   // - There is no writeback (LDM of base register),
748   // - the base register is killed by the merged instruction,
749   // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
750   //   to reset the base register.
751   // Otherwise, don't merge.
752   // It's safe to return here since the code to materialize a new base register
753   // above is also conditional on SafeToClobberCPSR.
754   if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
755     return nullptr;
756 
757   MachineInstrBuilder MIB;
758 
759   if (Writeback) {
760     assert(isThumb1 && "expected Writeback only inThumb1");
761     if (Opcode == ARM::tLDMIA) {
762       assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
763       // Update tLDMIA with writeback if necessary.
764       Opcode = ARM::tLDMIA_UPD;
765     }
766 
767     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
768 
769     // Thumb1: we might need to set base writeback when building the MI.
770     MIB.addReg(Base, getDefRegState(true))
771        .addReg(Base, getKillRegState(BaseKill));
772 
773     // The base isn't dead after a merged instruction with writeback.
774     // Insert a sub instruction after the newly formed instruction to reset.
775     if (!BaseKill)
776       UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
777 
778   } else {
779     // No writeback, simply build the MachineInstr.
780     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
781     MIB.addReg(Base, getKillRegState(BaseKill));
782   }
783 
784   MIB.addImm(Pred).addReg(PredReg);
785 
786   for (const std::pair<unsigned, bool> &R : Regs)
787     MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
788 
789   return MIB.getInstr();
790 }
791 
792 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
793     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
794     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
795     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
796     ArrayRef<std::pair<unsigned, bool>> Regs) const {
797   bool IsLoad = isi32Load(Opcode);
798   assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
799   unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
800 
801   assert(Regs.size() == 2);
802   MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
803                                     TII->get(LoadStoreOpcode));
804   if (IsLoad) {
805     MIB.addReg(Regs[0].first, RegState::Define)
806        .addReg(Regs[1].first, RegState::Define);
807   } else {
808     MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
809        .addReg(Regs[1].first, getKillRegState(Regs[1].second));
810   }
811   MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
812   return MIB.getInstr();
813 }
814 
815 /// Call MergeOps and update MemOps and merges accordingly on success.
816 MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
817   const MachineInstr *First = Cand.Instrs.front();
818   unsigned Opcode = First->getOpcode();
819   bool IsLoad = isLoadSingle(Opcode);
820   SmallVector<std::pair<unsigned, bool>, 8> Regs;
821   SmallVector<unsigned, 4> ImpDefs;
822   DenseSet<unsigned> KilledRegs;
823   DenseSet<unsigned> UsedRegs;
824   // Determine list of registers and list of implicit super-register defs.
825   for (const MachineInstr *MI : Cand.Instrs) {
826     const MachineOperand &MO = getLoadStoreRegOp(*MI);
827     unsigned Reg = MO.getReg();
828     bool IsKill = MO.isKill();
829     if (IsKill)
830       KilledRegs.insert(Reg);
831     Regs.push_back(std::make_pair(Reg, IsKill));
832     UsedRegs.insert(Reg);
833 
834     if (IsLoad) {
835       // Collect any implicit defs of super-registers, after merging we can't
836       // be sure anymore that we properly preserved these live ranges and must
837       // removed these implicit operands.
838       for (const MachineOperand &MO : MI->implicit_operands()) {
839         if (!MO.isReg() || !MO.isDef() || MO.isDead())
840           continue;
841         assert(MO.isImplicit());
842         unsigned DefReg = MO.getReg();
843 
844         if (is_contained(ImpDefs, DefReg))
845           continue;
846         // We can ignore cases where the super-reg is read and written.
847         if (MI->readsRegister(DefReg))
848           continue;
849         ImpDefs.push_back(DefReg);
850       }
851     }
852   }
853 
854   // Attempt the merge.
855   typedef MachineBasicBlock::iterator iterator;
856   MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
857   iterator InsertBefore = std::next(iterator(LatestMI));
858   MachineBasicBlock &MBB = *LatestMI->getParent();
859   unsigned Offset = getMemoryOpOffset(*First);
860   unsigned Base = getLoadStoreBaseOp(*First).getReg();
861   bool BaseKill = LatestMI->killsRegister(Base);
862   unsigned PredReg = 0;
863   ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
864   DebugLoc DL = First->getDebugLoc();
865   MachineInstr *Merged = nullptr;
866   if (Cand.CanMergeToLSDouble)
867     Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
868                                    Opcode, Pred, PredReg, DL, Regs);
869   if (!Merged && Cand.CanMergeToLSMulti)
870     Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
871                                   Opcode, Pred, PredReg, DL, Regs);
872   if (!Merged)
873     return nullptr;
874 
875   // Determine earliest instruction that will get removed. We then keep an
876   // iterator just above it so the following erases don't invalidated it.
877   iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
878   bool EarliestAtBegin = false;
879   if (EarliestI == MBB.begin()) {
880     EarliestAtBegin = true;
881   } else {
882     EarliestI = std::prev(EarliestI);
883   }
884 
885   // Remove instructions which have been merged.
886   for (MachineInstr *MI : Cand.Instrs)
887     MBB.erase(MI);
888 
889   // Determine range between the earliest removed instruction and the new one.
890   if (EarliestAtBegin)
891     EarliestI = MBB.begin();
892   else
893     EarliestI = std::next(EarliestI);
894   auto FixupRange = make_range(EarliestI, iterator(Merged));
895 
896   if (isLoadSingle(Opcode)) {
897     // If the previous loads defined a super-reg, then we have to mark earlier
898     // operands undef; Replicate the super-reg def on the merged instruction.
899     for (MachineInstr &MI : FixupRange) {
900       for (unsigned &ImpDefReg : ImpDefs) {
901         for (MachineOperand &MO : MI.implicit_operands()) {
902           if (!MO.isReg() || MO.getReg() != ImpDefReg)
903             continue;
904           if (MO.readsReg())
905             MO.setIsUndef();
906           else if (MO.isDef())
907             ImpDefReg = 0;
908         }
909       }
910     }
911 
912     MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
913     for (unsigned ImpDef : ImpDefs)
914       MIB.addReg(ImpDef, RegState::ImplicitDefine);
915   } else {
916     // Remove kill flags: We are possibly storing the values later now.
917     assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
918     for (MachineInstr &MI : FixupRange) {
919       for (MachineOperand &MO : MI.uses()) {
920         if (!MO.isReg() || !MO.isKill())
921           continue;
922         if (UsedRegs.count(MO.getReg()))
923           MO.setIsKill(false);
924       }
925     }
926     assert(ImpDefs.empty());
927   }
928 
929   return Merged;
930 }
931 
932 static bool isValidLSDoubleOffset(int Offset) {
933   unsigned Value = abs(Offset);
934   // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
935   // multiplied by 4.
936   return (Value % 4) == 0 && Value < 1024;
937 }
938 
939 /// Return true for loads/stores that can be combined to a double/multi
940 /// operation without increasing the requirements for alignment.
941 static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
942                                  const MachineInstr &MI) {
943   // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
944   // difference.
945   unsigned Opcode = MI.getOpcode();
946   if (!isi32Load(Opcode) && !isi32Store(Opcode))
947     return true;
948 
949   // Stack pointer alignment is out of the programmers control so we can trust
950   // SP-relative loads/stores.
951   if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
952       STI.getFrameLowering()->getTransientStackAlignment() >= 4)
953     return true;
954   return false;
955 }
956 
957 /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
958 void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
959   const MachineInstr *FirstMI = MemOps[0].MI;
960   unsigned Opcode = FirstMI->getOpcode();
961   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
962   unsigned Size = getLSMultipleTransferSize(FirstMI);
963 
964   unsigned SIndex = 0;
965   unsigned EIndex = MemOps.size();
966   do {
967     // Look at the first instruction.
968     const MachineInstr *MI = MemOps[SIndex].MI;
969     int Offset = MemOps[SIndex].Offset;
970     const MachineOperand &PMO = getLoadStoreRegOp(*MI);
971     unsigned PReg = PMO.getReg();
972     unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
973     unsigned Latest = SIndex;
974     unsigned Earliest = SIndex;
975     unsigned Count = 1;
976     bool CanMergeToLSDouble =
977       STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
978     // ARM errata 602117: LDRD with base in list may result in incorrect base
979     // register when interrupted or faulted.
980     if (STI->isCortexM3() && isi32Load(Opcode) &&
981         PReg == getLoadStoreBaseOp(*MI).getReg())
982       CanMergeToLSDouble = false;
983 
984     bool CanMergeToLSMulti = true;
985     // On swift vldm/vstm starting with an odd register number as that needs
986     // more uops than single vldrs.
987     if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
988       CanMergeToLSMulti = false;
989 
990     // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
991     // deprecated; LDM to PC is fine but cannot happen here.
992     if (PReg == ARM::SP || PReg == ARM::PC)
993       CanMergeToLSMulti = CanMergeToLSDouble = false;
994 
995     // Should we be conservative?
996     if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
997       CanMergeToLSMulti = CanMergeToLSDouble = false;
998 
999     // Merge following instructions where possible.
1000     for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1001       int NewOffset = MemOps[I].Offset;
1002       if (NewOffset != Offset + (int)Size)
1003         break;
1004       const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1005       unsigned Reg = MO.getReg();
1006       if (Reg == ARM::SP || Reg == ARM::PC)
1007         break;
1008 
1009       // See if the current load/store may be part of a multi load/store.
1010       unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
1011       bool PartOfLSMulti = CanMergeToLSMulti;
1012       if (PartOfLSMulti) {
1013         // Register numbers must be in ascending order.
1014         if (RegNum <= PRegNum)
1015           PartOfLSMulti = false;
1016         // For VFP / NEON load/store multiples, the registers must be
1017         // consecutive and within the limit on the number of registers per
1018         // instruction.
1019         else if (!isNotVFP && RegNum != PRegNum+1)
1020           PartOfLSMulti = false;
1021       }
1022       // See if the current load/store may be part of a double load/store.
1023       bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1024 
1025       if (!PartOfLSMulti && !PartOfLSDouble)
1026         break;
1027       CanMergeToLSMulti &= PartOfLSMulti;
1028       CanMergeToLSDouble &= PartOfLSDouble;
1029       // Track MemOp with latest and earliest position (Positions are
1030       // counted in reverse).
1031       unsigned Position = MemOps[I].Position;
1032       if (Position < MemOps[Latest].Position)
1033         Latest = I;
1034       else if (Position > MemOps[Earliest].Position)
1035         Earliest = I;
1036       // Prepare for next MemOp.
1037       Offset += Size;
1038       PRegNum = RegNum;
1039     }
1040 
1041     // Form a candidate from the Ops collected so far.
1042     MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1043     for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1044       Candidate->Instrs.push_back(MemOps[C].MI);
1045     Candidate->LatestMIIdx = Latest - SIndex;
1046     Candidate->EarliestMIIdx = Earliest - SIndex;
1047     Candidate->InsertPos = MemOps[Latest].Position;
1048     if (Count == 1)
1049       CanMergeToLSMulti = CanMergeToLSDouble = false;
1050     Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1051     Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1052     Candidates.push_back(Candidate);
1053     // Continue after the chain.
1054     SIndex += Count;
1055   } while (SIndex < EIndex);
1056 }
1057 
1058 static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1059                                             ARM_AM::AMSubMode Mode) {
1060   switch (Opc) {
1061   default: llvm_unreachable("Unhandled opcode!");
1062   case ARM::LDMIA:
1063   case ARM::LDMDA:
1064   case ARM::LDMDB:
1065   case ARM::LDMIB:
1066     switch (Mode) {
1067     default: llvm_unreachable("Unhandled submode!");
1068     case ARM_AM::ia: return ARM::LDMIA_UPD;
1069     case ARM_AM::ib: return ARM::LDMIB_UPD;
1070     case ARM_AM::da: return ARM::LDMDA_UPD;
1071     case ARM_AM::db: return ARM::LDMDB_UPD;
1072     }
1073   case ARM::STMIA:
1074   case ARM::STMDA:
1075   case ARM::STMDB:
1076   case ARM::STMIB:
1077     switch (Mode) {
1078     default: llvm_unreachable("Unhandled submode!");
1079     case ARM_AM::ia: return ARM::STMIA_UPD;
1080     case ARM_AM::ib: return ARM::STMIB_UPD;
1081     case ARM_AM::da: return ARM::STMDA_UPD;
1082     case ARM_AM::db: return ARM::STMDB_UPD;
1083     }
1084   case ARM::t2LDMIA:
1085   case ARM::t2LDMDB:
1086     switch (Mode) {
1087     default: llvm_unreachable("Unhandled submode!");
1088     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1089     case ARM_AM::db: return ARM::t2LDMDB_UPD;
1090     }
1091   case ARM::t2STMIA:
1092   case ARM::t2STMDB:
1093     switch (Mode) {
1094     default: llvm_unreachable("Unhandled submode!");
1095     case ARM_AM::ia: return ARM::t2STMIA_UPD;
1096     case ARM_AM::db: return ARM::t2STMDB_UPD;
1097     }
1098   case ARM::VLDMSIA:
1099     switch (Mode) {
1100     default: llvm_unreachable("Unhandled submode!");
1101     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1102     case ARM_AM::db: return ARM::VLDMSDB_UPD;
1103     }
1104   case ARM::VLDMDIA:
1105     switch (Mode) {
1106     default: llvm_unreachable("Unhandled submode!");
1107     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1108     case ARM_AM::db: return ARM::VLDMDDB_UPD;
1109     }
1110   case ARM::VSTMSIA:
1111     switch (Mode) {
1112     default: llvm_unreachable("Unhandled submode!");
1113     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1114     case ARM_AM::db: return ARM::VSTMSDB_UPD;
1115     }
1116   case ARM::VSTMDIA:
1117     switch (Mode) {
1118     default: llvm_unreachable("Unhandled submode!");
1119     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1120     case ARM_AM::db: return ARM::VSTMDDB_UPD;
1121     }
1122   }
1123 }
1124 
1125 /// Check if the given instruction increments or decrements a register and
1126 /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1127 /// generated by the instruction are possibly read as well.
1128 static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
1129                                   ARMCC::CondCodes Pred, unsigned PredReg) {
1130   bool CheckCPSRDef;
1131   int Scale;
1132   switch (MI.getOpcode()) {
1133   case ARM::tADDi8:  Scale =  4; CheckCPSRDef = true; break;
1134   case ARM::tSUBi8:  Scale = -4; CheckCPSRDef = true; break;
1135   case ARM::t2SUBri:
1136   case ARM::SUBri:   Scale = -1; CheckCPSRDef = true; break;
1137   case ARM::t2ADDri:
1138   case ARM::ADDri:   Scale =  1; CheckCPSRDef = true; break;
1139   case ARM::tADDspi: Scale =  4; CheckCPSRDef = false; break;
1140   case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1141   default: return 0;
1142   }
1143 
1144   unsigned MIPredReg;
1145   if (MI.getOperand(0).getReg() != Reg ||
1146       MI.getOperand(1).getReg() != Reg ||
1147       getInstrPredicate(MI, MIPredReg) != Pred ||
1148       MIPredReg != PredReg)
1149     return 0;
1150 
1151   if (CheckCPSRDef && definesCPSR(MI))
1152     return 0;
1153   return MI.getOperand(2).getImm() * Scale;
1154 }
1155 
1156 /// Searches for an increment or decrement of \p Reg before \p MBBI.
1157 static MachineBasicBlock::iterator
1158 findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
1159                  ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1160   Offset = 0;
1161   MachineBasicBlock &MBB = *MBBI->getParent();
1162   MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1163   MachineBasicBlock::iterator EndMBBI = MBB.end();
1164   if (MBBI == BeginMBBI)
1165     return EndMBBI;
1166 
1167   // Skip debug values.
1168   MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1169   while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
1170     --PrevMBBI;
1171 
1172   Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1173   return Offset == 0 ? EndMBBI : PrevMBBI;
1174 }
1175 
1176 /// Searches for a increment or decrement of \p Reg after \p MBBI.
1177 static MachineBasicBlock::iterator
1178 findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
1179                 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1180   Offset = 0;
1181   MachineBasicBlock &MBB = *MBBI->getParent();
1182   MachineBasicBlock::iterator EndMBBI = MBB.end();
1183   MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1184   // Skip debug values.
1185   while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1186     ++NextMBBI;
1187   if (NextMBBI == EndMBBI)
1188     return EndMBBI;
1189 
1190   Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1191   return Offset == 0 ? EndMBBI : NextMBBI;
1192 }
1193 
1194 /// Fold proceeding/trailing inc/dec of base register into the
1195 /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1196 ///
1197 /// stmia rn, <ra, rb, rc>
1198 /// rn := rn + 4 * 3;
1199 /// =>
1200 /// stmia rn!, <ra, rb, rc>
1201 ///
1202 /// rn := rn - 4 * 3;
1203 /// ldmia rn, <ra, rb, rc>
1204 /// =>
1205 /// ldmdb rn!, <ra, rb, rc>
1206 bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1207   // Thumb1 is already using updating loads/stores.
1208   if (isThumb1) return false;
1209 
1210   const MachineOperand &BaseOP = MI->getOperand(0);
1211   unsigned Base = BaseOP.getReg();
1212   bool BaseKill = BaseOP.isKill();
1213   unsigned PredReg = 0;
1214   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1215   unsigned Opcode = MI->getOpcode();
1216   DebugLoc DL = MI->getDebugLoc();
1217 
1218   // Can't use an updating ld/st if the base register is also a dest
1219   // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1220   for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1221     if (MI->getOperand(i).getReg() == Base)
1222       return false;
1223 
1224   int Bytes = getLSMultipleTransferSize(MI);
1225   MachineBasicBlock &MBB = *MI->getParent();
1226   MachineBasicBlock::iterator MBBI(MI);
1227   int Offset;
1228   MachineBasicBlock::iterator MergeInstr
1229     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1230   ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1231   if (Mode == ARM_AM::ia && Offset == -Bytes) {
1232     Mode = ARM_AM::db;
1233   } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1234     Mode = ARM_AM::da;
1235   } else {
1236     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1237     if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1238         ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1239 
1240       // We couldn't find an inc/dec to merge. But if the base is dead, we
1241       // can still change to a writeback form as that will save us 2 bytes
1242       // of code size. It can create WAW hazards though, so only do it if
1243       // we're minimizing code size.
1244       if (!MBB.getParent()->getFunction()->optForMinSize() || !BaseKill)
1245         return false;
1246 
1247       bool HighRegsUsed = false;
1248       for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1249         if (MI->getOperand(i).getReg() >= ARM::R8) {
1250           HighRegsUsed = true;
1251           break;
1252         }
1253 
1254       if (!HighRegsUsed)
1255         MergeInstr = MBB.end();
1256       else
1257         return false;
1258     }
1259   }
1260   if (MergeInstr != MBB.end())
1261     MBB.erase(MergeInstr);
1262 
1263   unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1264   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1265     .addReg(Base, getDefRegState(true)) // WB base register
1266     .addReg(Base, getKillRegState(BaseKill))
1267     .addImm(Pred).addReg(PredReg);
1268 
1269   // Transfer the rest of operands.
1270   for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
1271     MIB.add(MI->getOperand(OpNum));
1272 
1273   // Transfer memoperands.
1274   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1275 
1276   MBB.erase(MBBI);
1277   return true;
1278 }
1279 
1280 static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1281                                              ARM_AM::AddrOpc Mode) {
1282   switch (Opc) {
1283   case ARM::LDRi12:
1284     return ARM::LDR_PRE_IMM;
1285   case ARM::STRi12:
1286     return ARM::STR_PRE_IMM;
1287   case ARM::VLDRS:
1288     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1289   case ARM::VLDRD:
1290     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1291   case ARM::VSTRS:
1292     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1293   case ARM::VSTRD:
1294     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1295   case ARM::t2LDRi8:
1296   case ARM::t2LDRi12:
1297     return ARM::t2LDR_PRE;
1298   case ARM::t2STRi8:
1299   case ARM::t2STRi12:
1300     return ARM::t2STR_PRE;
1301   default: llvm_unreachable("Unhandled opcode!");
1302   }
1303 }
1304 
1305 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1306                                               ARM_AM::AddrOpc Mode) {
1307   switch (Opc) {
1308   case ARM::LDRi12:
1309     return ARM::LDR_POST_IMM;
1310   case ARM::STRi12:
1311     return ARM::STR_POST_IMM;
1312   case ARM::VLDRS:
1313     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1314   case ARM::VLDRD:
1315     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1316   case ARM::VSTRS:
1317     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1318   case ARM::VSTRD:
1319     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1320   case ARM::t2LDRi8:
1321   case ARM::t2LDRi12:
1322     return ARM::t2LDR_POST;
1323   case ARM::t2STRi8:
1324   case ARM::t2STRi12:
1325     return ARM::t2STR_POST;
1326   default: llvm_unreachable("Unhandled opcode!");
1327   }
1328 }
1329 
1330 /// Fold proceeding/trailing inc/dec of base register into the
1331 /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
1332 bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1333   // Thumb1 doesn't have updating LDR/STR.
1334   // FIXME: Use LDM/STM with single register instead.
1335   if (isThumb1) return false;
1336 
1337   unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1338   bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1339   unsigned Opcode = MI->getOpcode();
1340   DebugLoc DL = MI->getDebugLoc();
1341   bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1342                 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1343   bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1344   if (isi32Load(Opcode) || isi32Store(Opcode))
1345     if (MI->getOperand(2).getImm() != 0)
1346       return false;
1347   if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1348     return false;
1349 
1350   // Can't do the merge if the destination register is the same as the would-be
1351   // writeback register.
1352   if (MI->getOperand(0).getReg() == Base)
1353     return false;
1354 
1355   unsigned PredReg = 0;
1356   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1357   int Bytes = getLSMultipleTransferSize(MI);
1358   MachineBasicBlock &MBB = *MI->getParent();
1359   MachineBasicBlock::iterator MBBI(MI);
1360   int Offset;
1361   MachineBasicBlock::iterator MergeInstr
1362     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1363   unsigned NewOpc;
1364   if (!isAM5 && Offset == Bytes) {
1365     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1366   } else if (Offset == -Bytes) {
1367     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1368   } else {
1369     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1370     if (Offset == Bytes) {
1371       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1372     } else if (!isAM5 && Offset == -Bytes) {
1373       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1374     } else
1375       return false;
1376   }
1377   MBB.erase(MergeInstr);
1378 
1379   ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1380 
1381   bool isLd = isLoadSingle(Opcode);
1382   if (isAM5) {
1383     // VLDM[SD]_UPD, VSTM[SD]_UPD
1384     // (There are no base-updating versions of VLDR/VSTR instructions, but the
1385     // updating load/store-multiple instructions can be used with only one
1386     // register.)
1387     MachineOperand &MO = MI->getOperand(0);
1388     BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1389       .addReg(Base, getDefRegState(true)) // WB base register
1390       .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1391       .addImm(Pred).addReg(PredReg)
1392       .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1393                             getKillRegState(MO.isKill())));
1394   } else if (isLd) {
1395     if (isAM2) {
1396       // LDR_PRE, LDR_POST
1397       if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1398         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1399           .addReg(Base, RegState::Define)
1400           .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1401       } else {
1402         int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1403         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1404           .addReg(Base, RegState::Define)
1405           .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
1406       }
1407     } else {
1408       // t2LDR_PRE, t2LDR_POST
1409       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1410         .addReg(Base, RegState::Define)
1411         .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1412     }
1413   } else {
1414     MachineOperand &MO = MI->getOperand(0);
1415     // FIXME: post-indexed stores use am2offset_imm, which still encodes
1416     // the vestigal zero-reg offset register. When that's fixed, this clause
1417     // can be removed entirely.
1418     if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1419       int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1420       // STR_PRE, STR_POST
1421       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1422         .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1423         .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
1424     } else {
1425       // t2STR_PRE, t2STR_POST
1426       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1427         .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1428         .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1429     }
1430   }
1431   MBB.erase(MBBI);
1432 
1433   return true;
1434 }
1435 
1436 bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1437   unsigned Opcode = MI.getOpcode();
1438   assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1439          "Must have t2STRDi8 or t2LDRDi8");
1440   if (MI.getOperand(3).getImm() != 0)
1441     return false;
1442 
1443   // Behaviour for writeback is undefined if base register is the same as one
1444   // of the others.
1445   const MachineOperand &BaseOp = MI.getOperand(2);
1446   unsigned Base = BaseOp.getReg();
1447   const MachineOperand &Reg0Op = MI.getOperand(0);
1448   const MachineOperand &Reg1Op = MI.getOperand(1);
1449   if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1450     return false;
1451 
1452   unsigned PredReg;
1453   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1454   MachineBasicBlock::iterator MBBI(MI);
1455   MachineBasicBlock &MBB = *MI.getParent();
1456   int Offset;
1457   MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1458                                                             PredReg, Offset);
1459   unsigned NewOpc;
1460   if (Offset == 8 || Offset == -8) {
1461     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1462   } else {
1463     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1464     if (Offset == 8 || Offset == -8) {
1465       NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1466     } else
1467       return false;
1468   }
1469   MBB.erase(MergeInstr);
1470 
1471   DebugLoc DL = MI.getDebugLoc();
1472   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1473   if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1474     MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1475   } else {
1476     assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1477     MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1478   }
1479   MIB.addReg(BaseOp.getReg(), RegState::Kill)
1480      .addImm(Offset).addImm(Pred).addReg(PredReg);
1481   assert(TII->get(Opcode).getNumOperands() == 6 &&
1482          TII->get(NewOpc).getNumOperands() == 7 &&
1483          "Unexpected number of operands in Opcode specification.");
1484 
1485   // Transfer implicit operands.
1486   for (const MachineOperand &MO : MI.implicit_operands())
1487     MIB.add(MO);
1488   MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1489 
1490   MBB.erase(MBBI);
1491   return true;
1492 }
1493 
1494 /// Returns true if instruction is a memory operation that this pass is capable
1495 /// of operating on.
1496 static bool isMemoryOp(const MachineInstr &MI) {
1497   unsigned Opcode = MI.getOpcode();
1498   switch (Opcode) {
1499   case ARM::VLDRS:
1500   case ARM::VSTRS:
1501   case ARM::VLDRD:
1502   case ARM::VSTRD:
1503   case ARM::LDRi12:
1504   case ARM::STRi12:
1505   case ARM::tLDRi:
1506   case ARM::tSTRi:
1507   case ARM::tLDRspi:
1508   case ARM::tSTRspi:
1509   case ARM::t2LDRi8:
1510   case ARM::t2LDRi12:
1511   case ARM::t2STRi8:
1512   case ARM::t2STRi12:
1513     break;
1514   default:
1515     return false;
1516   }
1517   if (!MI.getOperand(1).isReg())
1518     return false;
1519 
1520   // When no memory operands are present, conservatively assume unaligned,
1521   // volatile, unfoldable.
1522   if (!MI.hasOneMemOperand())
1523     return false;
1524 
1525   const MachineMemOperand &MMO = **MI.memoperands_begin();
1526 
1527   // Don't touch volatile memory accesses - we may be changing their order.
1528   if (MMO.isVolatile())
1529     return false;
1530 
1531   // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1532   // not.
1533   if (MMO.getAlignment() < 4)
1534     return false;
1535 
1536   // str <undef> could probably be eliminated entirely, but for now we just want
1537   // to avoid making a mess of it.
1538   // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1539   if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1540     return false;
1541 
1542   // Likewise don't mess with references to undefined addresses.
1543   if (MI.getOperand(1).isUndef())
1544     return false;
1545 
1546   return true;
1547 }
1548 
1549 static void InsertLDR_STR(MachineBasicBlock &MBB,
1550                           MachineBasicBlock::iterator &MBBI, int Offset,
1551                           bool isDef, const DebugLoc &DL, unsigned NewOpc,
1552                           unsigned Reg, bool RegDeadKill, bool RegUndef,
1553                           unsigned BaseReg, bool BaseKill, bool BaseUndef,
1554                           bool OffKill, bool OffUndef, ARMCC::CondCodes Pred,
1555                           unsigned PredReg, const TargetInstrInfo *TII,
1556                           bool isT2) {
1557   if (isDef) {
1558     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1559                                       TII->get(NewOpc))
1560       .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
1561       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1562     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1563   } else {
1564     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1565                                       TII->get(NewOpc))
1566       .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1567       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1568     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1569   }
1570 }
1571 
1572 bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1573                                           MachineBasicBlock::iterator &MBBI) {
1574   MachineInstr *MI = &*MBBI;
1575   unsigned Opcode = MI->getOpcode();
1576   if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1577     return false;
1578 
1579   const MachineOperand &BaseOp = MI->getOperand(2);
1580   unsigned BaseReg = BaseOp.getReg();
1581   unsigned EvenReg = MI->getOperand(0).getReg();
1582   unsigned OddReg  = MI->getOperand(1).getReg();
1583   unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1584   unsigned OddRegNum  = TRI->getDwarfRegNum(OddReg, false);
1585 
1586   // ARM errata 602117: LDRD with base in list may result in incorrect base
1587   // register when interrupted or faulted.
1588   bool Errata602117 = EvenReg == BaseReg &&
1589     (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1590   // ARM LDRD/STRD needs consecutive registers.
1591   bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1592     (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1593 
1594   if (!Errata602117 && !NonConsecutiveRegs)
1595     return false;
1596 
1597   bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1598   bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1599   bool EvenDeadKill = isLd ?
1600     MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1601   bool EvenUndef = MI->getOperand(0).isUndef();
1602   bool OddDeadKill  = isLd ?
1603     MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1604   bool OddUndef = MI->getOperand(1).isUndef();
1605   bool BaseKill = BaseOp.isKill();
1606   bool BaseUndef = BaseOp.isUndef();
1607   bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
1608   bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
1609   int OffImm = getMemoryOpOffset(*MI);
1610   unsigned PredReg = 0;
1611   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1612 
1613   if (OddRegNum > EvenRegNum && OffImm == 0) {
1614     // Ascending register numbers and no offset. It's safe to change it to a
1615     // ldm or stm.
1616     unsigned NewOpc = (isLd)
1617       ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1618       : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1619     if (isLd) {
1620       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1621         .addReg(BaseReg, getKillRegState(BaseKill))
1622         .addImm(Pred).addReg(PredReg)
1623         .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1624         .addReg(OddReg,  getDefRegState(isLd) | getDeadRegState(OddDeadKill));
1625       ++NumLDRD2LDM;
1626     } else {
1627       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1628         .addReg(BaseReg, getKillRegState(BaseKill))
1629         .addImm(Pred).addReg(PredReg)
1630         .addReg(EvenReg,
1631                 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1632         .addReg(OddReg,
1633                 getKillRegState(OddDeadKill)  | getUndefRegState(OddUndef));
1634       ++NumSTRD2STM;
1635     }
1636   } else {
1637     // Split into two instructions.
1638     unsigned NewOpc = (isLd)
1639       ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1640       : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1641     // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1642     // so adjust and use t2LDRi12 here for that.
1643     unsigned NewOpc2 = (isLd)
1644       ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1645       : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1646     DebugLoc dl = MBBI->getDebugLoc();
1647     // If this is a load and base register is killed, it may have been
1648     // re-defed by the load, make sure the first load does not clobber it.
1649     if (isLd &&
1650         (BaseKill || OffKill) &&
1651         (TRI->regsOverlap(EvenReg, BaseReg))) {
1652       assert(!TRI->regsOverlap(OddReg, BaseReg));
1653       InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1654                     OddReg, OddDeadKill, false,
1655                     BaseReg, false, BaseUndef, false, OffUndef,
1656                     Pred, PredReg, TII, isT2);
1657       InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1658                     EvenReg, EvenDeadKill, false,
1659                     BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1660                     Pred, PredReg, TII, isT2);
1661     } else {
1662       if (OddReg == EvenReg && EvenDeadKill) {
1663         // If the two source operands are the same, the kill marker is
1664         // probably on the first one. e.g.
1665         // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
1666         EvenDeadKill = false;
1667         OddDeadKill = true;
1668       }
1669       // Never kill the base register in the first instruction.
1670       if (EvenReg == BaseReg)
1671         EvenDeadKill = false;
1672       InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1673                     EvenReg, EvenDeadKill, EvenUndef,
1674                     BaseReg, false, BaseUndef, false, OffUndef,
1675                     Pred, PredReg, TII, isT2);
1676       InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1677                     OddReg, OddDeadKill, OddUndef,
1678                     BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1679                     Pred, PredReg, TII, isT2);
1680     }
1681     if (isLd)
1682       ++NumLDRD2LDR;
1683     else
1684       ++NumSTRD2STR;
1685   }
1686 
1687   MBBI = MBB.erase(MBBI);
1688   return true;
1689 }
1690 
1691 /// An optimization pass to turn multiple LDR / STR ops of the same base and
1692 /// incrementing offset into LDM / STM ops.
1693 bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1694   MemOpQueue MemOps;
1695   unsigned CurrBase = 0;
1696   unsigned CurrOpc = ~0u;
1697   ARMCC::CondCodes CurrPred = ARMCC::AL;
1698   unsigned Position = 0;
1699   assert(Candidates.size() == 0);
1700   assert(MergeBaseCandidates.size() == 0);
1701   LiveRegsValid = false;
1702 
1703   for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1704        I = MBBI) {
1705     // The instruction in front of the iterator is the one we look at.
1706     MBBI = std::prev(I);
1707     if (FixInvalidRegPairOp(MBB, MBBI))
1708       continue;
1709     ++Position;
1710 
1711     if (isMemoryOp(*MBBI)) {
1712       unsigned Opcode = MBBI->getOpcode();
1713       const MachineOperand &MO = MBBI->getOperand(0);
1714       unsigned Reg = MO.getReg();
1715       unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
1716       unsigned PredReg = 0;
1717       ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
1718       int Offset = getMemoryOpOffset(*MBBI);
1719       if (CurrBase == 0) {
1720         // Start of a new chain.
1721         CurrBase = Base;
1722         CurrOpc  = Opcode;
1723         CurrPred = Pred;
1724         MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1725         continue;
1726       }
1727       // Note: No need to match PredReg in the next if.
1728       if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1729         // Watch out for:
1730         //   r4 := ldr [r0, #8]
1731         //   r4 := ldr [r0, #4]
1732         // or
1733         //   r0 := ldr [r0]
1734         // If a load overrides the base register or a register loaded by
1735         // another load in our chain, we cannot take this instruction.
1736         bool Overlap = false;
1737         if (isLoadSingle(Opcode)) {
1738           Overlap = (Base == Reg);
1739           if (!Overlap) {
1740             for (const MemOpQueueEntry &E : MemOps) {
1741               if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1742                 Overlap = true;
1743                 break;
1744               }
1745             }
1746           }
1747         }
1748 
1749         if (!Overlap) {
1750           // Check offset and sort memory operation into the current chain.
1751           if (Offset > MemOps.back().Offset) {
1752             MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1753             continue;
1754           } else {
1755             MemOpQueue::iterator MI, ME;
1756             for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1757               if (Offset < MI->Offset) {
1758                 // Found a place to insert.
1759                 break;
1760               }
1761               if (Offset == MI->Offset) {
1762                 // Collision, abort.
1763                 MI = ME;
1764                 break;
1765               }
1766             }
1767             if (MI != MemOps.end()) {
1768               MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1769               continue;
1770             }
1771           }
1772         }
1773       }
1774 
1775       // Don't advance the iterator; The op will start a new chain next.
1776       MBBI = I;
1777       --Position;
1778       // Fallthrough to look into existing chain.
1779     } else if (MBBI->isDebugValue()) {
1780       continue;
1781     } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1782                MBBI->getOpcode() == ARM::t2STRDi8) {
1783       // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1784       // remember them because we may still be able to merge add/sub into them.
1785       MergeBaseCandidates.push_back(&*MBBI);
1786     }
1787 
1788 
1789     // If we are here then the chain is broken; Extract candidates for a merge.
1790     if (MemOps.size() > 0) {
1791       FormCandidates(MemOps);
1792       // Reset for the next chain.
1793       CurrBase = 0;
1794       CurrOpc = ~0u;
1795       CurrPred = ARMCC::AL;
1796       MemOps.clear();
1797     }
1798   }
1799   if (MemOps.size() > 0)
1800     FormCandidates(MemOps);
1801 
1802   // Sort candidates so they get processed from end to begin of the basic
1803   // block later; This is necessary for liveness calculation.
1804   auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1805     return M0->InsertPos < M1->InsertPos;
1806   };
1807   std::sort(Candidates.begin(), Candidates.end(), LessThan);
1808 
1809   // Go through list of candidates and merge.
1810   bool Changed = false;
1811   for (const MergeCandidate *Candidate : Candidates) {
1812     if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
1813       MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1814       // Merge preceding/trailing base inc/dec into the merged op.
1815       if (Merged) {
1816         Changed = true;
1817         unsigned Opcode = Merged->getOpcode();
1818         if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
1819           MergeBaseUpdateLSDouble(*Merged);
1820         else
1821           MergeBaseUpdateLSMultiple(Merged);
1822       } else {
1823         for (MachineInstr *MI : Candidate->Instrs) {
1824           if (MergeBaseUpdateLoadStore(MI))
1825             Changed = true;
1826         }
1827       }
1828     } else {
1829       assert(Candidate->Instrs.size() == 1);
1830       if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
1831         Changed = true;
1832     }
1833   }
1834   Candidates.clear();
1835   // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
1836   for (MachineInstr *MI : MergeBaseCandidates)
1837     MergeBaseUpdateLSDouble(*MI);
1838   MergeBaseCandidates.clear();
1839 
1840   return Changed;
1841 }
1842 
1843 /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
1844 /// into the preceding stack restore so it directly restore the value of LR
1845 /// into pc.
1846 ///   ldmfd sp!, {..., lr}
1847 ///   bx lr
1848 /// or
1849 ///   ldmfd sp!, {..., lr}
1850 ///   mov pc, lr
1851 /// =>
1852 ///   ldmfd sp!, {..., pc}
1853 bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
1854   // Thumb1 LDM doesn't allow high registers.
1855   if (isThumb1) return false;
1856   if (MBB.empty()) return false;
1857 
1858   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1859   if (MBBI != MBB.begin() && MBBI != MBB.end() &&
1860       (MBBI->getOpcode() == ARM::BX_RET ||
1861        MBBI->getOpcode() == ARM::tBX_RET ||
1862        MBBI->getOpcode() == ARM::MOVPCLR)) {
1863     MachineBasicBlock::iterator PrevI = std::prev(MBBI);
1864     // Ignore any DBG_VALUE instructions.
1865     while (PrevI->isDebugValue() && PrevI != MBB.begin())
1866       --PrevI;
1867     MachineInstr &PrevMI = *PrevI;
1868     unsigned Opcode = PrevMI.getOpcode();
1869     if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
1870         Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
1871         Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
1872       MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
1873       if (MO.getReg() != ARM::LR)
1874         return false;
1875       unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
1876       assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
1877               Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
1878       PrevMI.setDesc(TII->get(NewOpc));
1879       MO.setReg(ARM::PC);
1880       PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
1881       MBB.erase(MBBI);
1882       return true;
1883     }
1884   }
1885   return false;
1886 }
1887 
1888 bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
1889   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1890   if (MBBI == MBB.begin() || MBBI == MBB.end() ||
1891       MBBI->getOpcode() != ARM::tBX_RET)
1892     return false;
1893 
1894   MachineBasicBlock::iterator Prev = MBBI;
1895   --Prev;
1896   if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR))
1897     return false;
1898 
1899   for (auto Use : Prev->uses())
1900     if (Use.isKill()) {
1901       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
1902           .addReg(Use.getReg(), RegState::Kill)
1903           .add(predOps(ARMCC::AL))
1904           .copyImplicitOps(*MBBI);
1905       MBB.erase(MBBI);
1906       MBB.erase(Prev);
1907       return true;
1908     }
1909 
1910   llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
1911 }
1912 
1913 bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1914   if (skipFunction(*Fn.getFunction()))
1915     return false;
1916 
1917   MF = &Fn;
1918   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1919   TL = STI->getTargetLowering();
1920   AFI = Fn.getInfo<ARMFunctionInfo>();
1921   TII = STI->getInstrInfo();
1922   TRI = STI->getRegisterInfo();
1923 
1924   RegClassInfoValid = false;
1925   isThumb2 = AFI->isThumb2Function();
1926   isThumb1 = AFI->isThumbFunction() && !isThumb2;
1927 
1928   bool Modified = false;
1929   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1930        ++MFI) {
1931     MachineBasicBlock &MBB = *MFI;
1932     Modified |= LoadStoreMultipleOpti(MBB);
1933     if (STI->hasV5TOps())
1934       Modified |= MergeReturnIntoLDM(MBB);
1935     if (isThumb1)
1936       Modified |= CombineMovBx(MBB);
1937   }
1938 
1939   Allocator.DestroyAll();
1940   return Modified;
1941 }
1942 
1943 #define ARM_PREALLOC_LOAD_STORE_OPT_NAME                                       \
1944   "ARM pre- register allocation load / store optimization pass"
1945 
1946 namespace {
1947   /// Pre- register allocation pass that move load / stores from consecutive
1948   /// locations close to make it more likely they will be combined later.
1949   struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
1950     static char ID;
1951     ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
1952 
1953     const DataLayout *TD;
1954     const TargetInstrInfo *TII;
1955     const TargetRegisterInfo *TRI;
1956     const ARMSubtarget *STI;
1957     MachineRegisterInfo *MRI;
1958     MachineFunction *MF;
1959 
1960     bool runOnMachineFunction(MachineFunction &Fn) override;
1961 
1962     StringRef getPassName() const override {
1963       return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
1964     }
1965 
1966   private:
1967     bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1968                           unsigned &NewOpc, unsigned &EvenReg,
1969                           unsigned &OddReg, unsigned &BaseReg,
1970                           int &Offset,
1971                           unsigned &PredReg, ARMCC::CondCodes &Pred,
1972                           bool &isT2);
1973     bool RescheduleOps(MachineBasicBlock *MBB,
1974                        SmallVectorImpl<MachineInstr *> &Ops,
1975                        unsigned Base, bool isLd,
1976                        DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1977     bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1978   };
1979   char ARMPreAllocLoadStoreOpt::ID = 0;
1980 }
1981 
1982 INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
1983                 ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
1984 
1985 bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1986   if (AssumeMisalignedLoadStores || skipFunction(*Fn.getFunction()))
1987     return false;
1988 
1989   TD = &Fn.getDataLayout();
1990   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1991   TII = STI->getInstrInfo();
1992   TRI = STI->getRegisterInfo();
1993   MRI = &Fn.getRegInfo();
1994   MF  = &Fn;
1995 
1996   bool Modified = false;
1997   for (MachineBasicBlock &MFI : Fn)
1998     Modified |= RescheduleLoadStoreInstrs(&MFI);
1999 
2000   return Modified;
2001 }
2002 
2003 static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2004                                       MachineBasicBlock::iterator I,
2005                                       MachineBasicBlock::iterator E,
2006                                       SmallPtrSetImpl<MachineInstr*> &MemOps,
2007                                       SmallSet<unsigned, 4> &MemRegs,
2008                                       const TargetRegisterInfo *TRI) {
2009   // Are there stores / loads / calls between them?
2010   // FIXME: This is overly conservative. We should make use of alias information
2011   // some day.
2012   SmallSet<unsigned, 4> AddedRegPressure;
2013   while (++I != E) {
2014     if (I->isDebugValue() || MemOps.count(&*I))
2015       continue;
2016     if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2017       return false;
2018     if (isLd && I->mayStore())
2019       return false;
2020     if (!isLd) {
2021       if (I->mayLoad())
2022         return false;
2023       // It's not safe to move the first 'str' down.
2024       // str r1, [r0]
2025       // strh r5, [r0]
2026       // str r4, [r0, #+4]
2027       if (I->mayStore())
2028         return false;
2029     }
2030     for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2031       MachineOperand &MO = I->getOperand(j);
2032       if (!MO.isReg())
2033         continue;
2034       unsigned Reg = MO.getReg();
2035       if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2036         return false;
2037       if (Reg != Base && !MemRegs.count(Reg))
2038         AddedRegPressure.insert(Reg);
2039     }
2040   }
2041 
2042   // Estimate register pressure increase due to the transformation.
2043   if (MemRegs.size() <= 4)
2044     // Ok if we are moving small number of instructions.
2045     return true;
2046   return AddedRegPressure.size() <= MemRegs.size() * 2;
2047 }
2048 
2049 bool
2050 ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
2051                                           DebugLoc &dl, unsigned &NewOpc,
2052                                           unsigned &FirstReg,
2053                                           unsigned &SecondReg,
2054                                           unsigned &BaseReg, int &Offset,
2055                                           unsigned &PredReg,
2056                                           ARMCC::CondCodes &Pred,
2057                                           bool &isT2) {
2058   // Make sure we're allowed to generate LDRD/STRD.
2059   if (!STI->hasV5TEOps())
2060     return false;
2061 
2062   // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2063   unsigned Scale = 1;
2064   unsigned Opcode = Op0->getOpcode();
2065   if (Opcode == ARM::LDRi12) {
2066     NewOpc = ARM::LDRD;
2067   } else if (Opcode == ARM::STRi12) {
2068     NewOpc = ARM::STRD;
2069   } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2070     NewOpc = ARM::t2LDRDi8;
2071     Scale = 4;
2072     isT2 = true;
2073   } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2074     NewOpc = ARM::t2STRDi8;
2075     Scale = 4;
2076     isT2 = true;
2077   } else {
2078     return false;
2079   }
2080 
2081   // Make sure the base address satisfies i64 ld / st alignment requirement.
2082   // At the moment, we ignore the memoryoperand's value.
2083   // If we want to use AliasAnalysis, we should check it accordingly.
2084   if (!Op0->hasOneMemOperand() ||
2085       (*Op0->memoperands_begin())->isVolatile())
2086     return false;
2087 
2088   unsigned Align = (*Op0->memoperands_begin())->getAlignment();
2089   const Function *Func = MF->getFunction();
2090   unsigned ReqAlign = STI->hasV6Ops()
2091     ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
2092     : 8;  // Pre-v6 need 8-byte align
2093   if (Align < ReqAlign)
2094     return false;
2095 
2096   // Then make sure the immediate offset fits.
2097   int OffImm = getMemoryOpOffset(*Op0);
2098   if (isT2) {
2099     int Limit = (1 << 8) * Scale;
2100     if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2101       return false;
2102     Offset = OffImm;
2103   } else {
2104     ARM_AM::AddrOpc AddSub = ARM_AM::add;
2105     if (OffImm < 0) {
2106       AddSub = ARM_AM::sub;
2107       OffImm = - OffImm;
2108     }
2109     int Limit = (1 << 8) * Scale;
2110     if (OffImm >= Limit || (OffImm & (Scale-1)))
2111       return false;
2112     Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2113   }
2114   FirstReg = Op0->getOperand(0).getReg();
2115   SecondReg = Op1->getOperand(0).getReg();
2116   if (FirstReg == SecondReg)
2117     return false;
2118   BaseReg = Op0->getOperand(1).getReg();
2119   Pred = getInstrPredicate(*Op0, PredReg);
2120   dl = Op0->getDebugLoc();
2121   return true;
2122 }
2123 
2124 bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
2125                                  SmallVectorImpl<MachineInstr *> &Ops,
2126                                  unsigned Base, bool isLd,
2127                                  DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2128   bool RetVal = false;
2129 
2130   // Sort by offset (in reverse order).
2131   std::sort(Ops.begin(), Ops.end(),
2132             [](const MachineInstr *LHS, const MachineInstr *RHS) {
2133               int LOffset = getMemoryOpOffset(*LHS);
2134               int ROffset = getMemoryOpOffset(*RHS);
2135               assert(LHS == RHS || LOffset != ROffset);
2136               return LOffset > ROffset;
2137             });
2138 
2139   // The loads / stores of the same base are in order. Scan them from first to
2140   // last and check for the following:
2141   // 1. Any def of base.
2142   // 2. Any gaps.
2143   while (Ops.size() > 1) {
2144     unsigned FirstLoc = ~0U;
2145     unsigned LastLoc = 0;
2146     MachineInstr *FirstOp = nullptr;
2147     MachineInstr *LastOp = nullptr;
2148     int LastOffset = 0;
2149     unsigned LastOpcode = 0;
2150     unsigned LastBytes = 0;
2151     unsigned NumMove = 0;
2152     for (int i = Ops.size() - 1; i >= 0; --i) {
2153       MachineInstr *Op = Ops[i];
2154       unsigned Loc = MI2LocMap[Op];
2155       if (Loc <= FirstLoc) {
2156         FirstLoc = Loc;
2157         FirstOp = Op;
2158       }
2159       if (Loc >= LastLoc) {
2160         LastLoc = Loc;
2161         LastOp = Op;
2162       }
2163 
2164       unsigned LSMOpcode
2165         = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2166       if (LastOpcode && LSMOpcode != LastOpcode)
2167         break;
2168 
2169       int Offset = getMemoryOpOffset(*Op);
2170       unsigned Bytes = getLSMultipleTransferSize(Op);
2171       if (LastBytes) {
2172         if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2173           break;
2174       }
2175       LastOffset = Offset;
2176       LastBytes = Bytes;
2177       LastOpcode = LSMOpcode;
2178       if (++NumMove == 8) // FIXME: Tune this limit.
2179         break;
2180     }
2181 
2182     if (NumMove <= 1)
2183       Ops.pop_back();
2184     else {
2185       SmallPtrSet<MachineInstr*, 4> MemOps;
2186       SmallSet<unsigned, 4> MemRegs;
2187       for (int i = NumMove-1; i >= 0; --i) {
2188         MemOps.insert(Ops[i]);
2189         MemRegs.insert(Ops[i]->getOperand(0).getReg());
2190       }
2191 
2192       // Be conservative, if the instructions are too far apart, don't
2193       // move them. We want to limit the increase of register pressure.
2194       bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2195       if (DoMove)
2196         DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2197                                            MemOps, MemRegs, TRI);
2198       if (!DoMove) {
2199         for (unsigned i = 0; i != NumMove; ++i)
2200           Ops.pop_back();
2201       } else {
2202         // This is the new location for the loads / stores.
2203         MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2204         while (InsertPos != MBB->end() &&
2205                (MemOps.count(&*InsertPos) || InsertPos->isDebugValue()))
2206           ++InsertPos;
2207 
2208         // If we are moving a pair of loads / stores, see if it makes sense
2209         // to try to allocate a pair of registers that can form register pairs.
2210         MachineInstr *Op0 = Ops.back();
2211         MachineInstr *Op1 = Ops[Ops.size()-2];
2212         unsigned FirstReg = 0, SecondReg = 0;
2213         unsigned BaseReg = 0, PredReg = 0;
2214         ARMCC::CondCodes Pred = ARMCC::AL;
2215         bool isT2 = false;
2216         unsigned NewOpc = 0;
2217         int Offset = 0;
2218         DebugLoc dl;
2219         if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2220                                              FirstReg, SecondReg, BaseReg,
2221                                              Offset, PredReg, Pred, isT2)) {
2222           Ops.pop_back();
2223           Ops.pop_back();
2224 
2225           const MCInstrDesc &MCID = TII->get(NewOpc);
2226           const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2227           MRI->constrainRegClass(FirstReg, TRC);
2228           MRI->constrainRegClass(SecondReg, TRC);
2229 
2230           // Form the pair instruction.
2231           if (isLd) {
2232             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2233               .addReg(FirstReg, RegState::Define)
2234               .addReg(SecondReg, RegState::Define)
2235               .addReg(BaseReg);
2236             // FIXME: We're converting from LDRi12 to an insn that still
2237             // uses addrmode2, so we need an explicit offset reg. It should
2238             // always by reg0 since we're transforming LDRi12s.
2239             if (!isT2)
2240               MIB.addReg(0);
2241             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2242             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2243             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2244             ++NumLDRDFormed;
2245           } else {
2246             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2247               .addReg(FirstReg)
2248               .addReg(SecondReg)
2249               .addReg(BaseReg);
2250             // FIXME: We're converting from LDRi12 to an insn that still
2251             // uses addrmode2, so we need an explicit offset reg. It should
2252             // always by reg0 since we're transforming STRi12s.
2253             if (!isT2)
2254               MIB.addReg(0);
2255             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2256             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2257             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2258             ++NumSTRDFormed;
2259           }
2260           MBB->erase(Op0);
2261           MBB->erase(Op1);
2262 
2263           if (!isT2) {
2264             // Add register allocation hints to form register pairs.
2265             MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2266             MRI->setRegAllocationHint(SecondReg,  ARMRI::RegPairOdd, FirstReg);
2267           }
2268         } else {
2269           for (unsigned i = 0; i != NumMove; ++i) {
2270             MachineInstr *Op = Ops.back();
2271             Ops.pop_back();
2272             MBB->splice(InsertPos, MBB, Op);
2273           }
2274         }
2275 
2276         NumLdStMoved += NumMove;
2277         RetVal = true;
2278       }
2279     }
2280   }
2281 
2282   return RetVal;
2283 }
2284 
2285 bool
2286 ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2287   bool RetVal = false;
2288 
2289   DenseMap<MachineInstr*, unsigned> MI2LocMap;
2290   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2291   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2292   SmallVector<unsigned, 4> LdBases;
2293   SmallVector<unsigned, 4> StBases;
2294 
2295   unsigned Loc = 0;
2296   MachineBasicBlock::iterator MBBI = MBB->begin();
2297   MachineBasicBlock::iterator E = MBB->end();
2298   while (MBBI != E) {
2299     for (; MBBI != E; ++MBBI) {
2300       MachineInstr &MI = *MBBI;
2301       if (MI.isCall() || MI.isTerminator()) {
2302         // Stop at barriers.
2303         ++MBBI;
2304         break;
2305       }
2306 
2307       if (!MI.isDebugValue())
2308         MI2LocMap[&MI] = ++Loc;
2309 
2310       if (!isMemoryOp(MI))
2311         continue;
2312       unsigned PredReg = 0;
2313       if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2314         continue;
2315 
2316       int Opc = MI.getOpcode();
2317       bool isLd = isLoadSingle(Opc);
2318       unsigned Base = MI.getOperand(1).getReg();
2319       int Offset = getMemoryOpOffset(MI);
2320 
2321       bool StopHere = false;
2322       if (isLd) {
2323         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2324           Base2LdsMap.find(Base);
2325         if (BI != Base2LdsMap.end()) {
2326           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2327             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2328               StopHere = true;
2329               break;
2330             }
2331           }
2332           if (!StopHere)
2333             BI->second.push_back(&MI);
2334         } else {
2335           Base2LdsMap[Base].push_back(&MI);
2336           LdBases.push_back(Base);
2337         }
2338       } else {
2339         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2340           Base2StsMap.find(Base);
2341         if (BI != Base2StsMap.end()) {
2342           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2343             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2344               StopHere = true;
2345               break;
2346             }
2347           }
2348           if (!StopHere)
2349             BI->second.push_back(&MI);
2350         } else {
2351           Base2StsMap[Base].push_back(&MI);
2352           StBases.push_back(Base);
2353         }
2354       }
2355 
2356       if (StopHere) {
2357         // Found a duplicate (a base+offset combination that's seen earlier).
2358         // Backtrack.
2359         --Loc;
2360         break;
2361       }
2362     }
2363 
2364     // Re-schedule loads.
2365     for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2366       unsigned Base = LdBases[i];
2367       SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2368       if (Lds.size() > 1)
2369         RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2370     }
2371 
2372     // Re-schedule stores.
2373     for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2374       unsigned Base = StBases[i];
2375       SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2376       if (Sts.size() > 1)
2377         RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2378     }
2379 
2380     if (MBBI != E) {
2381       Base2LdsMap.clear();
2382       Base2StsMap.clear();
2383       LdBases.clear();
2384       StBases.clear();
2385     }
2386   }
2387 
2388   return RetVal;
2389 }
2390 
2391 
2392 /// Returns an instance of the load / store optimization pass.
2393 FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2394   if (PreAlloc)
2395     return new ARMPreAllocLoadStoreOpt();
2396   return new ARMLoadStoreOpt();
2397 }
2398