blob: b6f8c320ba56b1f53b4dc8206db79449793e63ea [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Cheng10043e22007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
Matthias Braunec50fa62015-06-01 21:26:23 +000010/// \file This file contains a pass that performs load / store related peephole
11/// optimizations. This pass should be run after register allocation.
Evan Cheng10043e22007-01-19 07:51:42 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Cheng10043e22007-01-19 07:51:42 +000015#include "ARM.h"
Evan Cheng2aa91cc2009-08-08 03:20:32 +000016#include "ARMBaseInstrInfo.h"
Craig Topper5fa0caa2012-03-26 00:45:15 +000017#include "ARMBaseRegisterInfo.h"
James Molloy556763d2014-05-16 14:14:30 +000018#include "ARMISelLowering.h"
Evan Chengf030f2d2007-03-07 20:30:36 +000019#include "ARMMachineFunctionInfo.h"
Craig Toppera9253262014-03-22 23:51:00 +000020#include "ARMSubtarget.h"
Evan Chenga20cde32011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Eric Christopherae326492015-03-12 22:48:50 +000022#include "ThumbRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#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"
Evan Cheng10043e22007-01-19 07:51:42 +000029#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng185c9ef2009-06-13 09:12:55 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000034#include "llvm/CodeGen/RegisterClassInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000035#include "llvm/CodeGen/SelectionDAGNodes.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000036#include "llvm/CodeGen/LivePhysRegs.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/DerivedTypes.h"
39#include "llvm/IR/Function.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000040#include "llvm/Support/Allocator.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000043#include "llvm/Support/raw_ostream.h"
Evan Cheng10043e22007-01-19 07:51:42 +000044#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetMachine.h"
Evan Cheng1283c6a2009-06-15 08:28:29 +000046#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng10043e22007-01-19 07:51:42 +000047using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "arm-ldst-opt"
50
Evan Cheng10043e22007-01-19 07:51:42 +000051STATISTIC(NumLDMGened , "Number of ldm instructions generated");
52STATISTIC(NumSTMGened , "Number of stm instructions generated");
Jim Grosbachd7cf55c2009-11-09 00:11:35 +000053STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
54STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
Evan Cheng185c9ef2009-06-13 09:12:55 +000055STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
Evan Cheng0e796032009-06-18 02:04:01 +000056STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
57STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
58STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
59STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
60STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
61STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
Evan Cheng185c9ef2009-06-13 09:12:55 +000062
Evan Cheng10043e22007-01-19 07:51:42 +000063namespace {
Matthias Braunec50fa62015-06-01 21:26:23 +000064 /// Post- register allocation pass the combine load / store instructions to
65 /// form ldm / stm instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000066 struct ARMLoadStoreOpt : public MachineFunctionPass {
Devang Patel8c78a0b2007-05-03 01:11:54 +000067 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +000068 ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000069
Matthias Brauna4a3182d2015-07-10 18:08:49 +000070 const MachineFunction *MF;
Evan Cheng10043e22007-01-19 07:51:42 +000071 const TargetInstrInfo *TII;
Dan Gohman3a4be0f2008-02-10 18:45:23 +000072 const TargetRegisterInfo *TRI;
Matthias Brauna4a3182d2015-07-10 18:08:49 +000073 const MachineRegisterInfo *MRI;
Evan Chengc3770ac2011-11-08 21:21:09 +000074 const ARMSubtarget *STI;
James Molloy556763d2014-05-16 14:14:30 +000075 const TargetLowering *TL;
Evan Chengf030f2d2007-03-07 20:30:36 +000076 ARMFunctionInfo *AFI;
Matthias Brauna4a3182d2015-07-10 18:08:49 +000077 LivePhysRegs LiveRegs;
78 RegisterClassInfo RegClassInfo;
79 MachineBasicBlock::const_iterator LiveRegPos;
80 bool LiveRegsValid;
81 bool RegClassInfoValid;
James Molloy92a15072014-05-16 14:11:38 +000082 bool isThumb1, isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +000083
Craig Topper6bc27bf2014-03-10 02:09:33 +000084 bool runOnMachineFunction(MachineFunction &Fn) override;
Evan Cheng10043e22007-01-19 07:51:42 +000085
Craig Topper6bc27bf2014-03-10 02:09:33 +000086 const char *getPassName() const override {
Evan Cheng10043e22007-01-19 07:51:42 +000087 return "ARM load / store optimization pass";
88 }
89
90 private:
Matthias Brauna4a3182d2015-07-10 18:08:49 +000091 /// A set of load/store MachineInstrs with same base register sorted by
92 /// offset.
Evan Cheng10043e22007-01-19 07:51:42 +000093 struct MemOpQueueEntry {
Matthias Brauna4a3182d2015-07-10 18:08:49 +000094 MachineInstr *MI;
95 int Offset; ///< Load/Store offset.
96 unsigned Position; ///< Position as counted from end of basic block.
97 MemOpQueueEntry(MachineInstr *MI, int Offset, unsigned Position)
98 : MI(MI), Offset(Offset), Position(Position) {}
Evan Cheng10043e22007-01-19 07:51:42 +000099 };
100 typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
Evan Cheng10043e22007-01-19 07:51:42 +0000101
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000102 /// A set of MachineInstrs that fulfill (nearly all) conditions to get
103 /// merged into a LDM/STM.
104 struct MergeCandidate {
105 /// List of instructions ordered by load/store offset.
106 SmallVector<MachineInstr*, 4> Instrs;
107 /// Index in Instrs of the instruction being latest in the schedule.
108 unsigned LatestMIIdx;
109 /// Index in Instrs of the instruction being earliest in the schedule.
110 unsigned EarliestMIIdx;
111 /// Index into the basic block where the merged instruction will be
112 /// inserted. (See MemOpQueueEntry.Position)
113 unsigned InsertPos;
Matthias Braune40d89e2015-07-21 00:18:59 +0000114 /// Whether the instructions can be merged into a ldm/stm instruction.
115 bool CanMergeToLSMulti;
116 /// Whether the instructions can be merged into a ldrd/strd instruction.
117 bool CanMergeToLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000118 };
Matthias Braune40d89e2015-07-21 00:18:59 +0000119 SpecificBumpPtrAllocator<MergeCandidate> Allocator;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000120 SmallVector<const MergeCandidate*,4> Candidates;
121
122 void moveLiveRegsBefore(const MachineBasicBlock &MBB,
123 MachineBasicBlock::const_iterator Before);
124 unsigned findFreeReg(const TargetRegisterClass &RegClass);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000125 void UpdateBaseRegUses(MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator MBBI,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000127 DebugLoc DL, unsigned Base, unsigned WordOffset,
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000128 ARMCC::CondCodes Pred, unsigned PredReg);
Matthias Braune40d89e2015-07-21 00:18:59 +0000129 MachineInstr *CreateLoadStoreMulti(MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
131 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
132 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs);
133 MachineInstr *CreateLoadStoreDouble(MachineBasicBlock &MBB,
134 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
135 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
136 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000137 void FormCandidates(const MemOpQueue &MemOps);
138 MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
Evan Cheng1283c6a2009-06-15 08:28:29 +0000139 bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
140 MachineBasicBlock::iterator &MBBI);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000141 bool MergeBaseUpdateLoadStore(MachineInstr *MI);
142 bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
Evan Cheng10043e22007-01-19 07:51:42 +0000143 bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
144 bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
145 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000146 char ARMLoadStoreOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000147}
Evan Cheng10043e22007-01-19 07:51:42 +0000148
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000149static bool definesCPSR(const MachineInstr *MI) {
150 for (const auto &MO : MI->operands()) {
151 if (!MO.isReg())
152 continue;
153 if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
154 // If the instruction has live CPSR def, then it's not safe to fold it
155 // into load / store.
156 return true;
157 }
158
159 return false;
160}
161
162static int getMemoryOpOffset(const MachineInstr *MI) {
Matthias Braunfa3872e2015-05-18 20:27:55 +0000163 unsigned Opcode = MI->getOpcode();
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000164 bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
165 unsigned NumOperands = MI->getDesc().getNumOperands();
166 unsigned OffField = MI->getOperand(NumOperands-3).getImm();
167
168 if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
169 Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
170 Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
171 Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
172 return OffField;
173
174 // Thumb1 immediate offsets are scaled by 4
Renato Golinb9887ef2015-02-25 14:41:06 +0000175 if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
176 Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000177 return OffField * 4;
178
179 int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
180 : ARM_AM::getAM5Offset(OffField) * 4;
181 ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
182 : ARM_AM::getAM5Op(OffField);
183
184 if (Op == ARM_AM::sub)
185 return -Offset;
186
187 return Offset;
188}
189
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000190static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
191 return MI.getOperand(1);
192}
193
194static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
195 return MI.getOperand(0);
196}
197
Matthias Braunfa3872e2015-05-18 20:27:55 +0000198static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +0000199 switch (Opcode) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000200 default: llvm_unreachable("Unhandled opcode!");
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000201 case ARM::LDRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000202 ++NumLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000203 switch (Mode) {
204 default: llvm_unreachable("Unhandled submode!");
205 case ARM_AM::ia: return ARM::LDMIA;
206 case ARM_AM::da: return ARM::LDMDA;
207 case ARM_AM::db: return ARM::LDMDB;
208 case ARM_AM::ib: return ARM::LDMIB;
209 }
Jim Grosbach338de3e2010-10-27 23:12:14 +0000210 case ARM::STRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000211 ++NumSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000212 switch (Mode) {
213 default: llvm_unreachable("Unhandled submode!");
214 case ARM_AM::ia: return ARM::STMIA;
215 case ARM_AM::da: return ARM::STMDA;
216 case ARM_AM::db: return ARM::STMDB;
217 case ARM_AM::ib: return ARM::STMIB;
218 }
James Molloy556763d2014-05-16 14:14:30 +0000219 case ARM::tLDRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000220 case ARM::tLDRspi:
James Molloy556763d2014-05-16 14:14:30 +0000221 // tLDMIA is writeback-only - unless the base register is in the input
222 // reglist.
223 ++NumLDMGened;
224 switch (Mode) {
225 default: llvm_unreachable("Unhandled submode!");
226 case ARM_AM::ia: return ARM::tLDMIA;
227 }
228 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000229 case ARM::tSTRspi:
James Molloy556763d2014-05-16 14:14:30 +0000230 // There is no non-writeback tSTMIA either.
231 ++NumSTMGened;
232 switch (Mode) {
233 default: llvm_unreachable("Unhandled submode!");
234 case ARM_AM::ia: return ARM::tSTMIA_UPD;
235 }
Evan Cheng4605e8a2009-07-09 23:11:34 +0000236 case ARM::t2LDRi8:
237 case ARM::t2LDRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000238 ++NumLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000239 switch (Mode) {
240 default: llvm_unreachable("Unhandled submode!");
241 case ARM_AM::ia: return ARM::t2LDMIA;
242 case ARM_AM::db: return ARM::t2LDMDB;
243 }
Evan Cheng4605e8a2009-07-09 23:11:34 +0000244 case ARM::t2STRi8:
245 case ARM::t2STRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000246 ++NumSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000247 switch (Mode) {
248 default: llvm_unreachable("Unhandled submode!");
249 case ARM_AM::ia: return ARM::t2STMIA;
250 case ARM_AM::db: return ARM::t2STMDB;
251 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000252 case ARM::VLDRS:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000253 ++NumVLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000254 switch (Mode) {
255 default: llvm_unreachable("Unhandled submode!");
256 case ARM_AM::ia: return ARM::VLDMSIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000257 case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000258 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000259 case ARM::VSTRS:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000260 ++NumVSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000261 switch (Mode) {
262 default: llvm_unreachable("Unhandled submode!");
263 case ARM_AM::ia: return ARM::VSTMSIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000264 case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000265 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000266 case ARM::VLDRD:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000267 ++NumVLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000268 switch (Mode) {
269 default: llvm_unreachable("Unhandled submode!");
270 case ARM_AM::ia: return ARM::VLDMDIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000271 case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000272 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000273 case ARM::VSTRD:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000274 ++NumVSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000275 switch (Mode) {
276 default: llvm_unreachable("Unhandled submode!");
277 case ARM_AM::ia: return ARM::VSTMDIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000278 case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000279 }
Evan Cheng10043e22007-01-19 07:51:42 +0000280 }
Evan Cheng10043e22007-01-19 07:51:42 +0000281}
282
Benjamin Kramer113b2a92015-06-05 14:32:54 +0000283static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000284 switch (Opcode) {
285 default: llvm_unreachable("Unhandled opcode!");
Bill Wendlingb9bd5942010-11-18 19:44:29 +0000286 case ARM::LDMIA_RET:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000287 case ARM::LDMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000288 case ARM::LDMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000289 case ARM::STMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000290 case ARM::STMIA_UPD:
James Molloy556763d2014-05-16 14:14:30 +0000291 case ARM::tLDMIA:
292 case ARM::tLDMIA_UPD:
293 case ARM::tSTMIA_UPD:
Bill Wendlingb9bd5942010-11-18 19:44:29 +0000294 case ARM::t2LDMIA_RET:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000295 case ARM::t2LDMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000296 case ARM::t2LDMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000297 case ARM::t2STMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000298 case ARM::t2STMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000299 case ARM::VLDMSIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000300 case ARM::VLDMSIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000301 case ARM::VSTMSIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000302 case ARM::VSTMSIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000303 case ARM::VLDMDIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000304 case ARM::VLDMDIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000305 case ARM::VSTMDIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000306 case ARM::VSTMDIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000307 return ARM_AM::ia;
308
309 case ARM::LDMDA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000310 case ARM::LDMDA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000311 case ARM::STMDA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000312 case ARM::STMDA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000313 return ARM_AM::da;
314
315 case ARM::LDMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000316 case ARM::LDMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000317 case ARM::STMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000318 case ARM::STMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000319 case ARM::t2LDMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000320 case ARM::t2LDMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000321 case ARM::t2STMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000322 case ARM::t2STMDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000323 case ARM::VLDMSDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000324 case ARM::VSTMSDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000325 case ARM::VLDMDDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000326 case ARM::VSTMDDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000327 return ARM_AM::db;
328
329 case ARM::LDMIB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000330 case ARM::LDMIB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000331 case ARM::STMIB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000332 case ARM::STMIB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000333 return ARM_AM::ib;
334 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000335}
336
James Molloy556763d2014-05-16 14:14:30 +0000337static bool isT1i32Load(unsigned Opc) {
Renato Golinb9887ef2015-02-25 14:41:06 +0000338 return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
James Molloy556763d2014-05-16 14:14:30 +0000339}
340
Evan Cheng71756e72009-08-04 01:43:45 +0000341static bool isT2i32Load(unsigned Opc) {
342 return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
343}
344
Evan Cheng4605e8a2009-07-09 23:11:34 +0000345static bool isi32Load(unsigned Opc) {
James Molloy556763d2014-05-16 14:14:30 +0000346 return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
347}
348
349static bool isT1i32Store(unsigned Opc) {
Renato Golinb9887ef2015-02-25 14:41:06 +0000350 return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
Evan Cheng71756e72009-08-04 01:43:45 +0000351}
352
353static bool isT2i32Store(unsigned Opc) {
354 return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
Evan Cheng4605e8a2009-07-09 23:11:34 +0000355}
356
357static bool isi32Store(unsigned Opc) {
James Molloy556763d2014-05-16 14:14:30 +0000358 return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
359}
360
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000361static bool isLoadSingle(unsigned Opc) {
362 return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
363}
364
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000365static unsigned getImmScale(unsigned Opc) {
366 switch (Opc) {
367 default: llvm_unreachable("Unhandled opcode!");
368 case ARM::tLDRi:
369 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000370 case ARM::tLDRspi:
371 case ARM::tSTRspi:
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000372 return 1;
373 case ARM::tLDRHi:
374 case ARM::tSTRHi:
375 return 2;
376 case ARM::tLDRBi:
377 case ARM::tSTRBi:
378 return 4;
379 }
380}
381
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000382static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
383 switch (MI->getOpcode()) {
384 default: return 0;
385 case ARM::LDRi12:
386 case ARM::STRi12:
387 case ARM::tLDRi:
388 case ARM::tSTRi:
389 case ARM::tLDRspi:
390 case ARM::tSTRspi:
391 case ARM::t2LDRi8:
392 case ARM::t2LDRi12:
393 case ARM::t2STRi8:
394 case ARM::t2STRi12:
395 case ARM::VLDRS:
396 case ARM::VSTRS:
397 return 4;
398 case ARM::VLDRD:
399 case ARM::VSTRD:
400 return 8;
401 case ARM::LDMIA:
402 case ARM::LDMDA:
403 case ARM::LDMDB:
404 case ARM::LDMIB:
405 case ARM::STMIA:
406 case ARM::STMDA:
407 case ARM::STMDB:
408 case ARM::STMIB:
409 case ARM::tLDMIA:
410 case ARM::tLDMIA_UPD:
411 case ARM::tSTMIA_UPD:
412 case ARM::t2LDMIA:
413 case ARM::t2LDMDB:
414 case ARM::t2STMIA:
415 case ARM::t2STMDB:
416 case ARM::VLDMSIA:
417 case ARM::VSTMSIA:
418 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
419 case ARM::VLDMDIA:
420 case ARM::VSTMDIA:
421 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
422 }
423}
424
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000425/// Update future uses of the base register with the offset introduced
426/// due to writeback. This function only works on Thumb1.
427void
428ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
429 MachineBasicBlock::iterator MBBI,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000430 DebugLoc DL, unsigned Base,
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000431 unsigned WordOffset,
432 ARMCC::CondCodes Pred, unsigned PredReg) {
433 assert(isThumb1 && "Can only update base register uses for Thumb1!");
434 // Start updating any instructions with immediate offsets. Insert a SUB before
435 // the first non-updateable instruction (if any).
436 for (; MBBI != MBB.end(); ++MBBI) {
437 bool InsertSub = false;
438 unsigned Opc = MBBI->getOpcode();
439
440 if (MBBI->readsRegister(Base)) {
441 int Offset;
442 bool IsLoad =
443 Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
444 bool IsStore =
445 Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
446
447 if (IsLoad || IsStore) {
448 // Loads and stores with immediate offsets can be updated, but only if
449 // the new offset isn't negative.
450 // The MachineOperand containing the offset immediate is the last one
451 // before predicates.
452 MachineOperand &MO =
453 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
454 // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
455 Offset = MO.getImm() - WordOffset * getImmScale(Opc);
456
457 // If storing the base register, it needs to be reset first.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000458 unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000459
460 if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
461 MO.setImm(Offset);
462 else
463 InsertSub = true;
464
465 } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
466 !definesCPSR(MBBI)) {
467 // SUBS/ADDS using this register, with a dead def of the CPSR.
468 // Merge it with the update; if the merged offset is too large,
469 // insert a new sub instead.
470 MachineOperand &MO =
471 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
472 Offset = (Opc == ARM::tSUBi8) ?
473 MO.getImm() + WordOffset * 4 :
474 MO.getImm() - WordOffset * 4 ;
475 if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
476 // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
477 // Offset == 0.
478 MO.setImm(Offset);
479 // The base register has now been reset, so exit early.
480 return;
481 } else {
482 InsertSub = true;
483 }
484
485 } else {
486 // Can't update the instruction.
487 InsertSub = true;
488 }
489
490 } else if (definesCPSR(MBBI) || MBBI->isCall() || MBBI->isBranch()) {
491 // Since SUBS sets the condition flags, we can't place the base reset
492 // after an instruction that has a live CPSR def.
493 // The base register might also contain an argument for a function call.
494 InsertSub = true;
495 }
496
497 if (InsertSub) {
498 // An instruction above couldn't be updated, so insert a sub.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000499 AddDefaultT1CC(BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
Matthias Braunaa9fa352015-05-27 05:12:40 +0000500 .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000501 return;
502 }
503
John Brawnd86e0042015-06-23 16:02:11 +0000504 if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000505 // Register got killed. Stop updating.
506 return;
507 }
508
509 // End of block was reached.
510 if (MBB.succ_size() > 0) {
511 // FIXME: Because of a bug, live registers are sometimes missing from
512 // the successor blocks' live-in sets. This means we can't trust that
513 // information and *always* have to reset at the end of a block.
514 // See PR21029.
515 if (MBBI != MBB.end()) --MBBI;
516 AddDefaultT1CC(
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000517 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
Matthias Braunaa9fa352015-05-27 05:12:40 +0000518 .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000519 }
520}
521
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000522/// Return the first register of class \p RegClass that is not in \p Regs.
523unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
524 if (!RegClassInfoValid) {
525 RegClassInfo.runOnMachineFunction(*MF);
526 RegClassInfoValid = true;
527 }
528
529 for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
530 if (!LiveRegs.contains(Reg))
531 return Reg;
532 return 0;
533}
534
535/// Compute live registers just before instruction \p Before (in normal schedule
536/// direction). Computes backwards so multiple queries in the same block must
537/// come in reverse order.
538void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
539 MachineBasicBlock::const_iterator Before) {
540 // Initialize if we never queried in this block.
541 if (!LiveRegsValid) {
542 LiveRegs.init(TRI);
543 LiveRegs.addLiveOuts(&MBB, true);
544 LiveRegPos = MBB.end();
545 LiveRegsValid = true;
546 }
547 // Move backward just before the "Before" position.
548 while (LiveRegPos != Before) {
549 --LiveRegPos;
550 LiveRegs.stepBackward(*LiveRegPos);
551 }
552}
553
554static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
555 unsigned Reg) {
556 for (const std::pair<unsigned, bool> &R : Regs)
557 if (R.first == Reg)
558 return true;
559 return false;
560}
561
Matthias Braunec50fa62015-06-01 21:26:23 +0000562/// Create and insert a LDM or STM with Base as base register and registers in
563/// Regs as the register operands that would be loaded / stored. It returns
564/// true if the transformation is done.
Matthias Braune40d89e2015-07-21 00:18:59 +0000565MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(MachineBasicBlock &MBB,
566 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
567 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
568 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000569 unsigned NumRegs = Regs.size();
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000570 assert(NumRegs > 1);
Evan Cheng10043e22007-01-19 07:51:42 +0000571
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000572 // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
573 // Compute liveness information for that register to make the decision.
574 bool SafeToClobberCPSR = !isThumb1 ||
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000575 (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000576 MachineBasicBlock::LQR_Dead);
577
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000578 bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
579
580 // Exception: If the base register is in the input reglist, Thumb1 LDM is
581 // non-writeback.
582 // It's also not possible to merge an STR of the base register in Thumb1.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000583 if (isThumb1 && isi32Load(Opcode) && ContainsReg(Regs, Base)) {
584 assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
585 if (Opcode == ARM::tLDRi) {
586 Writeback = false;
587 } else if (Opcode == ARM::tSTRi) {
588 return nullptr;
589 }
590 }
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000591
Evan Cheng10043e22007-01-19 07:51:42 +0000592 ARM_AM::AMSubMode Mode = ARM_AM::ia;
James Molloy556763d2014-05-16 14:14:30 +0000593 // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
Bob Wilson13ce07f2010-08-27 23:18:17 +0000594 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
James Molloy556763d2014-05-16 14:14:30 +0000595 bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
596
James Molloybb73c232014-05-16 14:08:46 +0000597 if (Offset == 4 && haveIBAndDA) {
Evan Cheng10043e22007-01-19 07:51:42 +0000598 Mode = ARM_AM::ib;
James Molloybb73c232014-05-16 14:08:46 +0000599 } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
Evan Cheng10043e22007-01-19 07:51:42 +0000600 Mode = ARM_AM::da;
James Molloy556763d2014-05-16 14:14:30 +0000601 } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
Bob Wilsonca5af122010-08-27 23:57:52 +0000602 // VLDM/VSTM do not support DB mode without also updating the base reg.
Evan Cheng10043e22007-01-19 07:51:42 +0000603 Mode = ARM_AM::db;
Renato Golinb9887ef2015-02-25 14:41:06 +0000604 } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
James Molloybb73c232014-05-16 14:08:46 +0000605 // Check if this is a supported opcode before inserting instructions to
Owen Anderson7ac53ad2011-03-29 20:27:38 +0000606 // calculate a new base register.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000607 if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
Owen Anderson7ac53ad2011-03-29 20:27:38 +0000608
Evan Cheng10043e22007-01-19 07:51:42 +0000609 // If starting offset isn't zero, insert a MI to materialize a new base.
610 // But only do so if it is cost effective, i.e. merging more than two
611 // loads / stores.
612 if (NumRegs <= 2)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000613 return nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000614
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000615 // On Thumb1, it's not worth materializing a new base register without
616 // clobbering the CPSR (i.e. not using ADDS/SUBS).
617 if (!SafeToClobberCPSR)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000618 return nullptr;
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000619
Evan Cheng10043e22007-01-19 07:51:42 +0000620 unsigned NewBase;
James Molloybb73c232014-05-16 14:08:46 +0000621 if (isi32Load(Opcode)) {
Evan Cheng10043e22007-01-19 07:51:42 +0000622 // If it is a load, then just use one of the destination register to
623 // use as the new base.
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000624 NewBase = Regs[NumRegs-1].first;
James Molloybb73c232014-05-16 14:08:46 +0000625 } else {
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000626 // Find a free register that we can use as scratch register.
627 moveLiveRegsBefore(MBB, InsertBefore);
628 // The merged instruction does not exist yet but will use several Regs if
629 // it is a Store.
630 if (!isLoadSingle(Opcode))
631 for (const std::pair<unsigned, bool> &R : Regs)
632 LiveRegs.addReg(R.first);
633
634 NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000635 if (NewBase == 0)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000636 return nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000637 }
James Molloy556763d2014-05-16 14:14:30 +0000638
639 int BaseOpc =
640 isThumb2 ? ARM::t2ADDri :
Renato Golinb9887ef2015-02-25 14:41:06 +0000641 (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000642 (isThumb1 && Offset < 8) ? ARM::tADDi3 :
James Molloy556763d2014-05-16 14:14:30 +0000643 isThumb1 ? ARM::tADDi8 : ARM::ADDri;
644
Evan Cheng10043e22007-01-19 07:51:42 +0000645 if (Offset < 0) {
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000646 Offset = - Offset;
James Molloy556763d2014-05-16 14:14:30 +0000647 BaseOpc =
648 isThumb2 ? ARM::t2SUBri :
Renato Golinb9887ef2015-02-25 14:41:06 +0000649 (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
James Molloy556763d2014-05-16 14:14:30 +0000650 isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
Evan Cheng10043e22007-01-19 07:51:42 +0000651 }
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000652
James Molloy556763d2014-05-16 14:14:30 +0000653 if (!TL->isLegalAddImmediate(Offset))
654 // FIXME: Try add with register operand?
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000655 return nullptr; // Probably not worth it then.
656
657 // We can only append a kill flag to the add/sub input if the value is not
658 // used in the register list of the stm as well.
659 bool KillOldBase = BaseKill &&
660 (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
James Molloy556763d2014-05-16 14:14:30 +0000661
662 if (isThumb1) {
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000663 // Thumb1: depending on immediate size, use either
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000664 // ADDS NewBase, Base, #imm3
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000665 // or
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000666 // MOV NewBase, Base
667 // ADDS NewBase, #imm8.
Renato Golinb9887ef2015-02-25 14:41:06 +0000668 if (Base != NewBase &&
669 (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
James Molloy556763d2014-05-16 14:14:30 +0000670 // Need to insert a MOV to the new base first.
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000671 if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
Eric Christopher1b21f002015-01-29 00:19:33 +0000672 !STI->hasV6Ops()) {
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000673 // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
674 if (Pred != ARMCC::AL)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000675 return nullptr;
676 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
677 .addReg(Base, getKillRegState(KillOldBase));
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000678 } else
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000679 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
680 .addReg(Base, getKillRegState(KillOldBase))
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000681 .addImm(Pred).addReg(PredReg);
682
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000683 // The following ADDS/SUBS becomes an update.
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000684 Base = NewBase;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000685 KillOldBase = true;
James Molloy556763d2014-05-16 14:14:30 +0000686 }
Renato Golinb9887ef2015-02-25 14:41:06 +0000687 if (BaseOpc == ARM::tADDrSPi) {
688 assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000689 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
690 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset/4)
Renato Golinb9887ef2015-02-25 14:41:06 +0000691 .addImm(Pred).addReg(PredReg);
692 } else
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000693 AddDefaultT1CC(
694 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase), true)
695 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
Renato Golinb9887ef2015-02-25 14:41:06 +0000696 .addImm(Pred).addReg(PredReg);
James Molloy556763d2014-05-16 14:14:30 +0000697 } else {
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000698 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
699 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
James Molloy556763d2014-05-16 14:14:30 +0000700 .addImm(Pred).addReg(PredReg).addReg(0);
701 }
Evan Cheng10043e22007-01-19 07:51:42 +0000702 Base = NewBase;
James Molloybb73c232014-05-16 14:08:46 +0000703 BaseKill = true; // New base is always killed straight away.
Evan Cheng10043e22007-01-19 07:51:42 +0000704 }
705
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000706 bool isDef = isLoadSingle(Opcode);
James Molloy556763d2014-05-16 14:14:30 +0000707
708 // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
709 // base register writeback.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000710 Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000711 if (!Opcode)
712 return nullptr;
James Molloy556763d2014-05-16 14:14:30 +0000713
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000714 // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
715 // - There is no writeback (LDM of base register),
716 // - the base register is killed by the merged instruction,
717 // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
718 // to reset the base register.
719 // Otherwise, don't merge.
720 // It's safe to return here since the code to materialize a new base register
721 // above is also conditional on SafeToClobberCPSR.
722 if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000723 return nullptr;
Moritz Roth8f376562014-08-15 17:00:30 +0000724
James Molloy556763d2014-05-16 14:14:30 +0000725 MachineInstrBuilder MIB;
726
727 if (Writeback) {
728 if (Opcode == ARM::tLDMIA)
729 // Update tLDMIA with writeback if necessary.
730 Opcode = ARM::tLDMIA_UPD;
731
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000732 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
James Molloy556763d2014-05-16 14:14:30 +0000733
734 // Thumb1: we might need to set base writeback when building the MI.
735 MIB.addReg(Base, getDefRegState(true))
736 .addReg(Base, getKillRegState(BaseKill));
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000737
738 // The base isn't dead after a merged instruction with writeback.
739 // Insert a sub instruction after the newly formed instruction to reset.
740 if (!BaseKill)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000741 UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000742
James Molloy556763d2014-05-16 14:14:30 +0000743 } else {
744 // No writeback, simply build the MachineInstr.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000745 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
James Molloy556763d2014-05-16 14:14:30 +0000746 MIB.addReg(Base, getKillRegState(BaseKill));
747 }
748
749 MIB.addImm(Pred).addReg(PredReg);
750
Matthias Braunaa9fa352015-05-27 05:12:40 +0000751 for (const std::pair<unsigned, bool> &R : Regs)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000752 MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
Evan Cheng10043e22007-01-19 07:51:42 +0000753
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000754 return MIB.getInstr();
Tim Northover569f69d2013-10-10 09:28:20 +0000755}
756
Matthias Braune40d89e2015-07-21 00:18:59 +0000757MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(MachineBasicBlock &MBB,
758 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
759 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
760 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const {
761 bool IsLoad = isi32Load(Opcode);
762 assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
763 unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
764
765 assert(Regs.size() == 2);
766 MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
767 TII->get(LoadStoreOpcode));
768 if (IsLoad) {
769 MIB.addReg(Regs[0].first, RegState::Define)
770 .addReg(Regs[1].first, RegState::Define);
771 } else {
772 MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
773 .addReg(Regs[1].first, getKillRegState(Regs[1].second));
774 }
775 MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
776 return MIB.getInstr();
777}
778
Matthias Braunec50fa62015-06-01 21:26:23 +0000779/// Call MergeOps and update MemOps and merges accordingly on success.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000780MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
781 const MachineInstr *First = Cand.Instrs.front();
782 unsigned Opcode = First->getOpcode();
783 bool IsLoad = isLoadSingle(Opcode);
Evan Cheng1fb4de82010-06-21 21:21:14 +0000784 SmallVector<std::pair<unsigned, bool>, 8> Regs;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000785 SmallVector<unsigned, 4> ImpDefs;
786 DenseSet<unsigned> KilledRegs;
Pete Coopere3c81612015-07-16 00:09:18 +0000787 DenseSet<unsigned> UsedRegs;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000788 // Determine list of registers and list of implicit super-register defs.
789 for (const MachineInstr *MI : Cand.Instrs) {
790 const MachineOperand &MO = getLoadStoreRegOp(*MI);
791 unsigned Reg = MO.getReg();
792 bool IsKill = MO.isKill();
793 if (IsKill)
794 KilledRegs.insert(Reg);
795 Regs.push_back(std::make_pair(Reg, IsKill));
Pete Coopere3c81612015-07-16 00:09:18 +0000796 UsedRegs.insert(Reg);
Jakob Stoklund Olesencdee3262012-03-28 22:50:56 +0000797
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000798 if (IsLoad) {
799 // Collect any implicit defs of super-registers, after merging we can't
800 // be sure anymore that we properly preserved these live ranges and must
801 // removed these implicit operands.
802 for (const MachineOperand &MO : MI->implicit_operands()) {
803 if (!MO.isReg() || !MO.isDef() || MO.isDead())
804 continue;
805 assert(MO.isImplicit());
806 unsigned DefReg = MO.getReg();
807
808 if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) != ImpDefs.end())
809 continue;
810 // We can ignore cases where the super-reg is read and written.
811 if (MI->readsRegister(DefReg))
812 continue;
Jakob Stoklund Olesencdee3262012-03-28 22:50:56 +0000813 ImpDefs.push_back(DefReg);
Evan Cheng1fb4de82010-06-21 21:21:14 +0000814 }
815 }
Jakob Stoklund Olesen655e4e62009-12-23 21:28:23 +0000816 }
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000817
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000818 // Attempt the merge.
819 typedef MachineBasicBlock::iterator iterator;
820 MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
821 iterator InsertBefore = std::next(iterator(LatestMI));
822 MachineBasicBlock &MBB = *LatestMI->getParent();
823 unsigned Offset = getMemoryOpOffset(First);
824 unsigned Base = getLoadStoreBaseOp(*First).getReg();
825 bool BaseKill = LatestMI->killsRegister(Base);
826 unsigned PredReg = 0;
827 ARMCC::CondCodes Pred = getInstrPredicate(First, PredReg);
828 DebugLoc DL = First->getDebugLoc();
Matthias Braune40d89e2015-07-21 00:18:59 +0000829 MachineInstr *Merged = nullptr;
830 if (Cand.CanMergeToLSDouble)
831 Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
832 Opcode, Pred, PredReg, DL, Regs);
833 if (!Merged && Cand.CanMergeToLSMulti)
834 Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000835 Opcode, Pred, PredReg, DL, Regs);
836 if (!Merged)
837 return nullptr;
838
839 // Determine earliest instruction that will get removed. We then keep an
840 // iterator just above it so the following erases don't invalidated it.
841 iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
842 bool EarliestAtBegin = false;
843 if (EarliestI == MBB.begin()) {
844 EarliestAtBegin = true;
845 } else {
846 EarliestI = std::prev(EarliestI);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000847 }
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000848
849 // Remove instructions which have been merged.
850 for (MachineInstr *MI : Cand.Instrs)
851 MBB.erase(MI);
852
853 // Determine range between the earliest removed instruction and the new one.
854 if (EarliestAtBegin)
855 EarliestI = MBB.begin();
856 else
857 EarliestI = std::next(EarliestI);
858 auto FixupRange = make_range(EarliestI, iterator(Merged));
859
860 if (isLoadSingle(Opcode)) {
861 // If the previous loads defined a super-reg, then we have to mark earlier
862 // operands undef; Replicate the super-reg def on the merged instruction.
863 for (MachineInstr &MI : FixupRange) {
864 for (unsigned &ImpDefReg : ImpDefs) {
865 for (MachineOperand &MO : MI.implicit_operands()) {
866 if (!MO.isReg() || MO.getReg() != ImpDefReg)
867 continue;
868 if (MO.readsReg())
869 MO.setIsUndef();
870 else if (MO.isDef())
871 ImpDefReg = 0;
872 }
873 }
874 }
875
876 MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
877 for (unsigned ImpDef : ImpDefs)
878 MIB.addReg(ImpDef, RegState::ImplicitDefine);
879 } else {
880 // Remove kill flags: We are possibly storing the values later now.
881 assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
882 for (MachineInstr &MI : FixupRange) {
883 for (MachineOperand &MO : MI.uses()) {
884 if (!MO.isReg() || !MO.isKill())
885 continue;
Pete Coopere3c81612015-07-16 00:09:18 +0000886 if (UsedRegs.count(MO.getReg()))
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000887 MO.setIsKill(false);
888 }
889 }
890 assert(ImpDefs.empty());
891 }
892
893 return Merged;
Jakob Stoklund Olesen655e4e62009-12-23 21:28:23 +0000894}
895
Matthias Braune40d89e2015-07-21 00:18:59 +0000896static bool isValidLSDoubleOffset(int Offset) {
897 unsigned Value = abs(Offset);
898 // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
899 // multiplied by 4.
900 return (Value % 4) == 0 && Value < 1024;
901}
902
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000903/// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
904void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
905 const MachineInstr *FirstMI = MemOps[0].MI;
906 unsigned Opcode = FirstMI->getOpcode();
Bob Wilson13ce07f2010-08-27 23:18:17 +0000907 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000908 unsigned Size = getLSMultipleTransferSize(FirstMI);
Evan Cheng0f7cbe82007-05-15 01:29:07 +0000909
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000910 unsigned SIndex = 0;
911 unsigned EIndex = MemOps.size();
912 do {
913 // Look at the first instruction.
914 const MachineInstr *MI = MemOps[SIndex].MI;
915 int Offset = MemOps[SIndex].Offset;
916 const MachineOperand &PMO = getLoadStoreRegOp(*MI);
917 unsigned PReg = PMO.getReg();
918 unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
919 unsigned Latest = SIndex;
920 unsigned Earliest = SIndex;
921 unsigned Count = 1;
Matthias Braune40d89e2015-07-21 00:18:59 +0000922 bool CanMergeToLSDouble =
923 STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
924 // ARM errata 602117: LDRD with base in list may result in incorrect base
925 // register when interrupted or faulted.
926 if (STI->isCortexM3() && isi32Load(Opcode) &&
927 PReg == getLoadStoreBaseOp(*MI).getReg())
928 CanMergeToLSDouble = false;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000929
Matthias Braune40d89e2015-07-21 00:18:59 +0000930 bool CanMergeToLSMulti = true;
931 // On swift vldm/vstm starting with an odd register number as that needs
932 // more uops than single vldrs.
933 if (STI->isSwift() && !isNotVFP && (PRegNum % 2) == 1)
934 CanMergeToLSMulti = false;
935
936 // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
937 // deprecated; LDM to PC is fine but cannot happen here.
938 if (PReg == ARM::SP || PReg == ARM::PC)
939 CanMergeToLSMulti = CanMergeToLSDouble = false;
940
941 // Merge following instructions where possible.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000942 for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
943 int NewOffset = MemOps[I].Offset;
944 if (NewOffset != Offset + (int)Size)
945 break;
946 const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
947 unsigned Reg = MO.getReg();
Matthias Braune40d89e2015-07-21 00:18:59 +0000948 if (Reg == ARM::SP || Reg == ARM::PC)
Matthias Braun731e3592015-07-20 23:17:20 +0000949 break;
950
Matthias Braune40d89e2015-07-21 00:18:59 +0000951 // See if the current load/store may be part of a multi load/store.
952 unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
953 bool PartOfLSMulti = CanMergeToLSMulti;
954 if (PartOfLSMulti) {
955 // Register numbers must be in ascending order.
956 if (RegNum <= PRegNum)
957 PartOfLSMulti = false;
958 // For VFP / NEON load/store multiples, the registers must be
959 // consecutive and within the limit on the number of registers per
960 // instruction.
961 else if (!isNotVFP && RegNum != PRegNum+1)
962 PartOfLSMulti = false;
963 }
964 // See if the current load/store may be part of a double load/store.
965 bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
966
967 if (!PartOfLSMulti && !PartOfLSDouble)
968 break;
969 CanMergeToLSMulti &= PartOfLSMulti;
970 CanMergeToLSDouble &= PartOfLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000971 // Track MemOp with latest and earliest position (Positions are
972 // counted in reverse).
973 unsigned Position = MemOps[I].Position;
974 if (Position < MemOps[Latest].Position)
975 Latest = I;
976 else if (Position > MemOps[Earliest].Position)
977 Earliest = I;
978 // Prepare for next MemOp.
Evan Cheng10043e22007-01-19 07:51:42 +0000979 Offset += Size;
Evan Cheng10043e22007-01-19 07:51:42 +0000980 PRegNum = RegNum;
Evan Cheng10043e22007-01-19 07:51:42 +0000981 }
982
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000983 // Form a candidate from the Ops collected so far.
Matthias Braune40d89e2015-07-21 00:18:59 +0000984 MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000985 for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
986 Candidate->Instrs.push_back(MemOps[C].MI);
987 Candidate->LatestMIIdx = Latest - SIndex;
988 Candidate->EarliestMIIdx = Earliest - SIndex;
989 Candidate->InsertPos = MemOps[Latest].Position;
Matthias Braune40d89e2015-07-21 00:18:59 +0000990 if (Count == 1)
991 CanMergeToLSMulti = CanMergeToLSDouble = false;
992 Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
993 Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000994 Candidates.push_back(Candidate);
995 // Continue after the chain.
996 SIndex += Count;
997 } while (SIndex < EIndex);
Evan Cheng10043e22007-01-19 07:51:42 +0000998}
999
Matthias Braun84e28972015-07-20 23:17:16 +00001000static bool isMatchingDecrement(MachineInstr *MI, unsigned Base,
1001 unsigned Bytes, unsigned Limit,
1002 ARMCC::CondCodes Pred, unsigned PredReg) {
1003 unsigned MyPredReg = 0;
1004 if (!MI)
1005 return false;
1006
1007 bool CheckCPSRDef = false;
1008 switch (MI->getOpcode()) {
1009 default: return false;
1010 case ARM::tSUBi8:
1011 case ARM::t2SUBri:
1012 case ARM::SUBri:
1013 CheckCPSRDef = true;
1014 break;
1015 case ARM::tSUBspi:
1016 break;
1017 }
1018
1019 // Make sure the offset fits in 8 bits.
1020 if (Bytes == 0 || (Limit && Bytes >= Limit))
1021 return false;
1022
1023 unsigned Scale = (MI->getOpcode() == ARM::tSUBspi ||
1024 MI->getOpcode() == ARM::tSUBi8) ? 4 : 1; // FIXME
1025 if (!(MI->getOperand(0).getReg() == Base &&
1026 MI->getOperand(1).getReg() == Base &&
1027 (MI->getOperand(2).getImm() * Scale) == Bytes &&
1028 getInstrPredicate(MI, MyPredReg) == Pred &&
1029 MyPredReg == PredReg))
1030 return false;
1031
1032 return CheckCPSRDef ? !definesCPSR(MI) : true;
1033}
1034
1035static bool isMatchingIncrement(MachineInstr *MI, unsigned Base,
1036 unsigned Bytes, unsigned Limit,
1037 ARMCC::CondCodes Pred, unsigned PredReg) {
1038 unsigned MyPredReg = 0;
1039 if (!MI)
1040 return false;
1041
1042 bool CheckCPSRDef = false;
1043 switch (MI->getOpcode()) {
1044 default: return false;
1045 case ARM::tADDi8:
1046 case ARM::t2ADDri:
1047 case ARM::ADDri:
1048 CheckCPSRDef = true;
1049 break;
1050 case ARM::tADDspi:
1051 break;
1052 }
1053
1054 if (Bytes == 0 || (Limit && Bytes >= Limit))
1055 // Make sure the offset fits in 8 bits.
1056 return false;
1057
1058 unsigned Scale = (MI->getOpcode() == ARM::tADDspi ||
1059 MI->getOpcode() == ARM::tADDi8) ? 4 : 1; // FIXME
1060 if (!(MI->getOperand(0).getReg() == Base &&
1061 MI->getOperand(1).getReg() == Base &&
1062 (MI->getOperand(2).getImm() * Scale) == Bytes &&
1063 getInstrPredicate(MI, MyPredReg) == Pred &&
1064 MyPredReg == PredReg))
1065 return false;
1066
1067 return CheckCPSRDef ? !definesCPSR(MI) : true;
1068}
1069
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001070static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1071 ARM_AM::AMSubMode Mode) {
Bob Wilson947f04b2010-03-13 01:08:20 +00001072 switch (Opc) {
Bob Wilson947f04b2010-03-13 01:08:20 +00001073 default: llvm_unreachable("Unhandled opcode!");
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001074 case ARM::LDMIA:
1075 case ARM::LDMDA:
1076 case ARM::LDMDB:
1077 case ARM::LDMIB:
1078 switch (Mode) {
1079 default: llvm_unreachable("Unhandled submode!");
1080 case ARM_AM::ia: return ARM::LDMIA_UPD;
1081 case ARM_AM::ib: return ARM::LDMIB_UPD;
1082 case ARM_AM::da: return ARM::LDMDA_UPD;
1083 case ARM_AM::db: return ARM::LDMDB_UPD;
1084 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001085 case ARM::STMIA:
1086 case ARM::STMDA:
1087 case ARM::STMDB:
1088 case ARM::STMIB:
1089 switch (Mode) {
1090 default: llvm_unreachable("Unhandled submode!");
1091 case ARM_AM::ia: return ARM::STMIA_UPD;
1092 case ARM_AM::ib: return ARM::STMIB_UPD;
1093 case ARM_AM::da: return ARM::STMDA_UPD;
1094 case ARM_AM::db: return ARM::STMDB_UPD;
1095 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001096 case ARM::t2LDMIA:
1097 case ARM::t2LDMDB:
1098 switch (Mode) {
1099 default: llvm_unreachable("Unhandled submode!");
1100 case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1101 case ARM_AM::db: return ARM::t2LDMDB_UPD;
1102 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001103 case ARM::t2STMIA:
1104 case ARM::t2STMDB:
1105 switch (Mode) {
1106 default: llvm_unreachable("Unhandled submode!");
1107 case ARM_AM::ia: return ARM::t2STMIA_UPD;
1108 case ARM_AM::db: return ARM::t2STMDB_UPD;
1109 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001110 case ARM::VLDMSIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001111 switch (Mode) {
1112 default: llvm_unreachable("Unhandled submode!");
1113 case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1114 case ARM_AM::db: return ARM::VLDMSDB_UPD;
1115 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001116 case ARM::VLDMDIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001117 switch (Mode) {
1118 default: llvm_unreachable("Unhandled submode!");
1119 case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1120 case ARM_AM::db: return ARM::VLDMDDB_UPD;
1121 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001122 case ARM::VSTMSIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001123 switch (Mode) {
1124 default: llvm_unreachable("Unhandled submode!");
1125 case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1126 case ARM_AM::db: return ARM::VSTMSDB_UPD;
1127 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001128 case ARM::VSTMDIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001129 switch (Mode) {
1130 default: llvm_unreachable("Unhandled submode!");
1131 case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1132 case ARM_AM::db: return ARM::VSTMDDB_UPD;
1133 }
Bob Wilson947f04b2010-03-13 01:08:20 +00001134 }
Bob Wilson947f04b2010-03-13 01:08:20 +00001135}
1136
Matthias Braunec50fa62015-06-01 21:26:23 +00001137/// Fold proceeding/trailing inc/dec of base register into the
1138/// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
Evan Cheng10043e22007-01-19 07:51:42 +00001139///
1140/// stmia rn, <ra, rb, rc>
1141/// rn := rn + 4 * 3;
1142/// =>
1143/// stmia rn!, <ra, rb, rc>
1144///
1145/// rn := rn - 4 * 3;
1146/// ldmia rn, <ra, rb, rc>
1147/// =>
1148/// ldmdb rn!, <ra, rb, rc>
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001149bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
James Molloy556763d2014-05-16 14:14:30 +00001150 // Thumb1 is already using updating loads/stores.
1151 if (isThumb1) return false;
1152
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001153 const MachineOperand &BaseOP = MI->getOperand(0);
1154 unsigned Base = BaseOP.getReg();
1155 bool BaseKill = BaseOP.isKill();
Matthias Braun84e28972015-07-20 23:17:16 +00001156 unsigned Bytes = getLSMultipleTransferSize(MI);
Evan Cheng94f04c62007-07-05 07:18:20 +00001157 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001158 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
Matthias Braunfa3872e2015-05-18 20:27:55 +00001159 unsigned Opcode = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001160 DebugLoc DL = MI->getDebugLoc();
Evan Cheng10043e22007-01-19 07:51:42 +00001161
Bob Wilson13ce07f2010-08-27 23:18:17 +00001162 // Can't use an updating ld/st if the base register is also a dest
1163 // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001164 for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
Bob Wilson13ce07f2010-08-27 23:18:17 +00001165 if (MI->getOperand(i).getReg() == Base)
1166 return false;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001167
Matthias Braun84e28972015-07-20 23:17:16 +00001168 bool DoMerge = false;
Matthias Braund9bd22b2015-07-10 18:37:33 +00001169 ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
Matthias Braun84e28972015-07-20 23:17:16 +00001170
1171 // Try merging with the previous instruction.
1172 MachineBasicBlock &MBB = *MI->getParent();
1173 MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1174 MachineBasicBlock::iterator MBBI(MI);
1175 if (MBBI != BeginMBBI) {
1176 MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1177 while (PrevMBBI != BeginMBBI && PrevMBBI->isDebugValue())
1178 --PrevMBBI;
1179 if (Mode == ARM_AM::ia &&
1180 isMatchingDecrement(PrevMBBI, Base, Bytes, 0, Pred, PredReg)) {
1181 Mode = ARM_AM::db;
1182 DoMerge = true;
1183 } else if (Mode == ARM_AM::ib &&
1184 isMatchingDecrement(PrevMBBI, Base, Bytes, 0, Pred, PredReg)) {
1185 Mode = ARM_AM::da;
1186 DoMerge = true;
1187 }
1188 if (DoMerge)
1189 MBB.erase(PrevMBBI);
Bob Wilson947f04b2010-03-13 01:08:20 +00001190 }
Matthias Braun84e28972015-07-20 23:17:16 +00001191
1192 // Try merging with the next instruction.
1193 MachineBasicBlock::iterator EndMBBI = MBB.end();
1194 if (!DoMerge && MBBI != EndMBBI) {
1195 MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1196 while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1197 ++NextMBBI;
1198 if ((Mode == ARM_AM::ia || Mode == ARM_AM::ib) &&
1199 isMatchingIncrement(NextMBBI, Base, Bytes, 0, Pred, PredReg)) {
1200 DoMerge = true;
1201 } else if ((Mode == ARM_AM::da || Mode == ARM_AM::db) &&
1202 isMatchingDecrement(NextMBBI, Base, Bytes, 0, Pred, PredReg)) {
1203 DoMerge = true;
1204 }
1205 if (DoMerge)
1206 MBB.erase(NextMBBI);
1207 }
1208
1209 if (!DoMerge)
1210 return false;
Bob Wilson947f04b2010-03-13 01:08:20 +00001211
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001212 unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001213 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
Bob Wilson947f04b2010-03-13 01:08:20 +00001214 .addReg(Base, getDefRegState(true)) // WB base register
Bob Wilson13ce07f2010-08-27 23:18:17 +00001215 .addReg(Base, getKillRegState(BaseKill))
Bob Wilson13ce07f2010-08-27 23:18:17 +00001216 .addImm(Pred).addReg(PredReg);
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001217
Bob Wilson947f04b2010-03-13 01:08:20 +00001218 // Transfer the rest of operands.
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001219 for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
Bob Wilson947f04b2010-03-13 01:08:20 +00001220 MIB.addOperand(MI->getOperand(OpNum));
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001221
Bob Wilson947f04b2010-03-13 01:08:20 +00001222 // Transfer memoperands.
Chris Lattner1d0c2572011-04-29 05:24:29 +00001223 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Bob Wilson947f04b2010-03-13 01:08:20 +00001224
1225 MBB.erase(MBBI);
1226 return true;
Evan Cheng10043e22007-01-19 07:51:42 +00001227}
1228
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001229static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1230 ARM_AM::AddrOpc Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +00001231 switch (Opc) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001232 case ARM::LDRi12:
Owen Anderson16d33f32011-08-26 20:43:14 +00001233 return ARM::LDR_PRE_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001234 case ARM::STRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001235 return ARM::STR_PRE_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001236 case ARM::VLDRS:
1237 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1238 case ARM::VLDRD:
1239 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1240 case ARM::VSTRS:
1241 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1242 case ARM::VSTRD:
1243 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001244 case ARM::t2LDRi8:
1245 case ARM::t2LDRi12:
1246 return ARM::t2LDR_PRE;
1247 case ARM::t2STRi8:
1248 case ARM::t2STRi12:
1249 return ARM::t2STR_PRE;
Torok Edwinfbcc6632009-07-14 16:55:14 +00001250 default: llvm_unreachable("Unhandled opcode!");
Evan Cheng10043e22007-01-19 07:51:42 +00001251 }
Evan Cheng10043e22007-01-19 07:51:42 +00001252}
1253
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001254static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1255 ARM_AM::AddrOpc Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +00001256 switch (Opc) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001257 case ARM::LDRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001258 return ARM::LDR_POST_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001259 case ARM::STRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001260 return ARM::STR_POST_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001261 case ARM::VLDRS:
1262 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1263 case ARM::VLDRD:
1264 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1265 case ARM::VSTRS:
1266 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1267 case ARM::VSTRD:
1268 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001269 case ARM::t2LDRi8:
1270 case ARM::t2LDRi12:
1271 return ARM::t2LDR_POST;
1272 case ARM::t2STRi8:
1273 case ARM::t2STRi12:
1274 return ARM::t2STR_POST;
Torok Edwinfbcc6632009-07-14 16:55:14 +00001275 default: llvm_unreachable("Unhandled opcode!");
Evan Cheng10043e22007-01-19 07:51:42 +00001276 }
Evan Cheng10043e22007-01-19 07:51:42 +00001277}
1278
Matthias Braunec50fa62015-06-01 21:26:23 +00001279/// Fold proceeding/trailing inc/dec of base register into the
1280/// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001281bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
James Molloy556763d2014-05-16 14:14:30 +00001282 // Thumb1 doesn't have updating LDR/STR.
1283 // FIXME: Use LDM/STM with single register instead.
1284 if (isThumb1) return false;
1285
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001286 unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1287 bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
Matthias Braun84e28972015-07-20 23:17:16 +00001288 unsigned Bytes = getLSMultipleTransferSize(MI);
Matthias Braunfa3872e2015-05-18 20:27:55 +00001289 unsigned Opcode = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001290 DebugLoc DL = MI->getDebugLoc();
Bob Wilsonaf10d272010-03-12 22:50:09 +00001291 bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1292 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
Jim Grosbach338de3e2010-10-27 23:12:14 +00001293 bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1294 if (isi32Load(Opcode) || isi32Store(Opcode))
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00001295 if (MI->getOperand(2).getImm() != 0)
1296 return false;
Bob Wilsonaf10d272010-03-12 22:50:09 +00001297 if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
Evan Cheng4605e8a2009-07-09 23:11:34 +00001298 return false;
Evan Cheng10043e22007-01-19 07:51:42 +00001299
Matthias Braun84e28972015-07-20 23:17:16 +00001300 bool isLd = isLoadSingle(Opcode);
Evan Cheng10043e22007-01-19 07:51:42 +00001301 // Can't do the merge if the destination register is the same as the would-be
1302 // writeback register.
Chad Rosierace9c5d2013-03-25 16:29:20 +00001303 if (MI->getOperand(0).getReg() == Base)
Evan Cheng10043e22007-01-19 07:51:42 +00001304 return false;
1305
Evan Cheng94f04c62007-07-05 07:18:20 +00001306 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001307 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
Matthias Braun84e28972015-07-20 23:17:16 +00001308 bool DoMerge = false;
1309 ARM_AM::AddrOpc AddSub = ARM_AM::add;
1310 unsigned NewOpc = 0;
1311 // AM2 - 12 bits, thumb2 - 8 bits.
1312 unsigned Limit = isAM5 ? 0 : (isAM2 ? 0x1000 : 0x100);
1313
1314 // Try merging with the previous instruction.
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001315 MachineBasicBlock &MBB = *MI->getParent();
Matthias Braun84e28972015-07-20 23:17:16 +00001316 MachineBasicBlock::iterator BeginMBBI = MBB.begin();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001317 MachineBasicBlock::iterator MBBI(MI);
Matthias Braun84e28972015-07-20 23:17:16 +00001318 if (MBBI != BeginMBBI) {
1319 MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1320 while (PrevMBBI != BeginMBBI && PrevMBBI->isDebugValue())
1321 --PrevMBBI;
1322 if (isMatchingDecrement(PrevMBBI, Base, Bytes, Limit, Pred, PredReg)) {
1323 DoMerge = true;
1324 AddSub = ARM_AM::sub;
1325 } else if (!isAM5 &&
1326 isMatchingIncrement(PrevMBBI, Base, Bytes, Limit,Pred,PredReg)) {
1327 DoMerge = true;
1328 }
1329 if (DoMerge) {
1330 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, AddSub);
1331 MBB.erase(PrevMBBI);
1332 }
Evan Cheng10043e22007-01-19 07:51:42 +00001333 }
1334
Matthias Braun84e28972015-07-20 23:17:16 +00001335 // Try merging with the next instruction.
1336 MachineBasicBlock::iterator EndMBBI = MBB.end();
1337 if (!DoMerge && MBBI != EndMBBI) {
1338 MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1339 while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1340 ++NextMBBI;
1341 if (!isAM5 &&
1342 isMatchingDecrement(NextMBBI, Base, Bytes, Limit, Pred, PredReg)) {
1343 DoMerge = true;
1344 AddSub = ARM_AM::sub;
1345 } else if (isMatchingIncrement(NextMBBI, Base, Bytes, Limit,Pred,PredReg)) {
1346 DoMerge = true;
1347 }
1348 if (DoMerge) {
1349 NewOpc = getPostIndexedLoadStoreOpcode(Opcode, AddSub);
1350 MBB.erase(NextMBBI);
1351 }
1352 }
Evan Cheng10043e22007-01-19 07:51:42 +00001353
Matthias Braun84e28972015-07-20 23:17:16 +00001354 if (!DoMerge)
1355 return false;
1356
Bob Wilson53149402010-03-13 00:43:32 +00001357 if (isAM5) {
James Molloybb73c232014-05-16 14:08:46 +00001358 // VLDM[SD]_UPD, VSTM[SD]_UPD
Bob Wilson13ce07f2010-08-27 23:18:17 +00001359 // (There are no base-updating versions of VLDR/VSTR instructions, but the
1360 // updating load/store-multiple instructions can be used with only one
1361 // register.)
Bob Wilson53149402010-03-13 00:43:32 +00001362 MachineOperand &MO = MI->getOperand(0);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001363 BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
Bob Wilson947f04b2010-03-13 01:08:20 +00001364 .addReg(Base, getDefRegState(true)) // WB base register
Bob Wilson53149402010-03-13 00:43:32 +00001365 .addReg(Base, getKillRegState(isLd ? BaseKill : false))
Bob Wilson53149402010-03-13 00:43:32 +00001366 .addImm(Pred).addReg(PredReg)
Bob Wilson53149402010-03-13 00:43:32 +00001367 .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1368 getKillRegState(MO.isKill())));
1369 } else if (isLd) {
Jim Grosbach23254742011-08-12 22:20:41 +00001370 if (isAM2) {
Owen Anderson63143432011-08-29 17:59:41 +00001371 // LDR_PRE, LDR_POST
1372 if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
Matthias Braun84e28972015-07-20 23:17:16 +00001373 int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001374 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Owen Anderson63143432011-08-29 17:59:41 +00001375 .addReg(Base, RegState::Define)
1376 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1377 } else {
Matthias Braun84e28972015-07-20 23:17:16 +00001378 int Offset = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001379 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Owen Anderson63143432011-08-29 17:59:41 +00001380 .addReg(Base, RegState::Define)
Matthias Braun84e28972015-07-20 23:17:16 +00001381 .addReg(Base).addReg(0).addImm(Offset).addImm(Pred).addReg(PredReg);
Owen Anderson63143432011-08-29 17:59:41 +00001382 }
Jim Grosbach23254742011-08-12 22:20:41 +00001383 } else {
Matthias Braun84e28972015-07-20 23:17:16 +00001384 int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
Evan Cheng71756e72009-08-04 01:43:45 +00001385 // t2LDR_PRE, t2LDR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001386 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Evan Cheng71756e72009-08-04 01:43:45 +00001387 .addReg(Base, RegState::Define)
1388 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001389 }
Evan Cheng71756e72009-08-04 01:43:45 +00001390 } else {
1391 MachineOperand &MO = MI->getOperand(0);
Jim Grosbachf0c95ca2011-08-05 20:35:44 +00001392 // FIXME: post-indexed stores use am2offset_imm, which still encodes
1393 // the vestigal zero-reg offset register. When that's fixed, this clause
1394 // can be removed entirely.
Jim Grosbach23254742011-08-12 22:20:41 +00001395 if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
Matthias Braun84e28972015-07-20 23:17:16 +00001396 int Offset = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
Evan Cheng71756e72009-08-04 01:43:45 +00001397 // STR_PRE, STR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001398 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
Evan Cheng71756e72009-08-04 01:43:45 +00001399 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
Matthias Braun84e28972015-07-20 23:17:16 +00001400 .addReg(Base).addReg(0).addImm(Offset).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001401 } else {
Matthias Braun84e28972015-07-20 23:17:16 +00001402 int Offset = AddSub == ARM_AM::sub ? -Bytes : Bytes;
Evan Cheng71756e72009-08-04 01:43:45 +00001403 // t2STR_PRE, t2STR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001404 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
Evan Cheng71756e72009-08-04 01:43:45 +00001405 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1406 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001407 }
Evan Cheng10043e22007-01-19 07:51:42 +00001408 }
1409 MBB.erase(MBBI);
1410
1411 return true;
1412}
1413
Matthias Braunec50fa62015-06-01 21:26:23 +00001414/// Returns true if instruction is a memory operation that this pass is capable
1415/// of operating on.
Evan Cheng4605e8a2009-07-09 23:11:34 +00001416static bool isMemoryOp(const MachineInstr *MI) {
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001417 // When no memory operands are present, conservatively assume unaligned,
1418 // volatile, unfoldable.
1419 if (!MI->hasOneMemOperand())
1420 return false;
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001421
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001422 const MachineMemOperand *MMO = *MI->memoperands_begin();
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001423
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001424 // Don't touch volatile memory accesses - we may be changing their order.
1425 if (MMO->isVolatile())
1426 return false;
1427
1428 // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1429 // not.
1430 if (MMO->getAlignment() < 4)
1431 return false;
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001432
Jakob Stoklund Olesen0b94eb12010-02-24 18:57:08 +00001433 // str <undef> could probably be eliminated entirely, but for now we just want
1434 // to avoid making a mess of it.
1435 // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1436 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg() &&
1437 MI->getOperand(0).isUndef())
1438 return false;
1439
Bob Wilsoncf6e29a2010-03-04 21:04:38 +00001440 // Likewise don't mess with references to undefined addresses.
1441 if (MI->getNumOperands() > 1 && MI->getOperand(1).isReg() &&
1442 MI->getOperand(1).isUndef())
1443 return false;
1444
Matthias Braunfa3872e2015-05-18 20:27:55 +00001445 unsigned Opcode = MI->getOpcode();
Evan Chengd28de672007-03-06 18:02:41 +00001446 switch (Opcode) {
1447 default: break;
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001448 case ARM::VLDRS:
1449 case ARM::VSTRS:
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001450 return MI->getOperand(1).isReg();
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001451 case ARM::VLDRD:
1452 case ARM::VSTRD:
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001453 return MI->getOperand(1).isReg();
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00001454 case ARM::LDRi12:
Jim Grosbach338de3e2010-10-27 23:12:14 +00001455 case ARM::STRi12:
James Molloy556763d2014-05-16 14:14:30 +00001456 case ARM::tLDRi:
1457 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +00001458 case ARM::tLDRspi:
1459 case ARM::tSTRspi:
Evan Cheng4605e8a2009-07-09 23:11:34 +00001460 case ARM::t2LDRi8:
1461 case ARM::t2LDRi12:
1462 case ARM::t2STRi8:
1463 case ARM::t2STRi12:
Evan Chenga6b9cab2009-09-27 09:46:04 +00001464 return MI->getOperand(1).isReg();
Evan Chengd28de672007-03-06 18:02:41 +00001465 }
1466 return false;
1467}
1468
Evan Cheng1283c6a2009-06-15 08:28:29 +00001469static void InsertLDR_STR(MachineBasicBlock &MBB,
1470 MachineBasicBlock::iterator &MBBI,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001471 int Offset, bool isDef,
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001472 DebugLoc DL, unsigned NewOpc,
Evan Chenga6b9cab2009-09-27 09:46:04 +00001473 unsigned Reg, bool RegDeadKill, bool RegUndef,
1474 unsigned BaseReg, bool BaseKill, bool BaseUndef,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001475 bool OffKill, bool OffUndef,
Evan Cheng1283c6a2009-06-15 08:28:29 +00001476 ARMCC::CondCodes Pred, unsigned PredReg,
Evan Chenga6b9cab2009-09-27 09:46:04 +00001477 const TargetInstrInfo *TII, bool isT2) {
Evan Chenga6b9cab2009-09-27 09:46:04 +00001478 if (isDef) {
1479 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1480 TII->get(NewOpc))
Evan Cheng5d8df7f2009-06-19 01:59:04 +00001481 .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
Evan Chenga6b9cab2009-09-27 09:46:04 +00001482 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
Evan Chenga6b9cab2009-09-27 09:46:04 +00001483 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1484 } else {
1485 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1486 TII->get(NewOpc))
1487 .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1488 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
Evan Chenga6b9cab2009-09-27 09:46:04 +00001489 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1490 }
Evan Cheng1283c6a2009-06-15 08:28:29 +00001491}
1492
1493bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1494 MachineBasicBlock::iterator &MBBI) {
1495 MachineInstr *MI = &*MBBI;
1496 unsigned Opcode = MI->getOpcode();
Matthias Braunba3ecc32015-06-24 20:03:27 +00001497 if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1498 return false;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001499
Matthias Braunba3ecc32015-06-24 20:03:27 +00001500 const MachineOperand &BaseOp = MI->getOperand(2);
1501 unsigned BaseReg = BaseOp.getReg();
1502 unsigned EvenReg = MI->getOperand(0).getReg();
1503 unsigned OddReg = MI->getOperand(1).getReg();
1504 unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1505 unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
Evan Cheng1283c6a2009-06-15 08:28:29 +00001506
Matthias Braunba3ecc32015-06-24 20:03:27 +00001507 // ARM errata 602117: LDRD with base in list may result in incorrect base
1508 // register when interrupted or faulted.
1509 bool Errata602117 = EvenReg == BaseReg &&
1510 (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1511 // ARM LDRD/STRD needs consecutive registers.
1512 bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1513 (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1514
1515 if (!Errata602117 && !NonConsecutiveRegs)
1516 return false;
1517
Matthias Braunba3ecc32015-06-24 20:03:27 +00001518 bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1519 bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1520 bool EvenDeadKill = isLd ?
1521 MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1522 bool EvenUndef = MI->getOperand(0).isUndef();
1523 bool OddDeadKill = isLd ?
1524 MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1525 bool OddUndef = MI->getOperand(1).isUndef();
1526 bool BaseKill = BaseOp.isKill();
1527 bool BaseUndef = BaseOp.isUndef();
1528 bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
1529 bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
1530 int OffImm = getMemoryOpOffset(MI);
1531 unsigned PredReg = 0;
1532 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1533
1534 if (OddRegNum > EvenRegNum && OffImm == 0) {
1535 // Ascending register numbers and no offset. It's safe to change it to a
1536 // ldm or stm.
1537 unsigned NewOpc = (isLd)
1538 ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1539 : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1540 if (isLd) {
1541 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1542 .addReg(BaseReg, getKillRegState(BaseKill))
1543 .addImm(Pred).addReg(PredReg)
1544 .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1545 .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill));
1546 ++NumLDRD2LDM;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001547 } else {
Matthias Braunba3ecc32015-06-24 20:03:27 +00001548 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1549 .addReg(BaseReg, getKillRegState(BaseKill))
1550 .addImm(Pred).addReg(PredReg)
1551 .addReg(EvenReg,
1552 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1553 .addReg(OddReg,
1554 getKillRegState(OddDeadKill) | getUndefRegState(OddUndef));
1555 ++NumSTRD2STM;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001556 }
Matthias Braunba3ecc32015-06-24 20:03:27 +00001557 } else {
1558 // Split into two instructions.
1559 unsigned NewOpc = (isLd)
1560 ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1561 : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1562 // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1563 // so adjust and use t2LDRi12 here for that.
1564 unsigned NewOpc2 = (isLd)
1565 ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1566 : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1567 DebugLoc dl = MBBI->getDebugLoc();
1568 // If this is a load and base register is killed, it may have been
1569 // re-defed by the load, make sure the first load does not clobber it.
1570 if (isLd &&
1571 (BaseKill || OffKill) &&
1572 (TRI->regsOverlap(EvenReg, BaseReg))) {
1573 assert(!TRI->regsOverlap(OddReg, BaseReg));
1574 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1575 OddReg, OddDeadKill, false,
1576 BaseReg, false, BaseUndef, false, OffUndef,
1577 Pred, PredReg, TII, isT2);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001578 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1579 EvenReg, EvenDeadKill, false,
1580 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1581 Pred, PredReg, TII, isT2);
1582 } else {
1583 if (OddReg == EvenReg && EvenDeadKill) {
1584 // If the two source operands are the same, the kill marker is
1585 // probably on the first one. e.g.
1586 // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
1587 EvenDeadKill = false;
1588 OddDeadKill = true;
1589 }
1590 // Never kill the base register in the first instruction.
1591 if (EvenReg == BaseReg)
1592 EvenDeadKill = false;
1593 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1594 EvenReg, EvenDeadKill, EvenUndef,
1595 BaseReg, false, BaseUndef, false, OffUndef,
1596 Pred, PredReg, TII, isT2);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001597 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1598 OddReg, OddDeadKill, OddUndef,
1599 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1600 Pred, PredReg, TII, isT2);
1601 }
1602 if (isLd)
1603 ++NumLDRD2LDR;
1604 else
1605 ++NumSTRD2STR;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001606 }
Matthias Braunba3ecc32015-06-24 20:03:27 +00001607
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001608 MBBI = MBB.erase(MBBI);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001609 return true;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001610}
1611
Matthias Braunec50fa62015-06-01 21:26:23 +00001612/// An optimization pass to turn multiple LDR / STR ops of the same base and
1613/// incrementing offset into LDM / STM ops.
Evan Cheng10043e22007-01-19 07:51:42 +00001614bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +00001615 MemOpQueue MemOps;
1616 unsigned CurrBase = 0;
Matthias Braunfa3872e2015-05-18 20:27:55 +00001617 unsigned CurrOpc = ~0u;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001618 ARMCC::CondCodes CurrPred = ARMCC::AL;
Evan Cheng10043e22007-01-19 07:51:42 +00001619 unsigned Position = 0;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001620 assert(Candidates.size() == 0);
1621 LiveRegsValid = false;
Evan Chengd28de672007-03-06 18:02:41 +00001622
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001623 for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1624 I = MBBI) {
1625 // The instruction in front of the iterator is the one we look at.
1626 MBBI = std::prev(I);
Evan Cheng1283c6a2009-06-15 08:28:29 +00001627 if (FixInvalidRegPairOp(MBB, MBBI))
1628 continue;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001629 ++Position;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001630
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001631 if (isMemoryOp(MBBI)) {
Matthias Braunfa3872e2015-05-18 20:27:55 +00001632 unsigned Opcode = MBBI->getOpcode();
Evan Cheng1fb4de82010-06-21 21:21:14 +00001633 const MachineOperand &MO = MBBI->getOperand(0);
1634 unsigned Reg = MO.getReg();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001635 unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
Evan Cheng94f04c62007-07-05 07:18:20 +00001636 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001637 ARMCC::CondCodes Pred = getInstrPredicate(MBBI, PredReg);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001638 int Offset = getMemoryOpOffset(MBBI);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001639 if (CurrBase == 0) {
Evan Cheng10043e22007-01-19 07:51:42 +00001640 // Start of a new chain.
1641 CurrBase = Base;
1642 CurrOpc = Opcode;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001643 CurrPred = Pred;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001644 MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
1645 continue;
1646 }
1647 // Note: No need to match PredReg in the next if.
1648 if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1649 // Watch out for:
1650 // r4 := ldr [r0, #8]
1651 // r4 := ldr [r0, #4]
1652 // or
1653 // r0 := ldr [r0]
1654 // If a load overrides the base register or a register loaded by
1655 // another load in our chain, we cannot take this instruction.
1656 bool Overlap = false;
1657 if (isLoadSingle(Opcode)) {
1658 Overlap = (Base == Reg);
1659 if (!Overlap) {
1660 for (const MemOpQueueEntry &E : MemOps) {
1661 if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1662 Overlap = true;
Evan Cheng10043e22007-01-19 07:51:42 +00001663 break;
1664 }
1665 }
1666 }
1667 }
Evan Cheng10043e22007-01-19 07:51:42 +00001668
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001669 if (!Overlap) {
1670 // Check offset and sort memory operation into the current chain.
1671 if (Offset > MemOps.back().Offset) {
1672 MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
1673 continue;
1674 } else {
1675 MemOpQueue::iterator MI, ME;
1676 for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1677 if (Offset < MI->Offset) {
1678 // Found a place to insert.
1679 break;
1680 }
1681 if (Offset == MI->Offset) {
1682 // Collision, abort.
1683 MI = ME;
1684 break;
1685 }
1686 }
1687 if (MI != MemOps.end()) {
1688 MemOps.insert(MI, MemOpQueueEntry(MBBI, Offset, Position));
1689 continue;
1690 }
1691 }
Evan Cheng7f5976e2009-06-04 01:15:28 +00001692 }
Evan Cheng2818fdd2007-03-07 02:38:05 +00001693 }
Evan Cheng10043e22007-01-19 07:51:42 +00001694
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001695 // Don't advance the iterator; The op will start a new chain next.
1696 MBBI = I;
1697 --Position;
1698 // Fallthrough to look into existing chain.
Matthias Braun84e28972015-07-20 23:17:16 +00001699 } else if (MBBI->isDebugValue())
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001700 continue;
1701
1702 // If we are here then the chain is broken; Extract candidates for a merge.
1703 if (MemOps.size() > 0) {
1704 FormCandidates(MemOps);
1705 // Reset for the next chain.
Evan Cheng10043e22007-01-19 07:51:42 +00001706 CurrBase = 0;
Matthias Braunfa3872e2015-05-18 20:27:55 +00001707 CurrOpc = ~0u;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001708 CurrPred = ARMCC::AL;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001709 MemOps.clear();
Evan Cheng10043e22007-01-19 07:51:42 +00001710 }
1711 }
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001712 if (MemOps.size() > 0)
1713 FormCandidates(MemOps);
1714
1715 // Sort candidates so they get processed from end to begin of the basic
1716 // block later; This is necessary for liveness calculation.
1717 auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1718 return M0->InsertPos < M1->InsertPos;
1719 };
1720 std::sort(Candidates.begin(), Candidates.end(), LessThan);
1721
1722 // Go through list of candidates and merge.
1723 bool Changed = false;
1724 for (const MergeCandidate *Candidate : Candidates) {
Matthias Braune40d89e2015-07-21 00:18:59 +00001725 if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001726 MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1727 // Merge preceding/trailing base inc/dec into the merged op.
1728 if (Merged) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001729 Changed = true;
Matthias Braune40d89e2015-07-21 00:18:59 +00001730 unsigned Opcode = Merged->getOpcode();
1731 if (Opcode != ARM::t2STRDi8 && Opcode != ARM::t2LDRDi8)
1732 MergeBaseUpdateLSMultiple(Merged);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001733 } else {
1734 for (MachineInstr *MI : Candidate->Instrs) {
1735 if (MergeBaseUpdateLoadStore(MI))
1736 Changed = true;
1737 }
1738 }
1739 } else {
1740 assert(Candidate->Instrs.size() == 1);
1741 if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
1742 Changed = true;
1743 }
1744 }
1745 Candidates.clear();
1746
1747 return Changed;
Evan Cheng10043e22007-01-19 07:51:42 +00001748}
1749
Matthias Braunec50fa62015-06-01 21:26:23 +00001750/// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
1751/// into the preceding stack restore so it directly restore the value of LR
1752/// into pc.
Bob Wilson162242b2010-03-20 22:20:40 +00001753/// ldmfd sp!, {..., lr}
Evan Cheng10043e22007-01-19 07:51:42 +00001754/// bx lr
Bob Wilson162242b2010-03-20 22:20:40 +00001755/// or
1756/// ldmfd sp!, {..., lr}
1757/// mov pc, lr
Evan Cheng10043e22007-01-19 07:51:42 +00001758/// =>
Bob Wilson162242b2010-03-20 22:20:40 +00001759/// ldmfd sp!, {..., pc}
Evan Cheng10043e22007-01-19 07:51:42 +00001760bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
James Molloy556763d2014-05-16 14:14:30 +00001761 // Thumb1 LDM doesn't allow high registers.
1762 if (isThumb1) return false;
Evan Cheng10043e22007-01-19 07:51:42 +00001763 if (MBB.empty()) return false;
1764
Jakob Stoklund Olesenbbb1a542011-01-13 22:47:43 +00001765 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng4605e8a2009-07-09 23:11:34 +00001766 if (MBBI != MBB.begin() &&
Bob Wilson162242b2010-03-20 22:20:40 +00001767 (MBBI->getOpcode() == ARM::BX_RET ||
1768 MBBI->getOpcode() == ARM::tBX_RET ||
1769 MBBI->getOpcode() == ARM::MOVPCLR)) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001770 MachineInstr *PrevMI = std::prev(MBBI);
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001771 unsigned Opcode = PrevMI->getOpcode();
1772 if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
1773 Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
1774 Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
Evan Cheng10043e22007-01-19 07:51:42 +00001775 MachineOperand &MO = PrevMI->getOperand(PrevMI->getNumOperands()-1);
Evan Cheng71756e72009-08-04 01:43:45 +00001776 if (MO.getReg() != ARM::LR)
1777 return false;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001778 unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
1779 assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
1780 Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
Evan Cheng71756e72009-08-04 01:43:45 +00001781 PrevMI->setDesc(TII->get(NewOpc));
1782 MO.setReg(ARM::PC);
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001783 PrevMI->copyImplicitOps(*MBB.getParent(), &*MBBI);
Evan Cheng71756e72009-08-04 01:43:45 +00001784 MBB.erase(MBBI);
1785 return true;
Evan Cheng10043e22007-01-19 07:51:42 +00001786 }
1787 }
1788 return false;
1789}
1790
1791bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001792 MF = &Fn;
Eric Christopher1b21f002015-01-29 00:19:33 +00001793 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1794 TL = STI->getTargetLowering();
Evan Chengf030f2d2007-03-07 20:30:36 +00001795 AFI = Fn.getInfo<ARMFunctionInfo>();
Eric Christopher1b21f002015-01-29 00:19:33 +00001796 TII = STI->getInstrInfo();
1797 TRI = STI->getRegisterInfo();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001798 MRI = &Fn.getRegInfo();
1799 RegClassInfoValid = false;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001800 isThumb2 = AFI->isThumb2Function();
James Molloy92a15072014-05-16 14:11:38 +00001801 isThumb1 = AFI->isThumbFunction() && !isThumb2;
1802
Evan Cheng10043e22007-01-19 07:51:42 +00001803 bool Modified = false;
1804 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1805 ++MFI) {
1806 MachineBasicBlock &MBB = *MFI;
1807 Modified |= LoadStoreMultipleOpti(MBB);
Eric Christopher1b21f002015-01-29 00:19:33 +00001808 if (STI->hasV5TOps())
Bob Wilson914df822011-01-06 19:24:41 +00001809 Modified |= MergeReturnIntoLDM(MBB);
Evan Cheng10043e22007-01-19 07:51:42 +00001810 }
Evan Chengd28de672007-03-06 18:02:41 +00001811
Matthias Braune40d89e2015-07-21 00:18:59 +00001812 Allocator.DestroyAll();
Evan Cheng10043e22007-01-19 07:51:42 +00001813 return Modified;
1814}
Evan Cheng185c9ef2009-06-13 09:12:55 +00001815
Evan Cheng185c9ef2009-06-13 09:12:55 +00001816namespace {
Matthias Braunec50fa62015-06-01 21:26:23 +00001817 /// Pre- register allocation pass that move load / stores from consecutive
1818 /// locations close to make it more likely they will be combined later.
Nick Lewycky02d5f772009-10-25 06:33:48 +00001819 struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
Evan Cheng185c9ef2009-06-13 09:12:55 +00001820 static char ID;
Owen Andersona7aed182010-08-06 18:33:48 +00001821 ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
Evan Cheng185c9ef2009-06-13 09:12:55 +00001822
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001823 const DataLayout *TD;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001824 const TargetInstrInfo *TII;
1825 const TargetRegisterInfo *TRI;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001826 const ARMSubtarget *STI;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001827 MachineRegisterInfo *MRI;
Evan Chengfd6aad72009-09-25 21:44:53 +00001828 MachineFunction *MF;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001829
Craig Topper6bc27bf2014-03-10 02:09:33 +00001830 bool runOnMachineFunction(MachineFunction &Fn) override;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001831
Craig Topper6bc27bf2014-03-10 02:09:33 +00001832 const char *getPassName() const override {
Evan Cheng185c9ef2009-06-13 09:12:55 +00001833 return "ARM pre- register allocation load / store optimization pass";
1834 }
1835
1836 private:
Evan Chengeba57e42009-06-15 20:54:56 +00001837 bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1838 unsigned &NewOpc, unsigned &EvenReg,
1839 unsigned &OddReg, unsigned &BaseReg,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001840 int &Offset,
Evan Chengfd6aad72009-09-25 21:44:53 +00001841 unsigned &PredReg, ARMCC::CondCodes &Pred,
1842 bool &isT2);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001843 bool RescheduleOps(MachineBasicBlock *MBB,
Craig Topperaf0dea12013-07-04 01:31:24 +00001844 SmallVectorImpl<MachineInstr *> &Ops,
Evan Cheng185c9ef2009-06-13 09:12:55 +00001845 unsigned Base, bool isLd,
1846 DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1847 bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1848 };
1849 char ARMPreAllocLoadStoreOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001850}
Evan Cheng185c9ef2009-06-13 09:12:55 +00001851
1852bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001853 TD = &Fn.getDataLayout();
Eric Christopher7c558cf2014-10-14 08:44:19 +00001854 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
Eric Christopher1b21f002015-01-29 00:19:33 +00001855 TII = STI->getInstrInfo();
1856 TRI = STI->getRegisterInfo();
Evan Cheng185c9ef2009-06-13 09:12:55 +00001857 MRI = &Fn.getRegInfo();
Evan Chengfd6aad72009-09-25 21:44:53 +00001858 MF = &Fn;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001859
1860 bool Modified = false;
1861 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1862 ++MFI)
1863 Modified |= RescheduleLoadStoreInstrs(MFI);
1864
1865 return Modified;
1866}
1867
Evan Chengb4b20bb2009-06-19 23:17:27 +00001868static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
1869 MachineBasicBlock::iterator I,
1870 MachineBasicBlock::iterator E,
Craig Topper71b7b682014-08-21 05:55:13 +00001871 SmallPtrSetImpl<MachineInstr*> &MemOps,
Evan Chengb4b20bb2009-06-19 23:17:27 +00001872 SmallSet<unsigned, 4> &MemRegs,
1873 const TargetRegisterInfo *TRI) {
Evan Cheng185c9ef2009-06-13 09:12:55 +00001874 // Are there stores / loads / calls between them?
1875 // FIXME: This is overly conservative. We should make use of alias information
1876 // some day.
Evan Chengb4b20bb2009-06-19 23:17:27 +00001877 SmallSet<unsigned, 4> AddedRegPressure;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001878 while (++I != E) {
Jim Grosbach4e5e6a82010-06-04 01:23:30 +00001879 if (I->isDebugValue() || MemOps.count(&*I))
Evan Chengb4b20bb2009-06-19 23:17:27 +00001880 continue;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001881 if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001882 return false;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001883 if (isLd && I->mayStore())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001884 return false;
1885 if (!isLd) {
Evan Cheng7f8e5632011-12-07 07:15:52 +00001886 if (I->mayLoad())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001887 return false;
1888 // It's not safe to move the first 'str' down.
1889 // str r1, [r0]
1890 // strh r5, [r0]
1891 // str r4, [r0, #+4]
Evan Cheng7f8e5632011-12-07 07:15:52 +00001892 if (I->mayStore())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001893 return false;
1894 }
1895 for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
1896 MachineOperand &MO = I->getOperand(j);
Evan Chengb4b20bb2009-06-19 23:17:27 +00001897 if (!MO.isReg())
1898 continue;
1899 unsigned Reg = MO.getReg();
1900 if (MO.isDef() && TRI->regsOverlap(Reg, Base))
Evan Cheng185c9ef2009-06-13 09:12:55 +00001901 return false;
Evan Chengb4b20bb2009-06-19 23:17:27 +00001902 if (Reg != Base && !MemRegs.count(Reg))
1903 AddedRegPressure.insert(Reg);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001904 }
1905 }
Evan Chengb4b20bb2009-06-19 23:17:27 +00001906
1907 // Estimate register pressure increase due to the transformation.
1908 if (MemRegs.size() <= 4)
1909 // Ok if we are moving small number of instructions.
1910 return true;
1911 return AddedRegPressure.size() <= MemRegs.size() * 2;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001912}
1913
Andrew Trick28c1d182011-11-11 22:18:09 +00001914
Matthias Braunec50fa62015-06-01 21:26:23 +00001915/// Copy \p Op0 and \p Op1 operands into a new array assigned to MI.
Andrew Trick28c1d182011-11-11 22:18:09 +00001916static void concatenateMemOperands(MachineInstr *MI, MachineInstr *Op0,
1917 MachineInstr *Op1) {
1918 assert(MI->memoperands_empty() && "expected a new machineinstr");
1919 size_t numMemRefs = (Op0->memoperands_end() - Op0->memoperands_begin())
1920 + (Op1->memoperands_end() - Op1->memoperands_begin());
1921
1922 MachineFunction *MF = MI->getParent()->getParent();
1923 MachineSDNode::mmo_iterator MemBegin = MF->allocateMemRefsArray(numMemRefs);
1924 MachineSDNode::mmo_iterator MemEnd =
1925 std::copy(Op0->memoperands_begin(), Op0->memoperands_end(), MemBegin);
1926 MemEnd =
1927 std::copy(Op1->memoperands_begin(), Op1->memoperands_end(), MemEnd);
1928 MI->setMemRefs(MemBegin, MemEnd);
1929}
1930
Evan Chengeba57e42009-06-15 20:54:56 +00001931bool
1932ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
Matthias Braun125c9f52015-06-03 16:30:24 +00001933 DebugLoc &dl, unsigned &NewOpc,
1934 unsigned &FirstReg,
1935 unsigned &SecondReg,
1936 unsigned &BaseReg, int &Offset,
1937 unsigned &PredReg,
Evan Chengfd6aad72009-09-25 21:44:53 +00001938 ARMCC::CondCodes &Pred,
1939 bool &isT2) {
Evan Cheng139c3db2009-09-29 07:07:30 +00001940 // Make sure we're allowed to generate LDRD/STRD.
1941 if (!STI->hasV5TEOps())
1942 return false;
1943
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001944 // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
Evan Chengfd6aad72009-09-25 21:44:53 +00001945 unsigned Scale = 1;
Evan Chengeba57e42009-06-15 20:54:56 +00001946 unsigned Opcode = Op0->getOpcode();
James Molloybb73c232014-05-16 14:08:46 +00001947 if (Opcode == ARM::LDRi12) {
Evan Chengeba57e42009-06-15 20:54:56 +00001948 NewOpc = ARM::LDRD;
James Molloybb73c232014-05-16 14:08:46 +00001949 } else if (Opcode == ARM::STRi12) {
Evan Chengeba57e42009-06-15 20:54:56 +00001950 NewOpc = ARM::STRD;
James Molloybb73c232014-05-16 14:08:46 +00001951 } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
Evan Chengfd6aad72009-09-25 21:44:53 +00001952 NewOpc = ARM::t2LDRDi8;
1953 Scale = 4;
1954 isT2 = true;
1955 } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
1956 NewOpc = ARM::t2STRDi8;
1957 Scale = 4;
1958 isT2 = true;
James Molloybb73c232014-05-16 14:08:46 +00001959 } else {
Evan Chengfd6aad72009-09-25 21:44:53 +00001960 return false;
James Molloybb73c232014-05-16 14:08:46 +00001961 }
Evan Chengfd6aad72009-09-25 21:44:53 +00001962
Jim Grosbach9302bfd2010-10-26 19:34:41 +00001963 // Make sure the base address satisfies i64 ld / st alignment requirement.
Quentin Colombet663150f2013-06-20 22:51:44 +00001964 // At the moment, we ignore the memoryoperand's value.
1965 // If we want to use AliasAnalysis, we should check it accordingly.
Evan Chengeba57e42009-06-15 20:54:56 +00001966 if (!Op0->hasOneMemOperand() ||
Dan Gohman48b185d2009-09-25 20:36:54 +00001967 (*Op0->memoperands_begin())->isVolatile())
Evan Cheng1283c6a2009-06-15 08:28:29 +00001968 return false;
1969
Dan Gohman48b185d2009-09-25 20:36:54 +00001970 unsigned Align = (*Op0->memoperands_begin())->getAlignment();
Dan Gohman913c9982010-04-15 04:33:49 +00001971 const Function *Func = MF->getFunction();
Evan Cheng1283c6a2009-06-15 08:28:29 +00001972 unsigned ReqAlign = STI->hasV6Ops()
Jim Grosbach338de3e2010-10-27 23:12:14 +00001973 ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
Evan Chengfd6aad72009-09-25 21:44:53 +00001974 : 8; // Pre-v6 need 8-byte align
Evan Chengeba57e42009-06-15 20:54:56 +00001975 if (Align < ReqAlign)
1976 return false;
1977
1978 // Then make sure the immediate offset fits.
1979 int OffImm = getMemoryOpOffset(Op0);
Evan Chenga6b9cab2009-09-27 09:46:04 +00001980 if (isT2) {
Evan Cheng42401d62011-03-15 18:41:52 +00001981 int Limit = (1 << 8) * Scale;
1982 if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
1983 return false;
Evan Chengfd6aad72009-09-25 21:44:53 +00001984 Offset = OffImm;
Evan Chenga6b9cab2009-09-27 09:46:04 +00001985 } else {
1986 ARM_AM::AddrOpc AddSub = ARM_AM::add;
1987 if (OffImm < 0) {
1988 AddSub = ARM_AM::sub;
1989 OffImm = - OffImm;
1990 }
1991 int Limit = (1 << 8) * Scale;
1992 if (OffImm >= Limit || (OffImm & (Scale-1)))
1993 return false;
Evan Chengfd6aad72009-09-25 21:44:53 +00001994 Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
Evan Chenga6b9cab2009-09-27 09:46:04 +00001995 }
Matthias Braun125c9f52015-06-03 16:30:24 +00001996 FirstReg = Op0->getOperand(0).getReg();
1997 SecondReg = Op1->getOperand(0).getReg();
1998 if (FirstReg == SecondReg)
Evan Chengeba57e42009-06-15 20:54:56 +00001999 return false;
2000 BaseReg = Op0->getOperand(1).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00002001 Pred = getInstrPredicate(Op0, PredReg);
Evan Chengeba57e42009-06-15 20:54:56 +00002002 dl = Op0->getDebugLoc();
2003 return true;
Evan Cheng1283c6a2009-06-15 08:28:29 +00002004}
2005
Evan Cheng185c9ef2009-06-13 09:12:55 +00002006bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
Craig Topperaf0dea12013-07-04 01:31:24 +00002007 SmallVectorImpl<MachineInstr *> &Ops,
Evan Cheng185c9ef2009-06-13 09:12:55 +00002008 unsigned Base, bool isLd,
2009 DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2010 bool RetVal = false;
2011
2012 // Sort by offset (in reverse order).
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00002013 std::sort(Ops.begin(), Ops.end(),
2014 [](const MachineInstr *LHS, const MachineInstr *RHS) {
2015 int LOffset = getMemoryOpOffset(LHS);
2016 int ROffset = getMemoryOpOffset(RHS);
2017 assert(LHS == RHS || LOffset != ROffset);
2018 return LOffset > ROffset;
2019 });
Evan Cheng185c9ef2009-06-13 09:12:55 +00002020
2021 // The loads / stores of the same base are in order. Scan them from first to
Jim Grosbach1bcdf322010-06-04 00:15:00 +00002022 // last and check for the following:
Evan Cheng185c9ef2009-06-13 09:12:55 +00002023 // 1. Any def of base.
2024 // 2. Any gaps.
2025 while (Ops.size() > 1) {
2026 unsigned FirstLoc = ~0U;
2027 unsigned LastLoc = 0;
Craig Topper062a2ba2014-04-25 05:30:21 +00002028 MachineInstr *FirstOp = nullptr;
2029 MachineInstr *LastOp = nullptr;
Evan Cheng185c9ef2009-06-13 09:12:55 +00002030 int LastOffset = 0;
Evan Cheng0e796032009-06-18 02:04:01 +00002031 unsigned LastOpcode = 0;
Evan Cheng185c9ef2009-06-13 09:12:55 +00002032 unsigned LastBytes = 0;
2033 unsigned NumMove = 0;
2034 for (int i = Ops.size() - 1; i >= 0; --i) {
2035 MachineInstr *Op = Ops[i];
2036 unsigned Loc = MI2LocMap[Op];
2037 if (Loc <= FirstLoc) {
2038 FirstLoc = Loc;
2039 FirstOp = Op;
2040 }
2041 if (Loc >= LastLoc) {
2042 LastLoc = Loc;
2043 LastOp = Op;
2044 }
2045
Andrew Trick642f0f62012-01-11 03:56:08 +00002046 unsigned LSMOpcode
2047 = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2048 if (LastOpcode && LSMOpcode != LastOpcode)
Evan Cheng0e796032009-06-18 02:04:01 +00002049 break;
2050
Evan Cheng185c9ef2009-06-13 09:12:55 +00002051 int Offset = getMemoryOpOffset(Op);
2052 unsigned Bytes = getLSMultipleTransferSize(Op);
2053 if (LastBytes) {
2054 if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2055 break;
2056 }
2057 LastOffset = Offset;
2058 LastBytes = Bytes;
Andrew Trick642f0f62012-01-11 03:56:08 +00002059 LastOpcode = LSMOpcode;
Evan Chengfd6aad72009-09-25 21:44:53 +00002060 if (++NumMove == 8) // FIXME: Tune this limit.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002061 break;
2062 }
2063
2064 if (NumMove <= 1)
2065 Ops.pop_back();
2066 else {
Evan Chengb4b20bb2009-06-19 23:17:27 +00002067 SmallPtrSet<MachineInstr*, 4> MemOps;
2068 SmallSet<unsigned, 4> MemRegs;
2069 for (int i = NumMove-1; i >= 0; --i) {
2070 MemOps.insert(Ops[i]);
2071 MemRegs.insert(Ops[i]->getOperand(0).getReg());
2072 }
Evan Cheng185c9ef2009-06-13 09:12:55 +00002073
2074 // Be conservative, if the instructions are too far apart, don't
2075 // move them. We want to limit the increase of register pressure.
Evan Chengb4b20bb2009-06-19 23:17:27 +00002076 bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002077 if (DoMove)
Evan Chengb4b20bb2009-06-19 23:17:27 +00002078 DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2079 MemOps, MemRegs, TRI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002080 if (!DoMove) {
2081 for (unsigned i = 0; i != NumMove; ++i)
2082 Ops.pop_back();
2083 } else {
2084 // This is the new location for the loads / stores.
2085 MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
Jim Grosbachf14e08b2010-06-15 00:41:09 +00002086 while (InsertPos != MBB->end()
2087 && (MemOps.count(InsertPos) || InsertPos->isDebugValue()))
Evan Cheng185c9ef2009-06-13 09:12:55 +00002088 ++InsertPos;
Evan Cheng1283c6a2009-06-15 08:28:29 +00002089
2090 // If we are moving a pair of loads / stores, see if it makes sense
2091 // to try to allocate a pair of registers that can form register pairs.
Evan Chengeba57e42009-06-15 20:54:56 +00002092 MachineInstr *Op0 = Ops.back();
2093 MachineInstr *Op1 = Ops[Ops.size()-2];
Matthias Braun125c9f52015-06-03 16:30:24 +00002094 unsigned FirstReg = 0, SecondReg = 0;
Jim Grosbach338de3e2010-10-27 23:12:14 +00002095 unsigned BaseReg = 0, PredReg = 0;
Evan Chengeba57e42009-06-15 20:54:56 +00002096 ARMCC::CondCodes Pred = ARMCC::AL;
Evan Chengfd6aad72009-09-25 21:44:53 +00002097 bool isT2 = false;
Evan Chengeba57e42009-06-15 20:54:56 +00002098 unsigned NewOpc = 0;
Evan Chenga6b9cab2009-09-27 09:46:04 +00002099 int Offset = 0;
Evan Chengeba57e42009-06-15 20:54:56 +00002100 DebugLoc dl;
2101 if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
Matthias Braun125c9f52015-06-03 16:30:24 +00002102 FirstReg, SecondReg, BaseReg,
Evan Chengfd6aad72009-09-25 21:44:53 +00002103 Offset, PredReg, Pred, isT2)) {
Evan Chengeba57e42009-06-15 20:54:56 +00002104 Ops.pop_back();
2105 Ops.pop_back();
Evan Cheng1283c6a2009-06-15 08:28:29 +00002106
Evan Cheng6cc775f2011-06-28 19:10:37 +00002107 const MCInstrDesc &MCID = TII->get(NewOpc);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002108 const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
Matthias Braun125c9f52015-06-03 16:30:24 +00002109 MRI->constrainRegClass(FirstReg, TRC);
2110 MRI->constrainRegClass(SecondReg, TRC);
Cameron Zwarichec645bf2011-05-18 21:25:14 +00002111
Evan Chengeba57e42009-06-15 20:54:56 +00002112 // Form the pair instruction.
Evan Cheng0e796032009-06-18 02:04:01 +00002113 if (isLd) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002114 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
Matthias Braun125c9f52015-06-03 16:30:24 +00002115 .addReg(FirstReg, RegState::Define)
2116 .addReg(SecondReg, RegState::Define)
Evan Chengfd6aad72009-09-25 21:44:53 +00002117 .addReg(BaseReg);
Jim Grosbach338de3e2010-10-27 23:12:14 +00002118 // FIXME: We're converting from LDRi12 to an insn that still
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00002119 // uses addrmode2, so we need an explicit offset reg. It should
Jim Grosbach338de3e2010-10-27 23:12:14 +00002120 // always by reg0 since we're transforming LDRi12s.
Evan Chengfd6aad72009-09-25 21:44:53 +00002121 if (!isT2)
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00002122 MIB.addReg(0);
Evan Chengfd6aad72009-09-25 21:44:53 +00002123 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
Andrew Trick28c1d182011-11-11 22:18:09 +00002124 concatenateMemOperands(MIB, Op0, Op1);
2125 DEBUG(dbgs() << "Formed " << *MIB << "\n");
Evan Cheng0e796032009-06-18 02:04:01 +00002126 ++NumLDRDFormed;
2127 } else {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002128 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
Matthias Braun125c9f52015-06-03 16:30:24 +00002129 .addReg(FirstReg)
2130 .addReg(SecondReg)
Evan Chengfd6aad72009-09-25 21:44:53 +00002131 .addReg(BaseReg);
Jim Grosbach338de3e2010-10-27 23:12:14 +00002132 // FIXME: We're converting from LDRi12 to an insn that still
2133 // uses addrmode2, so we need an explicit offset reg. It should
2134 // always by reg0 since we're transforming STRi12s.
Evan Chengfd6aad72009-09-25 21:44:53 +00002135 if (!isT2)
Jim Grosbach338de3e2010-10-27 23:12:14 +00002136 MIB.addReg(0);
Evan Chengfd6aad72009-09-25 21:44:53 +00002137 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
Andrew Trick28c1d182011-11-11 22:18:09 +00002138 concatenateMemOperands(MIB, Op0, Op1);
2139 DEBUG(dbgs() << "Formed " << *MIB << "\n");
Evan Cheng0e796032009-06-18 02:04:01 +00002140 ++NumSTRDFormed;
2141 }
2142 MBB->erase(Op0);
2143 MBB->erase(Op1);
Evan Cheng1283c6a2009-06-15 08:28:29 +00002144
Matthias Braun125c9f52015-06-03 16:30:24 +00002145 if (!isT2) {
2146 // Add register allocation hints to form register pairs.
2147 MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2148 MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);
2149 }
Evan Chengeba57e42009-06-15 20:54:56 +00002150 } else {
2151 for (unsigned i = 0; i != NumMove; ++i) {
2152 MachineInstr *Op = Ops.back();
2153 Ops.pop_back();
2154 MBB->splice(InsertPos, MBB, Op);
2155 }
Evan Cheng185c9ef2009-06-13 09:12:55 +00002156 }
2157
2158 NumLdStMoved += NumMove;
2159 RetVal = true;
2160 }
2161 }
2162 }
2163
2164 return RetVal;
2165}
2166
2167bool
2168ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2169 bool RetVal = false;
2170
2171 DenseMap<MachineInstr*, unsigned> MI2LocMap;
2172 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2173 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2174 SmallVector<unsigned, 4> LdBases;
2175 SmallVector<unsigned, 4> StBases;
2176
2177 unsigned Loc = 0;
2178 MachineBasicBlock::iterator MBBI = MBB->begin();
2179 MachineBasicBlock::iterator E = MBB->end();
2180 while (MBBI != E) {
2181 for (; MBBI != E; ++MBBI) {
2182 MachineInstr *MI = MBBI;
Evan Cheng7f8e5632011-12-07 07:15:52 +00002183 if (MI->isCall() || MI->isTerminator()) {
Evan Cheng185c9ef2009-06-13 09:12:55 +00002184 // Stop at barriers.
2185 ++MBBI;
2186 break;
2187 }
2188
Jim Grosbach4e5e6a82010-06-04 01:23:30 +00002189 if (!MI->isDebugValue())
2190 MI2LocMap[MI] = ++Loc;
2191
Evan Cheng185c9ef2009-06-13 09:12:55 +00002192 if (!isMemoryOp(MI))
2193 continue;
2194 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00002195 if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
Evan Cheng185c9ef2009-06-13 09:12:55 +00002196 continue;
2197
Evan Chengfd6aad72009-09-25 21:44:53 +00002198 int Opc = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00002199 bool isLd = isLoadSingle(Opc);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002200 unsigned Base = MI->getOperand(1).getReg();
2201 int Offset = getMemoryOpOffset(MI);
2202
2203 bool StopHere = false;
2204 if (isLd) {
2205 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2206 Base2LdsMap.find(Base);
2207 if (BI != Base2LdsMap.end()) {
2208 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2209 if (Offset == getMemoryOpOffset(BI->second[i])) {
2210 StopHere = true;
2211 break;
2212 }
2213 }
2214 if (!StopHere)
2215 BI->second.push_back(MI);
2216 } else {
Craig Topper9ae47072013-07-10 16:38:35 +00002217 Base2LdsMap[Base].push_back(MI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002218 LdBases.push_back(Base);
2219 }
2220 } else {
2221 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2222 Base2StsMap.find(Base);
2223 if (BI != Base2StsMap.end()) {
2224 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2225 if (Offset == getMemoryOpOffset(BI->second[i])) {
2226 StopHere = true;
2227 break;
2228 }
2229 }
2230 if (!StopHere)
2231 BI->second.push_back(MI);
2232 } else {
Craig Topper9ae47072013-07-10 16:38:35 +00002233 Base2StsMap[Base].push_back(MI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002234 StBases.push_back(Base);
2235 }
2236 }
2237
2238 if (StopHere) {
Evan Chengb4b20bb2009-06-19 23:17:27 +00002239 // Found a duplicate (a base+offset combination that's seen earlier).
2240 // Backtrack.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002241 --Loc;
2242 break;
2243 }
2244 }
2245
2246 // Re-schedule loads.
2247 for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2248 unsigned Base = LdBases[i];
Craig Topperaf0dea12013-07-04 01:31:24 +00002249 SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
Evan Cheng185c9ef2009-06-13 09:12:55 +00002250 if (Lds.size() > 1)
2251 RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2252 }
2253
2254 // Re-schedule stores.
2255 for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2256 unsigned Base = StBases[i];
Craig Topperaf0dea12013-07-04 01:31:24 +00002257 SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
Evan Cheng185c9ef2009-06-13 09:12:55 +00002258 if (Sts.size() > 1)
2259 RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2260 }
2261
2262 if (MBBI != E) {
2263 Base2LdsMap.clear();
2264 Base2StsMap.clear();
2265 LdBases.clear();
2266 StBases.clear();
2267 }
2268 }
2269
2270 return RetVal;
2271}
2272
2273
Matthias Braunec50fa62015-06-01 21:26:23 +00002274/// Returns an instance of the load / store optimization pass.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002275FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2276 if (PreAlloc)
2277 return new ARMPreAllocLoadStoreOpt();
2278 return new ARMLoadStoreOpt();
2279}