• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 namespace llvm {
73 void initializeARMLoadStoreOptPass(PassRegistry &);
74 }
75 
76 #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
77 
78 namespace {
79   /// Post- register allocation pass the combine load / store instructions to
80   /// form ldm / stm instructions.
81   struct ARMLoadStoreOpt : public MachineFunctionPass {
82     static char ID;
ARMLoadStoreOpt__anonf87ca22c0111::ARMLoadStoreOpt83     ARMLoadStoreOpt() : MachineFunctionPass(ID) {
84       initializeARMLoadStoreOptPass(*PassRegistry::getPassRegistry());
85     }
86 
87     const MachineFunction *MF;
88     const TargetInstrInfo *TII;
89     const TargetRegisterInfo *TRI;
90     const ARMSubtarget *STI;
91     const TargetLowering *TL;
92     ARMFunctionInfo *AFI;
93     LivePhysRegs LiveRegs;
94     RegisterClassInfo RegClassInfo;
95     MachineBasicBlock::const_iterator LiveRegPos;
96     bool LiveRegsValid;
97     bool RegClassInfoValid;
98     bool isThumb1, isThumb2;
99 
100     bool runOnMachineFunction(MachineFunction &Fn) override;
101 
getRequiredProperties__anonf87ca22c0111::ARMLoadStoreOpt102     MachineFunctionProperties getRequiredProperties() const override {
103       return MachineFunctionProperties().set(
104           MachineFunctionProperties::Property::AllVRegsAllocated);
105     }
106 
getPassName__anonf87ca22c0111::ARMLoadStoreOpt107     const char *getPassName() const override {
108       return ARM_LOAD_STORE_OPT_NAME;
109     }
110 
111   private:
112     /// A set of load/store MachineInstrs with same base register sorted by
113     /// offset.
114     struct MemOpQueueEntry {
115       MachineInstr *MI;
116       int Offset;        ///< Load/Store offset.
117       unsigned Position; ///< Position as counted from end of basic block.
MemOpQueueEntry__anonf87ca22c0111::ARMLoadStoreOpt::MemOpQueueEntry118       MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
119           : MI(&MI), Offset(Offset), Position(Position) {}
120     };
121     typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
122 
123     /// A set of MachineInstrs that fulfill (nearly all) conditions to get
124     /// merged into a LDM/STM.
125     struct MergeCandidate {
126       /// List of instructions ordered by load/store offset.
127       SmallVector<MachineInstr*, 4> Instrs;
128       /// Index in Instrs of the instruction being latest in the schedule.
129       unsigned LatestMIIdx;
130       /// Index in Instrs of the instruction being earliest in the schedule.
131       unsigned EarliestMIIdx;
132       /// Index into the basic block where the merged instruction will be
133       /// inserted. (See MemOpQueueEntry.Position)
134       unsigned InsertPos;
135       /// Whether the instructions can be merged into a ldm/stm instruction.
136       bool CanMergeToLSMulti;
137       /// Whether the instructions can be merged into a ldrd/strd instruction.
138       bool CanMergeToLSDouble;
139     };
140     SpecificBumpPtrAllocator<MergeCandidate> Allocator;
141     SmallVector<const MergeCandidate*,4> Candidates;
142     SmallVector<MachineInstr*,4> MergeBaseCandidates;
143 
144     void moveLiveRegsBefore(const MachineBasicBlock &MBB,
145                             MachineBasicBlock::const_iterator Before);
146     unsigned findFreeReg(const TargetRegisterClass &RegClass);
147     void UpdateBaseRegUses(MachineBasicBlock &MBB,
148                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
149                            unsigned Base, unsigned WordOffset,
150                            ARMCC::CondCodes Pred, unsigned PredReg);
151     MachineInstr *CreateLoadStoreMulti(
152         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
153         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
154         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
155         ArrayRef<std::pair<unsigned, bool>> Regs);
156     MachineInstr *CreateLoadStoreDouble(
157         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
158         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
159         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
160         ArrayRef<std::pair<unsigned, bool>> Regs) const;
161     void FormCandidates(const MemOpQueue &MemOps);
162     MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
163     bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
164                              MachineBasicBlock::iterator &MBBI);
165     bool MergeBaseUpdateLoadStore(MachineInstr *MI);
166     bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
167     bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
168     bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
169     bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
170     bool CombineMovBx(MachineBasicBlock &MBB);
171   };
172   char ARMLoadStoreOpt::ID = 0;
173 }
174 
175 INITIALIZE_PASS(ARMLoadStoreOpt, "arm-load-store-opt", ARM_LOAD_STORE_OPT_NAME, false, false)
176 
definesCPSR(const MachineInstr & MI)177 static bool definesCPSR(const MachineInstr &MI) {
178   for (const auto &MO : MI.operands()) {
179     if (!MO.isReg())
180       continue;
181     if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
182       // If the instruction has live CPSR def, then it's not safe to fold it
183       // into load / store.
184       return true;
185   }
186 
187   return false;
188 }
189 
getMemoryOpOffset(const MachineInstr & MI)190 static int getMemoryOpOffset(const MachineInstr &MI) {
191   unsigned Opcode = MI.getOpcode();
192   bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
193   unsigned NumOperands = MI.getDesc().getNumOperands();
194   unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
195 
196   if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
197       Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
198       Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
199       Opcode == ARM::LDRi12   || Opcode == ARM::STRi12)
200     return OffField;
201 
202   // Thumb1 immediate offsets are scaled by 4
203   if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
204       Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
205     return OffField * 4;
206 
207   int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
208     : ARM_AM::getAM5Offset(OffField) * 4;
209   ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
210     : ARM_AM::getAM5Op(OffField);
211 
212   if (Op == ARM_AM::sub)
213     return -Offset;
214 
215   return Offset;
216 }
217 
getLoadStoreBaseOp(const MachineInstr & MI)218 static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
219   return MI.getOperand(1);
220 }
221 
getLoadStoreRegOp(const MachineInstr & MI)222 static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
223   return MI.getOperand(0);
224 }
225 
getLoadStoreMultipleOpcode(unsigned Opcode,ARM_AM::AMSubMode Mode)226 static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
227   switch (Opcode) {
228   default: llvm_unreachable("Unhandled opcode!");
229   case ARM::LDRi12:
230     ++NumLDMGened;
231     switch (Mode) {
232     default: llvm_unreachable("Unhandled submode!");
233     case ARM_AM::ia: return ARM::LDMIA;
234     case ARM_AM::da: return ARM::LDMDA;
235     case ARM_AM::db: return ARM::LDMDB;
236     case ARM_AM::ib: return ARM::LDMIB;
237     }
238   case ARM::STRi12:
239     ++NumSTMGened;
240     switch (Mode) {
241     default: llvm_unreachable("Unhandled submode!");
242     case ARM_AM::ia: return ARM::STMIA;
243     case ARM_AM::da: return ARM::STMDA;
244     case ARM_AM::db: return ARM::STMDB;
245     case ARM_AM::ib: return ARM::STMIB;
246     }
247   case ARM::tLDRi:
248   case ARM::tLDRspi:
249     // tLDMIA is writeback-only - unless the base register is in the input
250     // reglist.
251     ++NumLDMGened;
252     switch (Mode) {
253     default: llvm_unreachable("Unhandled submode!");
254     case ARM_AM::ia: return ARM::tLDMIA;
255     }
256   case ARM::tSTRi:
257   case ARM::tSTRspi:
258     // There is no non-writeback tSTMIA either.
259     ++NumSTMGened;
260     switch (Mode) {
261     default: llvm_unreachable("Unhandled submode!");
262     case ARM_AM::ia: return ARM::tSTMIA_UPD;
263     }
264   case ARM::t2LDRi8:
265   case ARM::t2LDRi12:
266     ++NumLDMGened;
267     switch (Mode) {
268     default: llvm_unreachable("Unhandled submode!");
269     case ARM_AM::ia: return ARM::t2LDMIA;
270     case ARM_AM::db: return ARM::t2LDMDB;
271     }
272   case ARM::t2STRi8:
273   case ARM::t2STRi12:
274     ++NumSTMGened;
275     switch (Mode) {
276     default: llvm_unreachable("Unhandled submode!");
277     case ARM_AM::ia: return ARM::t2STMIA;
278     case ARM_AM::db: return ARM::t2STMDB;
279     }
280   case ARM::VLDRS:
281     ++NumVLDMGened;
282     switch (Mode) {
283     default: llvm_unreachable("Unhandled submode!");
284     case ARM_AM::ia: return ARM::VLDMSIA;
285     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
286     }
287   case ARM::VSTRS:
288     ++NumVSTMGened;
289     switch (Mode) {
290     default: llvm_unreachable("Unhandled submode!");
291     case ARM_AM::ia: return ARM::VSTMSIA;
292     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
293     }
294   case ARM::VLDRD:
295     ++NumVLDMGened;
296     switch (Mode) {
297     default: llvm_unreachable("Unhandled submode!");
298     case ARM_AM::ia: return ARM::VLDMDIA;
299     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
300     }
301   case ARM::VSTRD:
302     ++NumVSTMGened;
303     switch (Mode) {
304     default: llvm_unreachable("Unhandled submode!");
305     case ARM_AM::ia: return ARM::VSTMDIA;
306     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
307     }
308   }
309 }
310 
getLoadStoreMultipleSubMode(unsigned Opcode)311 static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
312   switch (Opcode) {
313   default: llvm_unreachable("Unhandled opcode!");
314   case ARM::LDMIA_RET:
315   case ARM::LDMIA:
316   case ARM::LDMIA_UPD:
317   case ARM::STMIA:
318   case ARM::STMIA_UPD:
319   case ARM::tLDMIA:
320   case ARM::tLDMIA_UPD:
321   case ARM::tSTMIA_UPD:
322   case ARM::t2LDMIA_RET:
323   case ARM::t2LDMIA:
324   case ARM::t2LDMIA_UPD:
325   case ARM::t2STMIA:
326   case ARM::t2STMIA_UPD:
327   case ARM::VLDMSIA:
328   case ARM::VLDMSIA_UPD:
329   case ARM::VSTMSIA:
330   case ARM::VSTMSIA_UPD:
331   case ARM::VLDMDIA:
332   case ARM::VLDMDIA_UPD:
333   case ARM::VSTMDIA:
334   case ARM::VSTMDIA_UPD:
335     return ARM_AM::ia;
336 
337   case ARM::LDMDA:
338   case ARM::LDMDA_UPD:
339   case ARM::STMDA:
340   case ARM::STMDA_UPD:
341     return ARM_AM::da;
342 
343   case ARM::LDMDB:
344   case ARM::LDMDB_UPD:
345   case ARM::STMDB:
346   case ARM::STMDB_UPD:
347   case ARM::t2LDMDB:
348   case ARM::t2LDMDB_UPD:
349   case ARM::t2STMDB:
350   case ARM::t2STMDB_UPD:
351   case ARM::VLDMSDB_UPD:
352   case ARM::VSTMSDB_UPD:
353   case ARM::VLDMDDB_UPD:
354   case ARM::VSTMDDB_UPD:
355     return ARM_AM::db;
356 
357   case ARM::LDMIB:
358   case ARM::LDMIB_UPD:
359   case ARM::STMIB:
360   case ARM::STMIB_UPD:
361     return ARM_AM::ib;
362   }
363 }
364 
isT1i32Load(unsigned Opc)365 static bool isT1i32Load(unsigned Opc) {
366   return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
367 }
368 
isT2i32Load(unsigned Opc)369 static bool isT2i32Load(unsigned Opc) {
370   return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
371 }
372 
isi32Load(unsigned Opc)373 static bool isi32Load(unsigned Opc) {
374   return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
375 }
376 
isT1i32Store(unsigned Opc)377 static bool isT1i32Store(unsigned Opc) {
378   return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
379 }
380 
isT2i32Store(unsigned Opc)381 static bool isT2i32Store(unsigned Opc) {
382   return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
383 }
384 
isi32Store(unsigned Opc)385 static bool isi32Store(unsigned Opc) {
386   return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
387 }
388 
isLoadSingle(unsigned Opc)389 static bool isLoadSingle(unsigned Opc) {
390   return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
391 }
392 
getImmScale(unsigned Opc)393 static unsigned getImmScale(unsigned Opc) {
394   switch (Opc) {
395   default: llvm_unreachable("Unhandled opcode!");
396   case ARM::tLDRi:
397   case ARM::tSTRi:
398   case ARM::tLDRspi:
399   case ARM::tSTRspi:
400     return 1;
401   case ARM::tLDRHi:
402   case ARM::tSTRHi:
403     return 2;
404   case ARM::tLDRBi:
405   case ARM::tSTRBi:
406     return 4;
407   }
408 }
409 
getLSMultipleTransferSize(const MachineInstr * MI)410 static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
411   switch (MI->getOpcode()) {
412   default: return 0;
413   case ARM::LDRi12:
414   case ARM::STRi12:
415   case ARM::tLDRi:
416   case ARM::tSTRi:
417   case ARM::tLDRspi:
418   case ARM::tSTRspi:
419   case ARM::t2LDRi8:
420   case ARM::t2LDRi12:
421   case ARM::t2STRi8:
422   case ARM::t2STRi12:
423   case ARM::VLDRS:
424   case ARM::VSTRS:
425     return 4;
426   case ARM::VLDRD:
427   case ARM::VSTRD:
428     return 8;
429   case ARM::LDMIA:
430   case ARM::LDMDA:
431   case ARM::LDMDB:
432   case ARM::LDMIB:
433   case ARM::STMIA:
434   case ARM::STMDA:
435   case ARM::STMDB:
436   case ARM::STMIB:
437   case ARM::tLDMIA:
438   case ARM::tLDMIA_UPD:
439   case ARM::tSTMIA_UPD:
440   case ARM::t2LDMIA:
441   case ARM::t2LDMDB:
442   case ARM::t2STMIA:
443   case ARM::t2STMDB:
444   case ARM::VLDMSIA:
445   case ARM::VSTMSIA:
446     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
447   case ARM::VLDMDIA:
448   case ARM::VSTMDIA:
449     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
450   }
451 }
452 
453 /// Update future uses of the base register with the offset introduced
454 /// due to writeback. This function only works on Thumb1.
UpdateBaseRegUses(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,unsigned Base,unsigned WordOffset,ARMCC::CondCodes Pred,unsigned PredReg)455 void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
456                                         MachineBasicBlock::iterator MBBI,
457                                         const DebugLoc &DL, unsigned Base,
458                                         unsigned WordOffset,
459                                         ARMCC::CondCodes Pred,
460                                         unsigned PredReg) {
461   assert(isThumb1 && "Can only update base register uses for Thumb1!");
462   // Start updating any instructions with immediate offsets. Insert a SUB before
463   // the first non-updateable instruction (if any).
464   for (; MBBI != MBB.end(); ++MBBI) {
465     bool InsertSub = false;
466     unsigned Opc = MBBI->getOpcode();
467 
468     if (MBBI->readsRegister(Base)) {
469       int Offset;
470       bool IsLoad =
471         Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
472       bool IsStore =
473         Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
474 
475       if (IsLoad || IsStore) {
476         // Loads and stores with immediate offsets can be updated, but only if
477         // the new offset isn't negative.
478         // The MachineOperand containing the offset immediate is the last one
479         // before predicates.
480         MachineOperand &MO =
481           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
482         // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
483         Offset = MO.getImm() - WordOffset * getImmScale(Opc);
484 
485         // If storing the base register, it needs to be reset first.
486         unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
487 
488         if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
489           MO.setImm(Offset);
490         else
491           InsertSub = true;
492 
493       } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
494                  !definesCPSR(*MBBI)) {
495         // SUBS/ADDS using this register, with a dead def of the CPSR.
496         // Merge it with the update; if the merged offset is too large,
497         // insert a new sub instead.
498         MachineOperand &MO =
499           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
500         Offset = (Opc == ARM::tSUBi8) ?
501           MO.getImm() + WordOffset * 4 :
502           MO.getImm() - WordOffset * 4 ;
503         if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
504           // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
505           // Offset == 0.
506           MO.setImm(Offset);
507           // The base register has now been reset, so exit early.
508           return;
509         } else {
510           InsertSub = true;
511         }
512 
513       } else {
514         // Can't update the instruction.
515         InsertSub = true;
516       }
517 
518     } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
519       // Since SUBS sets the condition flags, we can't place the base reset
520       // after an instruction that has a live CPSR def.
521       // The base register might also contain an argument for a function call.
522       InsertSub = true;
523     }
524 
525     if (InsertSub) {
526       // An instruction above couldn't be updated, so insert a sub.
527       AddDefaultT1CC(BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
528         .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
529       return;
530     }
531 
532     if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
533       // Register got killed. Stop updating.
534       return;
535   }
536 
537   // End of block was reached.
538   if (MBB.succ_size() > 0) {
539     // FIXME: Because of a bug, live registers are sometimes missing from
540     // the successor blocks' live-in sets. This means we can't trust that
541     // information and *always* have to reset at the end of a block.
542     // See PR21029.
543     if (MBBI != MBB.end()) --MBBI;
544     AddDefaultT1CC(
545       BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
546       .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
547   }
548 }
549 
550 /// Return the first register of class \p RegClass that is not in \p Regs.
findFreeReg(const TargetRegisterClass & RegClass)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.
moveLiveRegsBefore(const MachineBasicBlock & MBB,MachineBasicBlock::const_iterator Before)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 
ContainsReg(const ArrayRef<std::pair<unsigned,bool>> & Regs,unsigned Reg)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.
CreateLoadStoreMulti(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,int Offset,unsigned Base,bool BaseKill,unsigned Opcode,ARMCC::CondCodes Pred,unsigned PredReg,const DebugLoc & DL,ArrayRef<std::pair<unsigned,bool>> Regs)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         AddDefaultT1CC(
724           BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase), true)
725           .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
726           .addImm(Pred).addReg(PredReg);
727     } else {
728       BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
729         .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
730         .addImm(Pred).addReg(PredReg).addReg(0);
731     }
732     Base = NewBase;
733     BaseKill = true; // New base is always killed straight away.
734   }
735 
736   bool isDef = isLoadSingle(Opcode);
737 
738   // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
739   // base register writeback.
740   Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
741   if (!Opcode)
742     return nullptr;
743 
744   // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
745   // - There is no writeback (LDM of base register),
746   // - the base register is killed by the merged instruction,
747   // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
748   //   to reset the base register.
749   // Otherwise, don't merge.
750   // It's safe to return here since the code to materialize a new base register
751   // above is also conditional on SafeToClobberCPSR.
752   if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
753     return nullptr;
754 
755   MachineInstrBuilder MIB;
756 
757   if (Writeback) {
758     assert(isThumb1 && "expected Writeback only inThumb1");
759     if (Opcode == ARM::tLDMIA) {
760       assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
761       // Update tLDMIA with writeback if necessary.
762       Opcode = ARM::tLDMIA_UPD;
763     }
764 
765     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
766 
767     // Thumb1: we might need to set base writeback when building the MI.
768     MIB.addReg(Base, getDefRegState(true))
769        .addReg(Base, getKillRegState(BaseKill));
770 
771     // The base isn't dead after a merged instruction with writeback.
772     // Insert a sub instruction after the newly formed instruction to reset.
773     if (!BaseKill)
774       UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
775 
776   } else {
777     // No writeback, simply build the MachineInstr.
778     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
779     MIB.addReg(Base, getKillRegState(BaseKill));
780   }
781 
782   MIB.addImm(Pred).addReg(PredReg);
783 
784   for (const std::pair<unsigned, bool> &R : Regs)
785     MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
786 
787   return MIB.getInstr();
788 }
789 
CreateLoadStoreDouble(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,int Offset,unsigned Base,bool BaseKill,unsigned Opcode,ARMCC::CondCodes Pred,unsigned PredReg,const DebugLoc & DL,ArrayRef<std::pair<unsigned,bool>> Regs) const790 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
791     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
792     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
793     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
794     ArrayRef<std::pair<unsigned, bool>> Regs) const {
795   bool IsLoad = isi32Load(Opcode);
796   assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
797   unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
798 
799   assert(Regs.size() == 2);
800   MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
801                                     TII->get(LoadStoreOpcode));
802   if (IsLoad) {
803     MIB.addReg(Regs[0].first, RegState::Define)
804        .addReg(Regs[1].first, RegState::Define);
805   } else {
806     MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
807        .addReg(Regs[1].first, getKillRegState(Regs[1].second));
808   }
809   MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
810   return MIB.getInstr();
811 }
812 
813 /// Call MergeOps and update MemOps and merges accordingly on success.
MergeOpsUpdate(const MergeCandidate & Cand)814 MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
815   const MachineInstr *First = Cand.Instrs.front();
816   unsigned Opcode = First->getOpcode();
817   bool IsLoad = isLoadSingle(Opcode);
818   SmallVector<std::pair<unsigned, bool>, 8> Regs;
819   SmallVector<unsigned, 4> ImpDefs;
820   DenseSet<unsigned> KilledRegs;
821   DenseSet<unsigned> UsedRegs;
822   // Determine list of registers and list of implicit super-register defs.
823   for (const MachineInstr *MI : Cand.Instrs) {
824     const MachineOperand &MO = getLoadStoreRegOp(*MI);
825     unsigned Reg = MO.getReg();
826     bool IsKill = MO.isKill();
827     if (IsKill)
828       KilledRegs.insert(Reg);
829     Regs.push_back(std::make_pair(Reg, IsKill));
830     UsedRegs.insert(Reg);
831 
832     if (IsLoad) {
833       // Collect any implicit defs of super-registers, after merging we can't
834       // be sure anymore that we properly preserved these live ranges and must
835       // removed these implicit operands.
836       for (const MachineOperand &MO : MI->implicit_operands()) {
837         if (!MO.isReg() || !MO.isDef() || MO.isDead())
838           continue;
839         assert(MO.isImplicit());
840         unsigned DefReg = MO.getReg();
841 
842         if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) != ImpDefs.end())
843           continue;
844         // We can ignore cases where the super-reg is read and written.
845         if (MI->readsRegister(DefReg))
846           continue;
847         ImpDefs.push_back(DefReg);
848       }
849     }
850   }
851 
852   // Attempt the merge.
853   typedef MachineBasicBlock::iterator iterator;
854   MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
855   iterator InsertBefore = std::next(iterator(LatestMI));
856   MachineBasicBlock &MBB = *LatestMI->getParent();
857   unsigned Offset = getMemoryOpOffset(*First);
858   unsigned Base = getLoadStoreBaseOp(*First).getReg();
859   bool BaseKill = LatestMI->killsRegister(Base);
860   unsigned PredReg = 0;
861   ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
862   DebugLoc DL = First->getDebugLoc();
863   MachineInstr *Merged = nullptr;
864   if (Cand.CanMergeToLSDouble)
865     Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
866                                    Opcode, Pred, PredReg, DL, Regs);
867   if (!Merged && Cand.CanMergeToLSMulti)
868     Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
869                                   Opcode, Pred, PredReg, DL, Regs);
870   if (!Merged)
871     return nullptr;
872 
873   // Determine earliest instruction that will get removed. We then keep an
874   // iterator just above it so the following erases don't invalidated it.
875   iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
876   bool EarliestAtBegin = false;
877   if (EarliestI == MBB.begin()) {
878     EarliestAtBegin = true;
879   } else {
880     EarliestI = std::prev(EarliestI);
881   }
882 
883   // Remove instructions which have been merged.
884   for (MachineInstr *MI : Cand.Instrs)
885     MBB.erase(MI);
886 
887   // Determine range between the earliest removed instruction and the new one.
888   if (EarliestAtBegin)
889     EarliestI = MBB.begin();
890   else
891     EarliestI = std::next(EarliestI);
892   auto FixupRange = make_range(EarliestI, iterator(Merged));
893 
894   if (isLoadSingle(Opcode)) {
895     // If the previous loads defined a super-reg, then we have to mark earlier
896     // operands undef; Replicate the super-reg def on the merged instruction.
897     for (MachineInstr &MI : FixupRange) {
898       for (unsigned &ImpDefReg : ImpDefs) {
899         for (MachineOperand &MO : MI.implicit_operands()) {
900           if (!MO.isReg() || MO.getReg() != ImpDefReg)
901             continue;
902           if (MO.readsReg())
903             MO.setIsUndef();
904           else if (MO.isDef())
905             ImpDefReg = 0;
906         }
907       }
908     }
909 
910     MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
911     for (unsigned ImpDef : ImpDefs)
912       MIB.addReg(ImpDef, RegState::ImplicitDefine);
913   } else {
914     // Remove kill flags: We are possibly storing the values later now.
915     assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
916     for (MachineInstr &MI : FixupRange) {
917       for (MachineOperand &MO : MI.uses()) {
918         if (!MO.isReg() || !MO.isKill())
919           continue;
920         if (UsedRegs.count(MO.getReg()))
921           MO.setIsKill(false);
922       }
923     }
924     assert(ImpDefs.empty());
925   }
926 
927   return Merged;
928 }
929 
isValidLSDoubleOffset(int Offset)930 static bool isValidLSDoubleOffset(int Offset) {
931   unsigned Value = abs(Offset);
932   // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
933   // multiplied by 4.
934   return (Value % 4) == 0 && Value < 1024;
935 }
936 
937 /// Return true for loads/stores that can be combined to a double/multi
938 /// operation without increasing the requirements for alignment.
mayCombineMisaligned(const TargetSubtargetInfo & STI,const MachineInstr & MI)939 static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
940                                  const MachineInstr &MI) {
941   // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
942   // difference.
943   unsigned Opcode = MI.getOpcode();
944   if (!isi32Load(Opcode) && !isi32Store(Opcode))
945     return true;
946 
947   // Stack pointer alignment is out of the programmers control so we can trust
948   // SP-relative loads/stores.
949   if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
950       STI.getFrameLowering()->getTransientStackAlignment() >= 4)
951     return true;
952   return false;
953 }
954 
955 /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
FormCandidates(const MemOpQueue & MemOps)956 void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
957   const MachineInstr *FirstMI = MemOps[0].MI;
958   unsigned Opcode = FirstMI->getOpcode();
959   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
960   unsigned Size = getLSMultipleTransferSize(FirstMI);
961 
962   unsigned SIndex = 0;
963   unsigned EIndex = MemOps.size();
964   do {
965     // Look at the first instruction.
966     const MachineInstr *MI = MemOps[SIndex].MI;
967     int Offset = MemOps[SIndex].Offset;
968     const MachineOperand &PMO = getLoadStoreRegOp(*MI);
969     unsigned PReg = PMO.getReg();
970     unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
971     unsigned Latest = SIndex;
972     unsigned Earliest = SIndex;
973     unsigned Count = 1;
974     bool CanMergeToLSDouble =
975       STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
976     // ARM errata 602117: LDRD with base in list may result in incorrect base
977     // register when interrupted or faulted.
978     if (STI->isCortexM3() && isi32Load(Opcode) &&
979         PReg == getLoadStoreBaseOp(*MI).getReg())
980       CanMergeToLSDouble = false;
981 
982     bool CanMergeToLSMulti = true;
983     // On swift vldm/vstm starting with an odd register number as that needs
984     // more uops than single vldrs.
985     if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
986       CanMergeToLSMulti = false;
987 
988     // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
989     // deprecated; LDM to PC is fine but cannot happen here.
990     if (PReg == ARM::SP || PReg == ARM::PC)
991       CanMergeToLSMulti = CanMergeToLSDouble = false;
992 
993     // Should we be conservative?
994     if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
995       CanMergeToLSMulti = CanMergeToLSDouble = false;
996 
997     // Merge following instructions where possible.
998     for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
999       int NewOffset = MemOps[I].Offset;
1000       if (NewOffset != Offset + (int)Size)
1001         break;
1002       const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1003       unsigned Reg = MO.getReg();
1004       if (Reg == ARM::SP || Reg == ARM::PC)
1005         break;
1006 
1007       // See if the current load/store may be part of a multi load/store.
1008       unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
1009       bool PartOfLSMulti = CanMergeToLSMulti;
1010       if (PartOfLSMulti) {
1011         // Register numbers must be in ascending order.
1012         if (RegNum <= PRegNum)
1013           PartOfLSMulti = false;
1014         // For VFP / NEON load/store multiples, the registers must be
1015         // consecutive and within the limit on the number of registers per
1016         // instruction.
1017         else if (!isNotVFP && RegNum != PRegNum+1)
1018           PartOfLSMulti = false;
1019       }
1020       // See if the current load/store may be part of a double load/store.
1021       bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1022 
1023       if (!PartOfLSMulti && !PartOfLSDouble)
1024         break;
1025       CanMergeToLSMulti &= PartOfLSMulti;
1026       CanMergeToLSDouble &= PartOfLSDouble;
1027       // Track MemOp with latest and earliest position (Positions are
1028       // counted in reverse).
1029       unsigned Position = MemOps[I].Position;
1030       if (Position < MemOps[Latest].Position)
1031         Latest = I;
1032       else if (Position > MemOps[Earliest].Position)
1033         Earliest = I;
1034       // Prepare for next MemOp.
1035       Offset += Size;
1036       PRegNum = RegNum;
1037     }
1038 
1039     // Form a candidate from the Ops collected so far.
1040     MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1041     for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1042       Candidate->Instrs.push_back(MemOps[C].MI);
1043     Candidate->LatestMIIdx = Latest - SIndex;
1044     Candidate->EarliestMIIdx = Earliest - SIndex;
1045     Candidate->InsertPos = MemOps[Latest].Position;
1046     if (Count == 1)
1047       CanMergeToLSMulti = CanMergeToLSDouble = false;
1048     Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1049     Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1050     Candidates.push_back(Candidate);
1051     // Continue after the chain.
1052     SIndex += Count;
1053   } while (SIndex < EIndex);
1054 }
1055 
getUpdatingLSMultipleOpcode(unsigned Opc,ARM_AM::AMSubMode Mode)1056 static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1057                                             ARM_AM::AMSubMode Mode) {
1058   switch (Opc) {
1059   default: llvm_unreachable("Unhandled opcode!");
1060   case ARM::LDMIA:
1061   case ARM::LDMDA:
1062   case ARM::LDMDB:
1063   case ARM::LDMIB:
1064     switch (Mode) {
1065     default: llvm_unreachable("Unhandled submode!");
1066     case ARM_AM::ia: return ARM::LDMIA_UPD;
1067     case ARM_AM::ib: return ARM::LDMIB_UPD;
1068     case ARM_AM::da: return ARM::LDMDA_UPD;
1069     case ARM_AM::db: return ARM::LDMDB_UPD;
1070     }
1071   case ARM::STMIA:
1072   case ARM::STMDA:
1073   case ARM::STMDB:
1074   case ARM::STMIB:
1075     switch (Mode) {
1076     default: llvm_unreachable("Unhandled submode!");
1077     case ARM_AM::ia: return ARM::STMIA_UPD;
1078     case ARM_AM::ib: return ARM::STMIB_UPD;
1079     case ARM_AM::da: return ARM::STMDA_UPD;
1080     case ARM_AM::db: return ARM::STMDB_UPD;
1081     }
1082   case ARM::t2LDMIA:
1083   case ARM::t2LDMDB:
1084     switch (Mode) {
1085     default: llvm_unreachable("Unhandled submode!");
1086     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1087     case ARM_AM::db: return ARM::t2LDMDB_UPD;
1088     }
1089   case ARM::t2STMIA:
1090   case ARM::t2STMDB:
1091     switch (Mode) {
1092     default: llvm_unreachable("Unhandled submode!");
1093     case ARM_AM::ia: return ARM::t2STMIA_UPD;
1094     case ARM_AM::db: return ARM::t2STMDB_UPD;
1095     }
1096   case ARM::VLDMSIA:
1097     switch (Mode) {
1098     default: llvm_unreachable("Unhandled submode!");
1099     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1100     case ARM_AM::db: return ARM::VLDMSDB_UPD;
1101     }
1102   case ARM::VLDMDIA:
1103     switch (Mode) {
1104     default: llvm_unreachable("Unhandled submode!");
1105     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1106     case ARM_AM::db: return ARM::VLDMDDB_UPD;
1107     }
1108   case ARM::VSTMSIA:
1109     switch (Mode) {
1110     default: llvm_unreachable("Unhandled submode!");
1111     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1112     case ARM_AM::db: return ARM::VSTMSDB_UPD;
1113     }
1114   case ARM::VSTMDIA:
1115     switch (Mode) {
1116     default: llvm_unreachable("Unhandled submode!");
1117     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1118     case ARM_AM::db: return ARM::VSTMDDB_UPD;
1119     }
1120   }
1121 }
1122 
1123 /// Check if the given instruction increments or decrements a register and
1124 /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1125 /// generated by the instruction are possibly read as well.
isIncrementOrDecrement(const MachineInstr & MI,unsigned Reg,ARMCC::CondCodes Pred,unsigned PredReg)1126 static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
1127                                   ARMCC::CondCodes Pred, unsigned PredReg) {
1128   bool CheckCPSRDef;
1129   int Scale;
1130   switch (MI.getOpcode()) {
1131   case ARM::tADDi8:  Scale =  4; CheckCPSRDef = true; break;
1132   case ARM::tSUBi8:  Scale = -4; CheckCPSRDef = true; break;
1133   case ARM::t2SUBri:
1134   case ARM::SUBri:   Scale = -1; CheckCPSRDef = true; break;
1135   case ARM::t2ADDri:
1136   case ARM::ADDri:   Scale =  1; CheckCPSRDef = true; break;
1137   case ARM::tADDspi: Scale =  4; CheckCPSRDef = false; break;
1138   case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1139   default: return 0;
1140   }
1141 
1142   unsigned MIPredReg;
1143   if (MI.getOperand(0).getReg() != Reg ||
1144       MI.getOperand(1).getReg() != Reg ||
1145       getInstrPredicate(MI, MIPredReg) != Pred ||
1146       MIPredReg != PredReg)
1147     return 0;
1148 
1149   if (CheckCPSRDef && definesCPSR(MI))
1150     return 0;
1151   return MI.getOperand(2).getImm() * Scale;
1152 }
1153 
1154 /// Searches for an increment or decrement of \p Reg before \p MBBI.
1155 static MachineBasicBlock::iterator
findIncDecBefore(MachineBasicBlock::iterator MBBI,unsigned Reg,ARMCC::CondCodes Pred,unsigned PredReg,int & Offset)1156 findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
1157                  ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1158   Offset = 0;
1159   MachineBasicBlock &MBB = *MBBI->getParent();
1160   MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1161   MachineBasicBlock::iterator EndMBBI = MBB.end();
1162   if (MBBI == BeginMBBI)
1163     return EndMBBI;
1164 
1165   // Skip debug values.
1166   MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1167   while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
1168     --PrevMBBI;
1169 
1170   Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1171   return Offset == 0 ? EndMBBI : PrevMBBI;
1172 }
1173 
1174 /// Searches for a increment or decrement of \p Reg after \p MBBI.
1175 static MachineBasicBlock::iterator
findIncDecAfter(MachineBasicBlock::iterator MBBI,unsigned Reg,ARMCC::CondCodes Pred,unsigned PredReg,int & Offset)1176 findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
1177                 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1178   Offset = 0;
1179   MachineBasicBlock &MBB = *MBBI->getParent();
1180   MachineBasicBlock::iterator EndMBBI = MBB.end();
1181   MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1182   // Skip debug values.
1183   while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1184     ++NextMBBI;
1185   if (NextMBBI == EndMBBI)
1186     return EndMBBI;
1187 
1188   Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1189   return Offset == 0 ? EndMBBI : NextMBBI;
1190 }
1191 
1192 /// Fold proceeding/trailing inc/dec of base register into the
1193 /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1194 ///
1195 /// stmia rn, <ra, rb, rc>
1196 /// rn := rn + 4 * 3;
1197 /// =>
1198 /// stmia rn!, <ra, rb, rc>
1199 ///
1200 /// rn := rn - 4 * 3;
1201 /// ldmia rn, <ra, rb, rc>
1202 /// =>
1203 /// ldmdb rn!, <ra, rb, rc>
MergeBaseUpdateLSMultiple(MachineInstr * MI)1204 bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1205   // Thumb1 is already using updating loads/stores.
1206   if (isThumb1) return false;
1207 
1208   const MachineOperand &BaseOP = MI->getOperand(0);
1209   unsigned Base = BaseOP.getReg();
1210   bool BaseKill = BaseOP.isKill();
1211   unsigned PredReg = 0;
1212   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1213   unsigned Opcode = MI->getOpcode();
1214   DebugLoc DL = MI->getDebugLoc();
1215 
1216   // Can't use an updating ld/st if the base register is also a dest
1217   // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1218   for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1219     if (MI->getOperand(i).getReg() == Base)
1220       return false;
1221 
1222   int Bytes = getLSMultipleTransferSize(MI);
1223   MachineBasicBlock &MBB = *MI->getParent();
1224   MachineBasicBlock::iterator MBBI(MI);
1225   int Offset;
1226   MachineBasicBlock::iterator MergeInstr
1227     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1228   ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1229   if (Mode == ARM_AM::ia && Offset == -Bytes) {
1230     Mode = ARM_AM::db;
1231   } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1232     Mode = ARM_AM::da;
1233   } else {
1234     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1235     if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1236         ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1237 
1238       // We couldn't find an inc/dec to merge. But if the base is dead, we
1239       // can still change to a writeback form as that will save us 2 bytes
1240       // of code size. It can create WAW hazards though, so only do it if
1241       // we're minimizing code size.
1242       if (!MBB.getParent()->getFunction()->optForMinSize() || !BaseKill)
1243         return false;
1244 
1245       bool HighRegsUsed = false;
1246       for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1247         if (MI->getOperand(i).getReg() >= ARM::R8) {
1248           HighRegsUsed = true;
1249           break;
1250         }
1251 
1252       if (!HighRegsUsed)
1253         MergeInstr = MBB.end();
1254       else
1255         return false;
1256     }
1257   }
1258   if (MergeInstr != MBB.end())
1259     MBB.erase(MergeInstr);
1260 
1261   unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1262   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1263     .addReg(Base, getDefRegState(true)) // WB base register
1264     .addReg(Base, getKillRegState(BaseKill))
1265     .addImm(Pred).addReg(PredReg);
1266 
1267   // Transfer the rest of operands.
1268   for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
1269     MIB.addOperand(MI->getOperand(OpNum));
1270 
1271   // Transfer memoperands.
1272   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1273 
1274   MBB.erase(MBBI);
1275   return true;
1276 }
1277 
getPreIndexedLoadStoreOpcode(unsigned Opc,ARM_AM::AddrOpc Mode)1278 static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1279                                              ARM_AM::AddrOpc Mode) {
1280   switch (Opc) {
1281   case ARM::LDRi12:
1282     return ARM::LDR_PRE_IMM;
1283   case ARM::STRi12:
1284     return ARM::STR_PRE_IMM;
1285   case ARM::VLDRS:
1286     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1287   case ARM::VLDRD:
1288     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1289   case ARM::VSTRS:
1290     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1291   case ARM::VSTRD:
1292     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1293   case ARM::t2LDRi8:
1294   case ARM::t2LDRi12:
1295     return ARM::t2LDR_PRE;
1296   case ARM::t2STRi8:
1297   case ARM::t2STRi12:
1298     return ARM::t2STR_PRE;
1299   default: llvm_unreachable("Unhandled opcode!");
1300   }
1301 }
1302 
getPostIndexedLoadStoreOpcode(unsigned Opc,ARM_AM::AddrOpc Mode)1303 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1304                                               ARM_AM::AddrOpc Mode) {
1305   switch (Opc) {
1306   case ARM::LDRi12:
1307     return ARM::LDR_POST_IMM;
1308   case ARM::STRi12:
1309     return ARM::STR_POST_IMM;
1310   case ARM::VLDRS:
1311     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1312   case ARM::VLDRD:
1313     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1314   case ARM::VSTRS:
1315     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1316   case ARM::VSTRD:
1317     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1318   case ARM::t2LDRi8:
1319   case ARM::t2LDRi12:
1320     return ARM::t2LDR_POST;
1321   case ARM::t2STRi8:
1322   case ARM::t2STRi12:
1323     return ARM::t2STR_POST;
1324   default: llvm_unreachable("Unhandled opcode!");
1325   }
1326 }
1327 
1328 /// Fold proceeding/trailing inc/dec of base register into the
1329 /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
MergeBaseUpdateLoadStore(MachineInstr * MI)1330 bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1331   // Thumb1 doesn't have updating LDR/STR.
1332   // FIXME: Use LDM/STM with single register instead.
1333   if (isThumb1) return false;
1334 
1335   unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1336   bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1337   unsigned Opcode = MI->getOpcode();
1338   DebugLoc DL = MI->getDebugLoc();
1339   bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1340                 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1341   bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1342   if (isi32Load(Opcode) || isi32Store(Opcode))
1343     if (MI->getOperand(2).getImm() != 0)
1344       return false;
1345   if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1346     return false;
1347 
1348   // Can't do the merge if the destination register is the same as the would-be
1349   // writeback register.
1350   if (MI->getOperand(0).getReg() == Base)
1351     return false;
1352 
1353   unsigned PredReg = 0;
1354   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1355   int Bytes = getLSMultipleTransferSize(MI);
1356   MachineBasicBlock &MBB = *MI->getParent();
1357   MachineBasicBlock::iterator MBBI(MI);
1358   int Offset;
1359   MachineBasicBlock::iterator MergeInstr
1360     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1361   unsigned NewOpc;
1362   if (!isAM5 && Offset == Bytes) {
1363     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1364   } else if (Offset == -Bytes) {
1365     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1366   } else {
1367     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1368     if (Offset == Bytes) {
1369       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1370     } else if (!isAM5 && Offset == -Bytes) {
1371       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1372     } else
1373       return false;
1374   }
1375   MBB.erase(MergeInstr);
1376 
1377   ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1378 
1379   bool isLd = isLoadSingle(Opcode);
1380   if (isAM5) {
1381     // VLDM[SD]_UPD, VSTM[SD]_UPD
1382     // (There are no base-updating versions of VLDR/VSTR instructions, but the
1383     // updating load/store-multiple instructions can be used with only one
1384     // register.)
1385     MachineOperand &MO = MI->getOperand(0);
1386     BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1387       .addReg(Base, getDefRegState(true)) // WB base register
1388       .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1389       .addImm(Pred).addReg(PredReg)
1390       .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1391                             getKillRegState(MO.isKill())));
1392   } else if (isLd) {
1393     if (isAM2) {
1394       // LDR_PRE, LDR_POST
1395       if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1396         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1397           .addReg(Base, RegState::Define)
1398           .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1399       } else {
1400         int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1401         BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1402           .addReg(Base, RegState::Define)
1403           .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
1404       }
1405     } else {
1406       // t2LDR_PRE, t2LDR_POST
1407       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1408         .addReg(Base, RegState::Define)
1409         .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1410     }
1411   } else {
1412     MachineOperand &MO = MI->getOperand(0);
1413     // FIXME: post-indexed stores use am2offset_imm, which still encodes
1414     // the vestigal zero-reg offset register. When that's fixed, this clause
1415     // can be removed entirely.
1416     if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1417       int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1418       // STR_PRE, STR_POST
1419       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1420         .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1421         .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
1422     } else {
1423       // t2STR_PRE, t2STR_POST
1424       BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1425         .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1426         .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1427     }
1428   }
1429   MBB.erase(MBBI);
1430 
1431   return true;
1432 }
1433 
MergeBaseUpdateLSDouble(MachineInstr & MI) const1434 bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1435   unsigned Opcode = MI.getOpcode();
1436   assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1437          "Must have t2STRDi8 or t2LDRDi8");
1438   if (MI.getOperand(3).getImm() != 0)
1439     return false;
1440 
1441   // Behaviour for writeback is undefined if base register is the same as one
1442   // of the others.
1443   const MachineOperand &BaseOp = MI.getOperand(2);
1444   unsigned Base = BaseOp.getReg();
1445   const MachineOperand &Reg0Op = MI.getOperand(0);
1446   const MachineOperand &Reg1Op = MI.getOperand(1);
1447   if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1448     return false;
1449 
1450   unsigned PredReg;
1451   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1452   MachineBasicBlock::iterator MBBI(MI);
1453   MachineBasicBlock &MBB = *MI.getParent();
1454   int Offset;
1455   MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1456                                                             PredReg, Offset);
1457   unsigned NewOpc;
1458   if (Offset == 8 || Offset == -8) {
1459     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1460   } else {
1461     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1462     if (Offset == 8 || Offset == -8) {
1463       NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1464     } else
1465       return false;
1466   }
1467   MBB.erase(MergeInstr);
1468 
1469   DebugLoc DL = MI.getDebugLoc();
1470   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1471   if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1472     MIB.addOperand(Reg0Op).addOperand(Reg1Op)
1473        .addReg(BaseOp.getReg(), RegState::Define);
1474   } else {
1475     assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1476     MIB.addReg(BaseOp.getReg(), RegState::Define)
1477        .addOperand(Reg0Op).addOperand(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.addOperand(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.
isMemoryOp(const MachineInstr & MI)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 
InsertLDR_STR(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,int Offset,bool isDef,const DebugLoc & DL,unsigned NewOpc,unsigned Reg,bool RegDeadKill,bool RegUndef,unsigned BaseReg,bool BaseKill,bool BaseUndef,bool OffKill,bool OffUndef,ARMCC::CondCodes Pred,unsigned PredReg,const TargetInstrInfo * TII,bool isT2)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 
FixInvalidRegPairOp(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI)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.
LoadStoreMultipleOpti(MachineBasicBlock & MBB)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}
MergeReturnIntoLDM(MachineBasicBlock & MBB)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() &&
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 
CombineMovBx(MachineBasicBlock & MBB)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       AddDefaultPred(BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
1902                          .addReg(Use.getReg(), RegState::Kill))
1903           .copyImplicitOps(*MBBI);
1904       MBB.erase(MBBI);
1905       MBB.erase(Prev);
1906       return true;
1907     }
1908 
1909   llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
1910 }
1911 
runOnMachineFunction(MachineFunction & Fn)1912 bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1913   if (skipFunction(*Fn.getFunction()))
1914     return false;
1915 
1916   MF = &Fn;
1917   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1918   TL = STI->getTargetLowering();
1919   AFI = Fn.getInfo<ARMFunctionInfo>();
1920   TII = STI->getInstrInfo();
1921   TRI = STI->getRegisterInfo();
1922 
1923   RegClassInfoValid = false;
1924   isThumb2 = AFI->isThumb2Function();
1925   isThumb1 = AFI->isThumbFunction() && !isThumb2;
1926 
1927   bool Modified = false;
1928   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1929        ++MFI) {
1930     MachineBasicBlock &MBB = *MFI;
1931     Modified |= LoadStoreMultipleOpti(MBB);
1932     if (STI->hasV5TOps())
1933       Modified |= MergeReturnIntoLDM(MBB);
1934     if (isThumb1)
1935       Modified |= CombineMovBx(MBB);
1936   }
1937 
1938   Allocator.DestroyAll();
1939   return Modified;
1940 }
1941 
1942 namespace llvm {
1943 void initializeARMPreAllocLoadStoreOptPass(PassRegistry &);
1944 }
1945 
1946 #define ARM_PREALLOC_LOAD_STORE_OPT_NAME                                       \
1947   "ARM pre- register allocation load / store optimization pass"
1948 
1949 namespace {
1950   /// Pre- register allocation pass that move load / stores from consecutive
1951   /// locations close to make it more likely they will be combined later.
1952   struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
1953     static char ID;
ARMPreAllocLoadStoreOpt__anonf87ca22c0311::ARMPreAllocLoadStoreOpt1954     ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {
1955       initializeARMPreAllocLoadStoreOptPass(*PassRegistry::getPassRegistry());
1956     }
1957 
1958     const DataLayout *TD;
1959     const TargetInstrInfo *TII;
1960     const TargetRegisterInfo *TRI;
1961     const ARMSubtarget *STI;
1962     MachineRegisterInfo *MRI;
1963     MachineFunction *MF;
1964 
1965     bool runOnMachineFunction(MachineFunction &Fn) override;
1966 
getPassName__anonf87ca22c0311::ARMPreAllocLoadStoreOpt1967     const char *getPassName() const override {
1968       return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
1969     }
1970 
1971   private:
1972     bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1973                           unsigned &NewOpc, unsigned &EvenReg,
1974                           unsigned &OddReg, unsigned &BaseReg,
1975                           int &Offset,
1976                           unsigned &PredReg, ARMCC::CondCodes &Pred,
1977                           bool &isT2);
1978     bool RescheduleOps(MachineBasicBlock *MBB,
1979                        SmallVectorImpl<MachineInstr *> &Ops,
1980                        unsigned Base, bool isLd,
1981                        DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1982     bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1983   };
1984   char ARMPreAllocLoadStoreOpt::ID = 0;
1985 }
1986 
1987 INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-load-store-opt",
1988                 ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
1989 
runOnMachineFunction(MachineFunction & Fn)1990 bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1991   if (AssumeMisalignedLoadStores || skipFunction(*Fn.getFunction()))
1992     return false;
1993 
1994   TD = &Fn.getDataLayout();
1995   STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1996   TII = STI->getInstrInfo();
1997   TRI = STI->getRegisterInfo();
1998   MRI = &Fn.getRegInfo();
1999   MF  = &Fn;
2000 
2001   bool Modified = false;
2002   for (MachineBasicBlock &MFI : Fn)
2003     Modified |= RescheduleLoadStoreInstrs(&MFI);
2004 
2005   return Modified;
2006 }
2007 
IsSafeAndProfitableToMove(bool isLd,unsigned Base,MachineBasicBlock::iterator I,MachineBasicBlock::iterator E,SmallPtrSetImpl<MachineInstr * > & MemOps,SmallSet<unsigned,4> & MemRegs,const TargetRegisterInfo * TRI)2008 static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2009                                       MachineBasicBlock::iterator I,
2010                                       MachineBasicBlock::iterator E,
2011                                       SmallPtrSetImpl<MachineInstr*> &MemOps,
2012                                       SmallSet<unsigned, 4> &MemRegs,
2013                                       const TargetRegisterInfo *TRI) {
2014   // Are there stores / loads / calls between them?
2015   // FIXME: This is overly conservative. We should make use of alias information
2016   // some day.
2017   SmallSet<unsigned, 4> AddedRegPressure;
2018   while (++I != E) {
2019     if (I->isDebugValue() || MemOps.count(&*I))
2020       continue;
2021     if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2022       return false;
2023     if (isLd && I->mayStore())
2024       return false;
2025     if (!isLd) {
2026       if (I->mayLoad())
2027         return false;
2028       // It's not safe to move the first 'str' down.
2029       // str r1, [r0]
2030       // strh r5, [r0]
2031       // str r4, [r0, #+4]
2032       if (I->mayStore())
2033         return false;
2034     }
2035     for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2036       MachineOperand &MO = I->getOperand(j);
2037       if (!MO.isReg())
2038         continue;
2039       unsigned Reg = MO.getReg();
2040       if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2041         return false;
2042       if (Reg != Base && !MemRegs.count(Reg))
2043         AddedRegPressure.insert(Reg);
2044     }
2045   }
2046 
2047   // Estimate register pressure increase due to the transformation.
2048   if (MemRegs.size() <= 4)
2049     // Ok if we are moving small number of instructions.
2050     return true;
2051   return AddedRegPressure.size() <= MemRegs.size() * 2;
2052 }
2053 
2054 bool
CanFormLdStDWord(MachineInstr * Op0,MachineInstr * Op1,DebugLoc & dl,unsigned & NewOpc,unsigned & FirstReg,unsigned & SecondReg,unsigned & BaseReg,int & Offset,unsigned & PredReg,ARMCC::CondCodes & Pred,bool & isT2)2055 ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
2056                                           DebugLoc &dl, unsigned &NewOpc,
2057                                           unsigned &FirstReg,
2058                                           unsigned &SecondReg,
2059                                           unsigned &BaseReg, int &Offset,
2060                                           unsigned &PredReg,
2061                                           ARMCC::CondCodes &Pred,
2062                                           bool &isT2) {
2063   // Make sure we're allowed to generate LDRD/STRD.
2064   if (!STI->hasV5TEOps())
2065     return false;
2066 
2067   // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2068   unsigned Scale = 1;
2069   unsigned Opcode = Op0->getOpcode();
2070   if (Opcode == ARM::LDRi12) {
2071     NewOpc = ARM::LDRD;
2072   } else if (Opcode == ARM::STRi12) {
2073     NewOpc = ARM::STRD;
2074   } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2075     NewOpc = ARM::t2LDRDi8;
2076     Scale = 4;
2077     isT2 = true;
2078   } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2079     NewOpc = ARM::t2STRDi8;
2080     Scale = 4;
2081     isT2 = true;
2082   } else {
2083     return false;
2084   }
2085 
2086   // Make sure the base address satisfies i64 ld / st alignment requirement.
2087   // At the moment, we ignore the memoryoperand's value.
2088   // If we want to use AliasAnalysis, we should check it accordingly.
2089   if (!Op0->hasOneMemOperand() ||
2090       (*Op0->memoperands_begin())->isVolatile())
2091     return false;
2092 
2093   unsigned Align = (*Op0->memoperands_begin())->getAlignment();
2094   const Function *Func = MF->getFunction();
2095   unsigned ReqAlign = STI->hasV6Ops()
2096     ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
2097     : 8;  // Pre-v6 need 8-byte align
2098   if (Align < ReqAlign)
2099     return false;
2100 
2101   // Then make sure the immediate offset fits.
2102   int OffImm = getMemoryOpOffset(*Op0);
2103   if (isT2) {
2104     int Limit = (1 << 8) * Scale;
2105     if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2106       return false;
2107     Offset = OffImm;
2108   } else {
2109     ARM_AM::AddrOpc AddSub = ARM_AM::add;
2110     if (OffImm < 0) {
2111       AddSub = ARM_AM::sub;
2112       OffImm = - OffImm;
2113     }
2114     int Limit = (1 << 8) * Scale;
2115     if (OffImm >= Limit || (OffImm & (Scale-1)))
2116       return false;
2117     Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2118   }
2119   FirstReg = Op0->getOperand(0).getReg();
2120   SecondReg = Op1->getOperand(0).getReg();
2121   if (FirstReg == SecondReg)
2122     return false;
2123   BaseReg = Op0->getOperand(1).getReg();
2124   Pred = getInstrPredicate(*Op0, PredReg);
2125   dl = Op0->getDebugLoc();
2126   return true;
2127 }
2128 
RescheduleOps(MachineBasicBlock * MBB,SmallVectorImpl<MachineInstr * > & Ops,unsigned Base,bool isLd,DenseMap<MachineInstr *,unsigned> & MI2LocMap)2129 bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
2130                                  SmallVectorImpl<MachineInstr *> &Ops,
2131                                  unsigned Base, bool isLd,
2132                                  DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2133   bool RetVal = false;
2134 
2135   // Sort by offset (in reverse order).
2136   std::sort(Ops.begin(), Ops.end(),
2137             [](const MachineInstr *LHS, const MachineInstr *RHS) {
2138               int LOffset = getMemoryOpOffset(*LHS);
2139               int ROffset = getMemoryOpOffset(*RHS);
2140               assert(LHS == RHS || LOffset != ROffset);
2141               return LOffset > ROffset;
2142             });
2143 
2144   // The loads / stores of the same base are in order. Scan them from first to
2145   // last and check for the following:
2146   // 1. Any def of base.
2147   // 2. Any gaps.
2148   while (Ops.size() > 1) {
2149     unsigned FirstLoc = ~0U;
2150     unsigned LastLoc = 0;
2151     MachineInstr *FirstOp = nullptr;
2152     MachineInstr *LastOp = nullptr;
2153     int LastOffset = 0;
2154     unsigned LastOpcode = 0;
2155     unsigned LastBytes = 0;
2156     unsigned NumMove = 0;
2157     for (int i = Ops.size() - 1; i >= 0; --i) {
2158       MachineInstr *Op = Ops[i];
2159       unsigned Loc = MI2LocMap[Op];
2160       if (Loc <= FirstLoc) {
2161         FirstLoc = Loc;
2162         FirstOp = Op;
2163       }
2164       if (Loc >= LastLoc) {
2165         LastLoc = Loc;
2166         LastOp = Op;
2167       }
2168 
2169       unsigned LSMOpcode
2170         = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2171       if (LastOpcode && LSMOpcode != LastOpcode)
2172         break;
2173 
2174       int Offset = getMemoryOpOffset(*Op);
2175       unsigned Bytes = getLSMultipleTransferSize(Op);
2176       if (LastBytes) {
2177         if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2178           break;
2179       }
2180       LastOffset = Offset;
2181       LastBytes = Bytes;
2182       LastOpcode = LSMOpcode;
2183       if (++NumMove == 8) // FIXME: Tune this limit.
2184         break;
2185     }
2186 
2187     if (NumMove <= 1)
2188       Ops.pop_back();
2189     else {
2190       SmallPtrSet<MachineInstr*, 4> MemOps;
2191       SmallSet<unsigned, 4> MemRegs;
2192       for (int i = NumMove-1; i >= 0; --i) {
2193         MemOps.insert(Ops[i]);
2194         MemRegs.insert(Ops[i]->getOperand(0).getReg());
2195       }
2196 
2197       // Be conservative, if the instructions are too far apart, don't
2198       // move them. We want to limit the increase of register pressure.
2199       bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2200       if (DoMove)
2201         DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2202                                            MemOps, MemRegs, TRI);
2203       if (!DoMove) {
2204         for (unsigned i = 0; i != NumMove; ++i)
2205           Ops.pop_back();
2206       } else {
2207         // This is the new location for the loads / stores.
2208         MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2209         while (InsertPos != MBB->end() &&
2210                (MemOps.count(&*InsertPos) || InsertPos->isDebugValue()))
2211           ++InsertPos;
2212 
2213         // If we are moving a pair of loads / stores, see if it makes sense
2214         // to try to allocate a pair of registers that can form register pairs.
2215         MachineInstr *Op0 = Ops.back();
2216         MachineInstr *Op1 = Ops[Ops.size()-2];
2217         unsigned FirstReg = 0, SecondReg = 0;
2218         unsigned BaseReg = 0, PredReg = 0;
2219         ARMCC::CondCodes Pred = ARMCC::AL;
2220         bool isT2 = false;
2221         unsigned NewOpc = 0;
2222         int Offset = 0;
2223         DebugLoc dl;
2224         if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2225                                              FirstReg, SecondReg, BaseReg,
2226                                              Offset, PredReg, Pred, isT2)) {
2227           Ops.pop_back();
2228           Ops.pop_back();
2229 
2230           const MCInstrDesc &MCID = TII->get(NewOpc);
2231           const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2232           MRI->constrainRegClass(FirstReg, TRC);
2233           MRI->constrainRegClass(SecondReg, TRC);
2234 
2235           // Form the pair instruction.
2236           if (isLd) {
2237             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2238               .addReg(FirstReg, RegState::Define)
2239               .addReg(SecondReg, RegState::Define)
2240               .addReg(BaseReg);
2241             // FIXME: We're converting from LDRi12 to an insn that still
2242             // uses addrmode2, so we need an explicit offset reg. It should
2243             // always by reg0 since we're transforming LDRi12s.
2244             if (!isT2)
2245               MIB.addReg(0);
2246             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2247             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2248             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2249             ++NumLDRDFormed;
2250           } else {
2251             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2252               .addReg(FirstReg)
2253               .addReg(SecondReg)
2254               .addReg(BaseReg);
2255             // FIXME: We're converting from LDRi12 to an insn that still
2256             // uses addrmode2, so we need an explicit offset reg. It should
2257             // always by reg0 since we're transforming STRi12s.
2258             if (!isT2)
2259               MIB.addReg(0);
2260             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2261             MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2262             DEBUG(dbgs() << "Formed " << *MIB << "\n");
2263             ++NumSTRDFormed;
2264           }
2265           MBB->erase(Op0);
2266           MBB->erase(Op1);
2267 
2268           if (!isT2) {
2269             // Add register allocation hints to form register pairs.
2270             MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2271             MRI->setRegAllocationHint(SecondReg,  ARMRI::RegPairOdd, FirstReg);
2272           }
2273         } else {
2274           for (unsigned i = 0; i != NumMove; ++i) {
2275             MachineInstr *Op = Ops.back();
2276             Ops.pop_back();
2277             MBB->splice(InsertPos, MBB, Op);
2278           }
2279         }
2280 
2281         NumLdStMoved += NumMove;
2282         RetVal = true;
2283       }
2284     }
2285   }
2286 
2287   return RetVal;
2288 }
2289 
2290 bool
RescheduleLoadStoreInstrs(MachineBasicBlock * MBB)2291 ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2292   bool RetVal = false;
2293 
2294   DenseMap<MachineInstr*, unsigned> MI2LocMap;
2295   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2296   DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2297   SmallVector<unsigned, 4> LdBases;
2298   SmallVector<unsigned, 4> StBases;
2299 
2300   unsigned Loc = 0;
2301   MachineBasicBlock::iterator MBBI = MBB->begin();
2302   MachineBasicBlock::iterator E = MBB->end();
2303   while (MBBI != E) {
2304     for (; MBBI != E; ++MBBI) {
2305       MachineInstr &MI = *MBBI;
2306       if (MI.isCall() || MI.isTerminator()) {
2307         // Stop at barriers.
2308         ++MBBI;
2309         break;
2310       }
2311 
2312       if (!MI.isDebugValue())
2313         MI2LocMap[&MI] = ++Loc;
2314 
2315       if (!isMemoryOp(MI))
2316         continue;
2317       unsigned PredReg = 0;
2318       if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2319         continue;
2320 
2321       int Opc = MI.getOpcode();
2322       bool isLd = isLoadSingle(Opc);
2323       unsigned Base = MI.getOperand(1).getReg();
2324       int Offset = getMemoryOpOffset(MI);
2325 
2326       bool StopHere = false;
2327       if (isLd) {
2328         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2329           Base2LdsMap.find(Base);
2330         if (BI != Base2LdsMap.end()) {
2331           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2332             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2333               StopHere = true;
2334               break;
2335             }
2336           }
2337           if (!StopHere)
2338             BI->second.push_back(&MI);
2339         } else {
2340           Base2LdsMap[Base].push_back(&MI);
2341           LdBases.push_back(Base);
2342         }
2343       } else {
2344         DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2345           Base2StsMap.find(Base);
2346         if (BI != Base2StsMap.end()) {
2347           for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2348             if (Offset == getMemoryOpOffset(*BI->second[i])) {
2349               StopHere = true;
2350               break;
2351             }
2352           }
2353           if (!StopHere)
2354             BI->second.push_back(&MI);
2355         } else {
2356           Base2StsMap[Base].push_back(&MI);
2357           StBases.push_back(Base);
2358         }
2359       }
2360 
2361       if (StopHere) {
2362         // Found a duplicate (a base+offset combination that's seen earlier).
2363         // Backtrack.
2364         --Loc;
2365         break;
2366       }
2367     }
2368 
2369     // Re-schedule loads.
2370     for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2371       unsigned Base = LdBases[i];
2372       SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2373       if (Lds.size() > 1)
2374         RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2375     }
2376 
2377     // Re-schedule stores.
2378     for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2379       unsigned Base = StBases[i];
2380       SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2381       if (Sts.size() > 1)
2382         RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2383     }
2384 
2385     if (MBBI != E) {
2386       Base2LdsMap.clear();
2387       Base2StsMap.clear();
2388       LdBases.clear();
2389       StBases.clear();
2390     }
2391   }
2392 
2393   return RetVal;
2394 }
2395 
2396 
2397 /// Returns an instance of the load / store optimization pass.
createARMLoadStoreOptimizationPass(bool PreAlloc)2398 FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2399   if (PreAlloc)
2400     return new ARMPreAllocLoadStoreOpt();
2401   return new ARMLoadStoreOpt();
2402 }
2403