blob: 2eef0987bde224f669c9eb4c561a56bfcf158d0a [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that performs load / store related peephole
11// optimizations. This pass should be run after register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000016#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "MCTargetDesc/AArch64AddressingModes.h"
18#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000019#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000020#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000021#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032using namespace llvm;
33
34#define DEBUG_TYPE "aarch64-ldst-opt"
35
36/// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37/// load / store instructions to form ldp / stp instructions.
38
39STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
40STATISTIC(NumPostFolded, "Number of post-index updates folded");
41STATISTIC(NumPreFolded, "Number of pre-index updates folded");
42STATISTIC(NumUnscaledPairCreated,
43 "Number of load/store from unscaled generated");
44
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000045static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000047
48// Place holder while testing unscaled load/store combining
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000049static cl::opt<bool> EnableAArch64UnscaledMemOp(
50 "aarch64-unscaled-mem-op", cl::Hidden,
51 cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
Tim Northover3b0846e2014-05-24 12:50:23 +000052
53namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000054
55typedef struct LdStPairFlags {
56 // If a matching instruction is found, MergeForward is set to true if the
57 // merge is to remove the first instruction and replace the second with
58 // a pair-wise insn, and false if the reverse is true.
59 bool MergeForward;
60
61 // SExtIdx gives the index of the result of the load pair that must be
62 // extended. The value of SExtIdx assumes that the paired load produces the
63 // value in this order: (I, returned iterator), i.e., -1 means no value has
64 // to be extended, 0 means I, and 1 means the returned iterator.
65 int SExtIdx;
66
67 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
68
69 void setMergeForward(bool V = true) { MergeForward = V; }
70 bool getMergeForward() const { return MergeForward; }
71
72 void setSExtIdx(int V) { SExtIdx = V; }
73 int getSExtIdx() const { return SExtIdx; }
74
75} LdStPairFlags;
76
Tim Northover3b0846e2014-05-24 12:50:23 +000077struct AArch64LoadStoreOpt : public MachineFunctionPass {
78 static char ID;
79 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {}
80
81 const AArch64InstrInfo *TII;
82 const TargetRegisterInfo *TRI;
83
84 // Scan the instructions looking for a load/store that can be combined
85 // with the current instruction into a load/store pair.
86 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +000087 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +000088 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +000089 unsigned Limit);
90 // Merge the two instructions indicated into a single pair-wise instruction.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +000091 // If MergeForward is true, erase the first instruction and fold its
Tim Northover3b0846e2014-05-24 12:50:23 +000092 // operation into the second. If false, the reverse. Return the instruction
93 // following the first instruction (which may change during processing).
94 MachineBasicBlock::iterator
95 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +000096 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +000097 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 // Scan the instruction list to find a base register update that can
100 // be combined with the current instruction (a load or store) using
101 // pre or post indexed addressing with writeback. Scan forwards.
102 MachineBasicBlock::iterator
103 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
104 int Value);
105
106 // Scan the instruction list to find a base register update that can
107 // be combined with the current instruction (a load or store) using
108 // pre or post indexed addressing with writeback. Scan backwards.
109 MachineBasicBlock::iterator
110 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
111
112 // Merge a pre-index base register update into a ld/st instruction.
113 MachineBasicBlock::iterator
114 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
115 MachineBasicBlock::iterator Update);
116
117 // Merge a post-index base register update into a ld/st instruction.
118 MachineBasicBlock::iterator
119 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
120 MachineBasicBlock::iterator Update);
121
122 bool optimizeBlock(MachineBasicBlock &MBB);
123
124 bool runOnMachineFunction(MachineFunction &Fn) override;
125
126 const char *getPassName() const override {
127 return "AArch64 load / store optimization pass";
128 }
129
130private:
131 int getMemSize(MachineInstr *MemMI);
132};
133char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000134} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000135
136static bool isUnscaledLdst(unsigned Opc) {
137 switch (Opc) {
138 default:
139 return false;
140 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000141 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000142 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000144 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000146 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000147 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000148 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000149 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000150 case AArch64::LDURSWi:
151 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000152 }
153}
154
155// Size in bytes of the data moved by an unscaled load or store
156int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
157 switch (MemMI->getOpcode()) {
158 default:
Tilmann Schellera17a4322014-06-03 16:33:13 +0000159 llvm_unreachable("Opcode has unknown size!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000160 case AArch64::STRSui:
161 case AArch64::STURSi:
162 return 4;
163 case AArch64::STRDui:
164 case AArch64::STURDi:
165 return 8;
166 case AArch64::STRQui:
167 case AArch64::STURQi:
168 return 16;
169 case AArch64::STRWui:
170 case AArch64::STURWi:
171 return 4;
172 case AArch64::STRXui:
173 case AArch64::STURXi:
174 return 8;
175 case AArch64::LDRSui:
176 case AArch64::LDURSi:
177 return 4;
178 case AArch64::LDRDui:
179 case AArch64::LDURDi:
180 return 8;
181 case AArch64::LDRQui:
182 case AArch64::LDURQi:
183 return 16;
184 case AArch64::LDRWui:
185 case AArch64::LDURWi:
186 return 4;
187 case AArch64::LDRXui:
188 case AArch64::LDURXi:
189 return 8;
Quentin Colombet29f55332015-01-24 01:25:54 +0000190 case AArch64::LDRSWui:
191 case AArch64::LDURSWi:
192 return 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 }
194}
195
Quentin Colombet66b61632015-03-06 22:42:10 +0000196static unsigned getMatchingNonSExtOpcode(unsigned Opc,
197 bool *IsValidLdStrOpc = nullptr) {
198 if (IsValidLdStrOpc)
199 *IsValidLdStrOpc = true;
200 switch (Opc) {
201 default:
202 if (IsValidLdStrOpc)
203 *IsValidLdStrOpc = false;
204 return UINT_MAX;
205 case AArch64::STRDui:
206 case AArch64::STURDi:
207 case AArch64::STRQui:
208 case AArch64::STURQi:
209 case AArch64::STRWui:
210 case AArch64::STURWi:
211 case AArch64::STRXui:
212 case AArch64::STURXi:
213 case AArch64::LDRDui:
214 case AArch64::LDURDi:
215 case AArch64::LDRQui:
216 case AArch64::LDURQi:
217 case AArch64::LDRWui:
218 case AArch64::LDURWi:
219 case AArch64::LDRXui:
220 case AArch64::LDURXi:
221 case AArch64::STRSui:
222 case AArch64::STURSi:
223 case AArch64::LDRSui:
224 case AArch64::LDURSi:
225 return Opc;
226 case AArch64::LDRSWui:
227 return AArch64::LDRWui;
228 case AArch64::LDURSWi:
229 return AArch64::LDURWi;
230 }
231}
232
Tim Northover3b0846e2014-05-24 12:50:23 +0000233static unsigned getMatchingPairOpcode(unsigned Opc) {
234 switch (Opc) {
235 default:
236 llvm_unreachable("Opcode has no pairwise equivalent!");
237 case AArch64::STRSui:
238 case AArch64::STURSi:
239 return AArch64::STPSi;
240 case AArch64::STRDui:
241 case AArch64::STURDi:
242 return AArch64::STPDi;
243 case AArch64::STRQui:
244 case AArch64::STURQi:
245 return AArch64::STPQi;
246 case AArch64::STRWui:
247 case AArch64::STURWi:
248 return AArch64::STPWi;
249 case AArch64::STRXui:
250 case AArch64::STURXi:
251 return AArch64::STPXi;
252 case AArch64::LDRSui:
253 case AArch64::LDURSi:
254 return AArch64::LDPSi;
255 case AArch64::LDRDui:
256 case AArch64::LDURDi:
257 return AArch64::LDPDi;
258 case AArch64::LDRQui:
259 case AArch64::LDURQi:
260 return AArch64::LDPQi;
261 case AArch64::LDRWui:
262 case AArch64::LDURWi:
263 return AArch64::LDPWi;
264 case AArch64::LDRXui:
265 case AArch64::LDURXi:
266 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000267 case AArch64::LDRSWui:
268 case AArch64::LDURSWi:
269 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000270 }
271}
272
273static unsigned getPreIndexedOpcode(unsigned Opc) {
274 switch (Opc) {
275 default:
276 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000277 case AArch64::STRSui:
278 return AArch64::STRSpre;
279 case AArch64::STRDui:
280 return AArch64::STRDpre;
281 case AArch64::STRQui:
282 return AArch64::STRQpre;
283 case AArch64::STRWui:
284 return AArch64::STRWpre;
285 case AArch64::STRXui:
286 return AArch64::STRXpre;
287 case AArch64::LDRSui:
288 return AArch64::LDRSpre;
289 case AArch64::LDRDui:
290 return AArch64::LDRDpre;
291 case AArch64::LDRQui:
292 return AArch64::LDRQpre;
293 case AArch64::LDRWui:
294 return AArch64::LDRWpre;
295 case AArch64::LDRXui:
296 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000297 case AArch64::LDRSWui:
298 return AArch64::LDRSWpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000299 }
300}
301
302static unsigned getPostIndexedOpcode(unsigned Opc) {
303 switch (Opc) {
304 default:
305 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
306 case AArch64::STRSui:
307 return AArch64::STRSpost;
308 case AArch64::STRDui:
309 return AArch64::STRDpost;
310 case AArch64::STRQui:
311 return AArch64::STRQpost;
312 case AArch64::STRWui:
313 return AArch64::STRWpost;
314 case AArch64::STRXui:
315 return AArch64::STRXpost;
316 case AArch64::LDRSui:
317 return AArch64::LDRSpost;
318 case AArch64::LDRDui:
319 return AArch64::LDRDpost;
320 case AArch64::LDRQui:
321 return AArch64::LDRQpost;
322 case AArch64::LDRWui:
323 return AArch64::LDRWpost;
324 case AArch64::LDRXui:
325 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000326 case AArch64::LDRSWui:
327 return AArch64::LDRSWpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000328 }
329}
330
331MachineBasicBlock::iterator
332AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
333 MachineBasicBlock::iterator Paired,
Chad Rosier96a18a92015-07-21 17:42:04 +0000334 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000335 MachineBasicBlock::iterator NextI = I;
336 ++NextI;
337 // If NextI is the second of the two instructions to be merged, we need
338 // to skip one further. Either way we merge will invalidate the iterator,
339 // and we don't need to scan the new instruction, as it's a pairwise
340 // instruction, which we're not considering for further action anyway.
341 if (NextI == Paired)
342 ++NextI;
343
Chad Rosier96a18a92015-07-21 17:42:04 +0000344 int SExtIdx = Flags.getSExtIdx();
Quentin Colombet66b61632015-03-06 22:42:10 +0000345 unsigned Opc =
346 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
347 bool IsUnscaled = isUnscaledLdst(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000348 int OffsetStride =
349 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
350
Chad Rosier96a18a92015-07-21 17:42:04 +0000351 bool MergeForward = Flags.getMergeForward();
Quentin Colombet66b61632015-03-06 22:42:10 +0000352 unsigned NewOpc = getMatchingPairOpcode(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000353 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000354 // instructions MergeForward indicates.
355 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
356 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000357 // so we get the flags compatible with the input code.
358 MachineOperand &BaseRegOp =
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000359 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
Tim Northover3b0846e2014-05-24 12:50:23 +0000360
361 // Which register is Rt and which is Rt2 depends on the offset order.
362 MachineInstr *RtMI, *Rt2MI;
363 if (I->getOperand(2).getImm() ==
364 Paired->getOperand(2).getImm() + OffsetStride) {
365 RtMI = Paired;
366 Rt2MI = I;
Quentin Colombet66b61632015-03-06 22:42:10 +0000367 // Here we swapped the assumption made for SExtIdx.
368 // I.e., we turn ldp I, Paired into ldp Paired, I.
369 // Update the index accordingly.
370 if (SExtIdx != -1)
371 SExtIdx = (SExtIdx + 1) % 2;
Tim Northover3b0846e2014-05-24 12:50:23 +0000372 } else {
373 RtMI = I;
374 Rt2MI = Paired;
375 }
376 // Handle Unscaled
377 int OffsetImm = RtMI->getOperand(2).getImm();
378 if (IsUnscaled && EnableAArch64UnscaledMemOp)
379 OffsetImm /= OffsetStride;
380
381 // Construct the new instruction.
382 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
383 I->getDebugLoc(), TII->get(NewOpc))
384 .addOperand(RtMI->getOperand(0))
385 .addOperand(Rt2MI->getOperand(0))
386 .addOperand(BaseRegOp)
387 .addImm(OffsetImm);
388 (void)MIB;
389
390 // FIXME: Do we need/want to copy the mem operands from the source
391 // instructions? Probably. What uses them after this?
392
393 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
394 DEBUG(I->print(dbgs()));
395 DEBUG(dbgs() << " ");
396 DEBUG(Paired->print(dbgs()));
397 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000398
399 if (SExtIdx != -1) {
400 // Generate the sign extension for the proper result of the ldp.
401 // I.e., with X1, that would be:
402 // %W1<def> = KILL %W1, %X1<imp-def>
403 // %X1<def> = SBFMXri %X1<kill>, 0, 31
404 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
405 // Right now, DstMO has the extended register, since it comes from an
406 // extended opcode.
407 unsigned DstRegX = DstMO.getReg();
408 // Get the W variant of that register.
409 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
410 // Update the result of LDP to use the W instead of the X variant.
411 DstMO.setReg(DstRegW);
412 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
413 DEBUG(dbgs() << "\n");
414 // Make the machine verifier happy by providing a definition for
415 // the X register.
416 // Insert this definition right after the generated LDP, i.e., before
417 // InsertionPoint.
418 MachineInstrBuilder MIBKill =
419 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
420 TII->get(TargetOpcode::KILL), DstRegW)
421 .addReg(DstRegW)
422 .addReg(DstRegX, RegState::Define);
423 MIBKill->getOperand(2).setImplicit();
424 // Create the sign extension.
425 MachineInstrBuilder MIBSXTW =
426 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
427 TII->get(AArch64::SBFMXri), DstRegX)
428 .addReg(DstRegX)
429 .addImm(0)
430 .addImm(31);
431 (void)MIBSXTW;
432 DEBUG(dbgs() << " Extend operand:\n ");
433 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
434 DEBUG(dbgs() << "\n");
435 } else {
436 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437 DEBUG(dbgs() << "\n");
438 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000439
440 // Erase the old instructions.
441 I->eraseFromParent();
442 Paired->eraseFromParent();
443
444 return NextI;
445}
446
447/// trackRegDefsUses - Remember what registers the specified instruction uses
448/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000449static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 BitVector &UsedRegs,
451 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000452 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 if (MO.isRegMask())
454 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
455
456 if (!MO.isReg())
457 continue;
458 unsigned Reg = MO.getReg();
459 if (MO.isDef()) {
460 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
461 ModifiedRegs.set(*AI);
462 } else {
463 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
464 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
465 UsedRegs.set(*AI);
466 }
467 }
468}
469
470static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
471 if (!IsUnscaled && (Offset > 63 || Offset < -64))
472 return false;
473 if (IsUnscaled) {
474 // Convert the byte-offset used by unscaled into an "element" offset used
475 // by the scaled pair load/store instructions.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000476 int ElemOffset = Offset / OffsetStride;
477 if (ElemOffset > 63 || ElemOffset < -64)
Tim Northover3b0846e2014-05-24 12:50:23 +0000478 return false;
479 }
480 return true;
481}
482
483// Do alignment, specialized to power of 2 and for signed ints,
484// avoiding having to do a C-style cast from uint_64t to int when
485// using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
486// FIXME: Move this function to include/MathExtras.h?
487static int alignTo(int Num, int PowOf2) {
488 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
489}
490
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000491static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
492 const AArch64InstrInfo *TII) {
493 // One of the instructions must modify memory.
494 if (!MIa->mayStore() && !MIb->mayStore())
495 return false;
496
497 // Both instructions must be memory operations.
498 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
499 return false;
500
501 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
502}
503
504static bool mayAlias(MachineInstr *MIa,
505 SmallVectorImpl<MachineInstr *> &MemInsns,
506 const AArch64InstrInfo *TII) {
507 for (auto &MIb : MemInsns)
508 if (mayAlias(MIa, MIb, TII))
509 return true;
510
511 return false;
512}
513
Tim Northover3b0846e2014-05-24 12:50:23 +0000514/// findMatchingInsn - Scan the instructions looking for a load/store that can
515/// be combined with the current instruction into a load/store pair.
516MachineBasicBlock::iterator
517AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000518 LdStPairFlags &Flags,
Quentin Colombet66b61632015-03-06 22:42:10 +0000519 unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 MachineBasicBlock::iterator E = I->getParent()->end();
521 MachineBasicBlock::iterator MBBI = I;
522 MachineInstr *FirstMI = I;
523 ++MBBI;
524
Matthias Braunfa3872e2015-05-18 20:27:55 +0000525 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000526 bool MayLoad = FirstMI->mayLoad();
Tim Northover3b0846e2014-05-24 12:50:23 +0000527 bool IsUnscaled = isUnscaledLdst(Opc);
528 unsigned Reg = FirstMI->getOperand(0).getReg();
529 unsigned BaseReg = FirstMI->getOperand(1).getReg();
530 int Offset = FirstMI->getOperand(2).getImm();
531
532 // Early exit if the first instruction modifies the base register.
533 // e.g., ldr x0, [x0]
534 // Early exit if the offset if not possible to match. (6 bits of positive
535 // range, plus allow an extra one in case we find a later insn that matches
536 // with Offset-1
537 if (FirstMI->modifiesRegister(BaseReg, TRI))
538 return E;
539 int OffsetStride =
540 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
541 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
542 return E;
543
544 // Track which registers have been modified and used between the first insn
545 // (inclusive) and the second insn.
546 BitVector ModifiedRegs, UsedRegs;
547 ModifiedRegs.resize(TRI->getNumRegs());
548 UsedRegs.resize(TRI->getNumRegs());
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000549
550 // Remember any instructions that read/write memory between FirstMI and MI.
551 SmallVector<MachineInstr *, 4> MemInsns;
552
Tim Northover3b0846e2014-05-24 12:50:23 +0000553 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
554 MachineInstr *MI = MBBI;
555 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
556 // optimization by changing how far we scan.
557 if (MI->isDebugValue())
558 continue;
559
560 // Now that we know this is a real instruction, count it.
561 ++Count;
562
Quentin Colombet66b61632015-03-06 22:42:10 +0000563 bool CanMergeOpc = Opc == MI->getOpcode();
Chad Rosier96a18a92015-07-21 17:42:04 +0000564 Flags.setSExtIdx(-1);
Quentin Colombet66b61632015-03-06 22:42:10 +0000565 if (!CanMergeOpc) {
566 bool IsValidLdStrOpc;
567 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
568 if (!IsValidLdStrOpc)
569 continue;
570 // Opc will be the first instruction in the pair.
Chad Rosier96a18a92015-07-21 17:42:04 +0000571 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
Quentin Colombet66b61632015-03-06 22:42:10 +0000572 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
573 }
574
575 if (CanMergeOpc && MI->getOperand(2).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000576 // If we've found another instruction with the same opcode, check to see
577 // if the base and offset are compatible with our starting instruction.
578 // These instructions all have scaled immediate operands, so we just
579 // check for +1/-1. Make sure to check the new instruction offset is
580 // actually an immediate and not a symbolic reference destined for
581 // a relocation.
582 //
583 // Pairwise instructions have a 7-bit signed offset field. Single insns
584 // have a 12-bit unsigned offset field. To be a valid combine, the
585 // final offset must be in range.
586 unsigned MIBaseReg = MI->getOperand(1).getReg();
587 int MIOffset = MI->getOperand(2).getImm();
588 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
589 (Offset + OffsetStride == MIOffset))) {
590 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
591 // If this is a volatile load/store that otherwise matched, stop looking
592 // as something is going on that we don't have enough information to
593 // safely transform. Similarly, stop if we see a hint to avoid pairs.
594 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
595 return E;
596 // If the resultant immediate offset of merging these instructions
597 // is out of range for a pairwise instruction, bail and keep looking.
598 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
599 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
600 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000601 if (MI->mayLoadOrStore())
602 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 continue;
604 }
605 // If the alignment requirements of the paired (scaled) instruction
606 // can't express the offset of the unscaled input, bail and keep
607 // looking.
608 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
609 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
610 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000611 if (MI->mayLoadOrStore())
612 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000613 continue;
614 }
615 // If the destination register of the loads is the same register, bail
616 // and keep looking. A load-pair instruction with both destination
617 // registers the same is UNPREDICTABLE and will result in an exception.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000618 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000619 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000620 if (MI->mayLoadOrStore())
621 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000622 continue;
623 }
624
625 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000626 // the two instructions and none of the instructions between the second
627 // and first alias with the second, we can combine the second into the
628 // first.
Tim Northover3b0846e2014-05-24 12:50:23 +0000629 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
Chad Rosiercf90acc2015-06-09 20:59:41 +0000630 !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000631 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000632 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 return MBBI;
634 }
635
636 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000637 // between the two instructions and none of the instructions between the
638 // first and the second alias with the first, we can combine the first
639 // into the second.
Tim Northover3b0846e2014-05-24 12:50:23 +0000640 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
Chad Rosiercf90acc2015-06-09 20:59:41 +0000641 !(FirstMI->mayLoad() &&
642 UsedRegs[FirstMI->getOperand(0).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000643 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000644 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000645 return MBBI;
646 }
647 // Unable to combine these instructions due to interference in between.
648 // Keep looking.
649 }
650 }
651
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000652 // If the instruction wasn't a matching load or store. Stop searching if we
653 // encounter a call instruction that might modify memory.
654 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +0000655 return E;
656
657 // Update modified / uses register lists.
658 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
659
660 // Otherwise, if the base register is modified, we have no match, so
661 // return early.
662 if (ModifiedRegs[BaseReg])
663 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000664
665 // Update list of instructions that read/write memory.
666 if (MI->mayLoadOrStore())
667 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000668 }
669 return E;
670}
671
672MachineBasicBlock::iterator
673AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
674 MachineBasicBlock::iterator Update) {
675 assert((Update->getOpcode() == AArch64::ADDXri ||
676 Update->getOpcode() == AArch64::SUBXri) &&
677 "Unexpected base register update instruction to merge!");
678 MachineBasicBlock::iterator NextI = I;
679 // Return the instruction following the merged instruction, which is
680 // the instruction following our unmerged load. Unless that's the add/sub
681 // instruction we're merging, in which case it's the one after that.
682 if (++NextI == Update)
683 ++NextI;
684
685 int Value = Update->getOperand(2).getImm();
686 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
687 "Can't merge 1 << 12 offset into pre-indexed load / store");
688 if (Update->getOpcode() == AArch64::SUBXri)
689 Value = -Value;
690
691 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
692 MachineInstrBuilder MIB =
693 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
694 .addOperand(Update->getOperand(0))
695 .addOperand(I->getOperand(0))
696 .addOperand(I->getOperand(1))
697 .addImm(Value);
698 (void)MIB;
699
700 DEBUG(dbgs() << "Creating pre-indexed load/store.");
701 DEBUG(dbgs() << " Replacing instructions:\n ");
702 DEBUG(I->print(dbgs()));
703 DEBUG(dbgs() << " ");
704 DEBUG(Update->print(dbgs()));
705 DEBUG(dbgs() << " with instruction:\n ");
706 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
707 DEBUG(dbgs() << "\n");
708
709 // Erase the old instructions for the block.
710 I->eraseFromParent();
711 Update->eraseFromParent();
712
713 return NextI;
714}
715
716MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
717 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
718 assert((Update->getOpcode() == AArch64::ADDXri ||
719 Update->getOpcode() == AArch64::SUBXri) &&
720 "Unexpected base register update instruction to merge!");
721 MachineBasicBlock::iterator NextI = I;
722 // Return the instruction following the merged instruction, which is
723 // the instruction following our unmerged load. Unless that's the add/sub
724 // instruction we're merging, in which case it's the one after that.
725 if (++NextI == Update)
726 ++NextI;
727
728 int Value = Update->getOperand(2).getImm();
729 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
730 "Can't merge 1 << 12 offset into post-indexed load / store");
731 if (Update->getOpcode() == AArch64::SUBXri)
732 Value = -Value;
733
734 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
735 MachineInstrBuilder MIB =
736 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
737 .addOperand(Update->getOperand(0))
738 .addOperand(I->getOperand(0))
739 .addOperand(I->getOperand(1))
740 .addImm(Value);
741 (void)MIB;
742
743 DEBUG(dbgs() << "Creating post-indexed load/store.");
744 DEBUG(dbgs() << " Replacing instructions:\n ");
745 DEBUG(I->print(dbgs()));
746 DEBUG(dbgs() << " ");
747 DEBUG(Update->print(dbgs()));
748 DEBUG(dbgs() << " with instruction:\n ");
749 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
750 DEBUG(dbgs() << "\n");
751
752 // Erase the old instructions for the block.
753 I->eraseFromParent();
754 Update->eraseFromParent();
755
756 return NextI;
757}
758
759static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
760 int Offset) {
761 switch (MI->getOpcode()) {
762 default:
763 break;
764 case AArch64::SUBXri:
765 // Negate the offset for a SUB instruction.
766 Offset *= -1;
767 // FALLTHROUGH
768 case AArch64::ADDXri:
769 // Make sure it's a vanilla immediate operand, not a relocation or
770 // anything else we can't handle.
771 if (!MI->getOperand(2).isImm())
772 break;
773 // Watch out for 1 << 12 shifted value.
774 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
775 break;
776 // If the instruction has the base register as source and dest and the
777 // immediate will fit in a signed 9-bit integer, then we have a match.
778 if (MI->getOperand(0).getReg() == BaseReg &&
779 MI->getOperand(1).getReg() == BaseReg &&
780 MI->getOperand(2).getImm() <= 255 &&
781 MI->getOperand(2).getImm() >= -256) {
782 // If we have a non-zero Offset, we check that it matches the amount
783 // we're adding to the register.
784 if (!Offset || Offset == MI->getOperand(2).getImm())
785 return true;
786 }
787 break;
788 }
789 return false;
790}
791
792MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
793 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
794 MachineBasicBlock::iterator E = I->getParent()->end();
795 MachineInstr *MemMI = I;
796 MachineBasicBlock::iterator MBBI = I;
797 const MachineFunction &MF = *MemMI->getParent()->getParent();
798
799 unsigned DestReg = MemMI->getOperand(0).getReg();
800 unsigned BaseReg = MemMI->getOperand(1).getReg();
801 int Offset = MemMI->getOperand(2).getImm() *
802 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
803
804 // If the base register overlaps the destination register, we can't
805 // merge the update.
806 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
807 return E;
808
809 // Scan forward looking for post-index opportunities.
810 // Updating instructions can't be formed if the memory insn already
811 // has an offset other than the value we're looking for.
812 if (Offset != Value)
813 return E;
814
815 // Track which registers have been modified and used between the first insn
816 // (inclusive) and the second insn.
817 BitVector ModifiedRegs, UsedRegs;
818 ModifiedRegs.resize(TRI->getNumRegs());
819 UsedRegs.resize(TRI->getNumRegs());
820 ++MBBI;
821 for (unsigned Count = 0; MBBI != E; ++MBBI) {
822 MachineInstr *MI = MBBI;
823 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
824 // optimization by changing how far we scan.
825 if (MI->isDebugValue())
826 continue;
827
828 // Now that we know this is a real instruction, count it.
829 ++Count;
830
831 // If we found a match, return it.
832 if (isMatchingUpdateInsn(MI, BaseReg, Value))
833 return MBBI;
834
835 // Update the status of what the instruction clobbered and used.
836 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
837
838 // Otherwise, if the base register is used or modified, we have no match, so
839 // return early.
840 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
841 return E;
842 }
843 return E;
844}
845
846MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
847 MachineBasicBlock::iterator I, unsigned Limit) {
848 MachineBasicBlock::iterator B = I->getParent()->begin();
849 MachineBasicBlock::iterator E = I->getParent()->end();
850 MachineInstr *MemMI = I;
851 MachineBasicBlock::iterator MBBI = I;
852 const MachineFunction &MF = *MemMI->getParent()->getParent();
853
854 unsigned DestReg = MemMI->getOperand(0).getReg();
855 unsigned BaseReg = MemMI->getOperand(1).getReg();
856 int Offset = MemMI->getOperand(2).getImm();
857 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
858
859 // If the load/store is the first instruction in the block, there's obviously
860 // not any matching update. Ditto if the memory offset isn't zero.
861 if (MBBI == B || Offset != 0)
862 return E;
863 // If the base register overlaps the destination register, we can't
864 // merge the update.
865 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
866 return E;
867
868 // Track which registers have been modified and used between the first insn
869 // (inclusive) and the second insn.
870 BitVector ModifiedRegs, UsedRegs;
871 ModifiedRegs.resize(TRI->getNumRegs());
872 UsedRegs.resize(TRI->getNumRegs());
873 --MBBI;
874 for (unsigned Count = 0; MBBI != B; --MBBI) {
875 MachineInstr *MI = MBBI;
876 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
877 // optimization by changing how far we scan.
878 if (MI->isDebugValue())
879 continue;
880
881 // Now that we know this is a real instruction, count it.
882 ++Count;
883
884 // If we found a match, return it.
885 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
886 return MBBI;
887
888 // Update the status of what the instruction clobbered and used.
889 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
890
891 // Otherwise, if the base register is used or modified, we have no match, so
892 // return early.
893 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
894 return E;
895 }
896 return E;
897}
898
899bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
900 bool Modified = false;
901 // Two tranformations to do here:
902 // 1) Find loads and stores that can be merged into a single load or store
903 // pair instruction.
904 // e.g.,
905 // ldr x0, [x2]
906 // ldr x1, [x2, #8]
907 // ; becomes
908 // ldp x0, x1, [x2]
909 // 2) Find base register updates that can be merged into the load or store
910 // as a base-reg writeback.
911 // e.g.,
912 // ldr x0, [x2]
913 // add x2, x2, #4
914 // ; becomes
915 // ldr x0, [x2], #4
916
917 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
918 MBBI != E;) {
919 MachineInstr *MI = MBBI;
920 switch (MI->getOpcode()) {
921 default:
922 // Just move on to the next instruction.
923 ++MBBI;
924 break;
925 case AArch64::STRSui:
926 case AArch64::STRDui:
927 case AArch64::STRQui:
928 case AArch64::STRXui:
929 case AArch64::STRWui:
930 case AArch64::LDRSui:
931 case AArch64::LDRDui:
932 case AArch64::LDRQui:
933 case AArch64::LDRXui:
934 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +0000935 case AArch64::LDRSWui:
Tim Northover3b0846e2014-05-24 12:50:23 +0000936 // do the unscaled versions as well
937 case AArch64::STURSi:
938 case AArch64::STURDi:
939 case AArch64::STURQi:
940 case AArch64::STURWi:
941 case AArch64::STURXi:
942 case AArch64::LDURSi:
943 case AArch64::LDURDi:
944 case AArch64::LDURQi:
945 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000946 case AArch64::LDURXi:
947 case AArch64::LDURSWi: {
Tim Northover3b0846e2014-05-24 12:50:23 +0000948 // If this is a volatile load/store, don't mess with it.
949 if (MI->hasOrderedMemoryRef()) {
950 ++MBBI;
951 break;
952 }
953 // Make sure this is a reg+imm (as opposed to an address reloc).
954 if (!MI->getOperand(2).isImm()) {
955 ++MBBI;
956 break;
957 }
958 // Check if this load/store has a hint to avoid pair formation.
959 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
960 if (TII->isLdStPairSuppressed(MI)) {
961 ++MBBI;
962 break;
963 }
964 // Look ahead up to ScanLimit instructions for a pairable instruction.
Chad Rosier96a18a92015-07-21 17:42:04 +0000965 LdStPairFlags Flags;
Tim Northover3b0846e2014-05-24 12:50:23 +0000966 MachineBasicBlock::iterator Paired =
Chad Rosier96a18a92015-07-21 17:42:04 +0000967 findMatchingInsn(MBBI, Flags, ScanLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000968 if (Paired != E) {
969 // Merge the loads into a pair. Keeping the iterator straight is a
970 // pain, so we let the merge routine tell us what the next instruction
971 // is after it's done mucking about.
Chad Rosier96a18a92015-07-21 17:42:04 +0000972 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000973
974 Modified = true;
975 ++NumPairCreated;
976 if (isUnscaledLdst(MI->getOpcode()))
977 ++NumUnscaledPairCreated;
978 break;
979 }
980 ++MBBI;
981 break;
982 }
983 // FIXME: Do the other instructions.
984 }
985 }
986
987 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
988 MBBI != E;) {
989 MachineInstr *MI = MBBI;
990 // Do update merging. It's simpler to keep this separate from the above
991 // switch, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000992 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000993 switch (Opc) {
994 default:
995 // Just move on to the next instruction.
996 ++MBBI;
997 break;
998 case AArch64::STRSui:
999 case AArch64::STRDui:
1000 case AArch64::STRQui:
1001 case AArch64::STRXui:
1002 case AArch64::STRWui:
1003 case AArch64::LDRSui:
1004 case AArch64::LDRDui:
1005 case AArch64::LDRQui:
1006 case AArch64::LDRXui:
1007 case AArch64::LDRWui:
1008 // do the unscaled versions as well
1009 case AArch64::STURSi:
1010 case AArch64::STURDi:
1011 case AArch64::STURQi:
1012 case AArch64::STURWi:
1013 case AArch64::STURXi:
1014 case AArch64::LDURSi:
1015 case AArch64::LDURDi:
1016 case AArch64::LDURQi:
1017 case AArch64::LDURWi:
1018 case AArch64::LDURXi: {
1019 // Make sure this is a reg+imm (as opposed to an address reloc).
1020 if (!MI->getOperand(2).isImm()) {
1021 ++MBBI;
1022 break;
1023 }
1024 // Look ahead up to ScanLimit instructions for a mergable instruction.
1025 MachineBasicBlock::iterator Update =
1026 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1027 if (Update != E) {
1028 // Merge the update into the ld/st.
1029 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1030 Modified = true;
1031 ++NumPostFolded;
1032 break;
1033 }
1034 // Don't know how to handle pre/post-index versions, so move to the next
1035 // instruction.
1036 if (isUnscaledLdst(Opc)) {
1037 ++MBBI;
1038 break;
1039 }
1040
1041 // Look back to try to find a pre-index instruction. For example,
1042 // add x0, x0, #8
1043 // ldr x1, [x0]
1044 // merged into:
1045 // ldr x1, [x0, #8]!
1046 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1047 if (Update != E) {
1048 // Merge the update into the ld/st.
1049 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1050 Modified = true;
1051 ++NumPreFolded;
1052 break;
1053 }
1054
1055 // Look forward to try to find a post-index instruction. For example,
1056 // ldr x1, [x0, #64]
1057 // add x0, x0, #64
1058 // merged into:
1059 // ldr x1, [x0, #64]!
1060
1061 // The immediate in the load/store is scaled by the size of the register
1062 // being loaded. The immediate in the add we're looking for,
1063 // however, is not, so adjust here.
1064 int Value = MI->getOperand(2).getImm() *
1065 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1066 ->getSize();
1067 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1068 if (Update != E) {
1069 // Merge the update into the ld/st.
1070 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1071 Modified = true;
1072 ++NumPreFolded;
1073 break;
1074 }
1075
1076 // Nothing found. Just move to the next instruction.
1077 ++MBBI;
1078 break;
1079 }
1080 // FIXME: Do the other instructions.
1081 }
1082 }
1083
1084 return Modified;
1085}
1086
1087bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Eric Christopher6c901622015-01-28 03:51:33 +00001088 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1089 TRI = Fn.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001090
1091 bool Modified = false;
1092 for (auto &MBB : Fn)
1093 Modified |= optimizeBlock(MBB);
1094
1095 return Modified;
1096}
1097
1098// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1099// loads and stores near one another?
1100
1101/// createARMLoadStoreOptimizationPass - returns an instance of the load / store
1102/// optimization pass.
1103FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1104 return new AArch64LoadStoreOpt();
1105}