blob: d2555148ff0f54eae445026004a15d02b129a77a [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
Tim Northover3b0846e2014-05-24 12:50:23 +000036STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37STATISTIC(NumPostFolded, "Number of post-index updates folded");
38STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
Jun Bum Limc12c2792015-11-19 18:41:27 +000041STATISTIC(NumNarrowLoadsPromoted, "Number of narrow loads promoted");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000042STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000043STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000044
Chad Rosier35706ad2016-02-04 21:26:02 +000045// The LdStLimit limits how far we search for load/store pairs.
46static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000047 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000048
Chad Rosier35706ad2016-02-04 21:26:02 +000049// The UpdateLimit limits how far we search for update instructions when we form
50// pre-/post-index instructions.
51static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
52 cl::Hidden);
53
Chad Rosier96530b32015-08-05 13:44:51 +000054namespace llvm {
55void initializeAArch64LoadStoreOptPass(PassRegistry &);
56}
57
58#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
59
Tim Northover3b0846e2014-05-24 12:50:23 +000060namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000061
62typedef struct LdStPairFlags {
63 // If a matching instruction is found, MergeForward is set to true if the
64 // merge is to remove the first instruction and replace the second with
65 // a pair-wise insn, and false if the reverse is true.
66 bool MergeForward;
67
68 // SExtIdx gives the index of the result of the load pair that must be
69 // extended. The value of SExtIdx assumes that the paired load produces the
70 // value in this order: (I, returned iterator), i.e., -1 means no value has
71 // to be extended, 0 means I, and 1 means the returned iterator.
72 int SExtIdx;
73
74 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75
76 void setMergeForward(bool V = true) { MergeForward = V; }
77 bool getMergeForward() const { return MergeForward; }
78
79 void setSExtIdx(int V) { SExtIdx = V; }
80 int getSExtIdx() const { return SExtIdx; }
81
82} LdStPairFlags;
83
Tim Northover3b0846e2014-05-24 12:50:23 +000084struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000086 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000087 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
88 }
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 const AArch64InstrInfo *TII;
91 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000092 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
Chad Rosierbba881e2016-02-02 15:02:30 +000094 // Track which registers have been modified and used.
95 BitVector ModifiedRegs, UsedRegs;
96
Tim Northover3b0846e2014-05-24 12:50:23 +000097 // Scan the instructions looking for a load/store that can be combined
98 // with the current instruction into a load/store pair.
99 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000101 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +0000102 unsigned Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000103
104 // Scan the instructions looking for a store that writes to the address from
105 // which the current load instruction reads. Return true if one is found.
106 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
107 MachineBasicBlock::iterator &StoreI);
108
Chad Rosierb5933d72016-02-09 19:02:12 +0000109 // Merge the two instructions indicated into a wider instruction.
110 MachineBasicBlock::iterator
111 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000112 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000113 const LdStPairFlags &Flags);
114
Tim Northover3b0846e2014-05-24 12:50:23 +0000115 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000116 MachineBasicBlock::iterator
117 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000118 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000119 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000120
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000121 // Promote the load that reads directly from the address stored to.
122 MachineBasicBlock::iterator
123 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
124 MachineBasicBlock::iterator StoreI);
125
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 // Scan the instruction list to find a base register update that can
127 // be combined with the current instruction (a load or store) using
128 // pre or post indexed addressing with writeback. Scan forwards.
129 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000130 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000131 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000132
133 // Scan the instruction list to find a base register update that can
134 // be combined with the current instruction (a load or store) using
135 // pre or post indexed addressing with writeback. Scan backwards.
136 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000137 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000138
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000139 // Find an instruction that updates the base register of the ld/st
140 // instruction.
141 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
142 unsigned BaseReg, int Offset);
143
Chad Rosier2dfd3542015-09-23 13:51:44 +0000144 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000146 mergeUpdateInsn(MachineBasicBlock::iterator I,
147 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000148
Chad Rosier24c46ad2016-02-09 18:10:20 +0000149 // Is this a candidate for ld/st merging or pairing? For example, we don't
150 // touch volatiles or load/stores that have a hint to avoid pair formation.
151 bool isCandidateToMergeOrPair(MachineInstr *MI);
152
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000153 // Find and merge foldable ldr/str instructions.
154 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
155
Chad Rosier24c46ad2016-02-09 18:10:20 +0000156 // Find and pair ldr/str instructions.
157 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
158
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000159 // Find and promote load instructions which read directly from store.
160 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
161
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000162 // Check if converting two narrow loads into a single wider load with
163 // bitfield extracts could be enabled.
164 bool enableNarrowLdMerge(MachineFunction &Fn);
165
166 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000167
168 bool runOnMachineFunction(MachineFunction &Fn) override;
169
170 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000171 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000173};
174char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000175} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000176
Chad Rosier96530b32015-08-05 13:44:51 +0000177INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
178 AARCH64_LOAD_STORE_OPT_NAME, false, false)
179
Chad Rosier22eb7102015-08-06 17:37:18 +0000180static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 switch (Opc) {
182 default:
183 return false;
184 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000187 case AArch64::STURBBi:
188 case AArch64::STURHHi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000196 case AArch64::LDURSWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000197 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000198 case AArch64::LDURBBi:
199 case AArch64::LDURSBWi:
200 case AArch64::LDURSHWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000201 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000202 }
203}
204
Chad Rosier22eb7102015-08-06 17:37:18 +0000205static bool isUnscaledLdSt(MachineInstr *MI) {
206 return isUnscaledLdSt(MI->getOpcode());
207}
208
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000209static unsigned getBitExtrOpcode(MachineInstr *MI) {
210 switch (MI->getOpcode()) {
211 default:
212 llvm_unreachable("Unexpected opcode.");
213 case AArch64::LDRBBui:
214 case AArch64::LDURBBi:
215 case AArch64::LDRHHui:
216 case AArch64::LDURHHi:
217 return AArch64::UBFMWri;
218 case AArch64::LDRSBWui:
219 case AArch64::LDURSBWi:
220 case AArch64::LDRSHWui:
221 case AArch64::LDURSHWi:
222 return AArch64::SBFMWri;
223 }
224}
225
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000226static bool isNarrowStore(unsigned Opc) {
227 switch (Opc) {
228 default:
229 return false;
230 case AArch64::STRBBui:
231 case AArch64::STURBBi:
232 case AArch64::STRHHui:
233 case AArch64::STURHHi:
234 return true;
235 }
236}
237
238static bool isNarrowStore(MachineInstr *MI) {
239 return isNarrowStore(MI->getOpcode());
240}
241
Jun Bum Limc12c2792015-11-19 18:41:27 +0000242static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000243 switch (Opc) {
244 default:
245 return false;
246 case AArch64::LDRHHui:
247 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000248 case AArch64::LDRBBui:
249 case AArch64::LDURBBi:
250 case AArch64::LDRSHWui:
251 case AArch64::LDURSHWi:
252 case AArch64::LDRSBWui:
253 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000254 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000255 }
256}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000257
Jun Bum Limc12c2792015-11-19 18:41:27 +0000258static bool isNarrowLoad(MachineInstr *MI) {
259 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000260}
261
Chad Rosier00f9d232016-02-11 14:25:08 +0000262static bool isNarrowLoadOrStore(unsigned Opc) {
263 return isNarrowLoad(Opc) || isNarrowStore(Opc);
264}
265
Chad Rosier32d4d372015-09-29 16:07:32 +0000266// Scaling factor for unscaled load or store.
267static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000268 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000269 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000270 llvm_unreachable("Opcode has unknown scale!");
271 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000272 case AArch64::LDURBBi:
273 case AArch64::LDRSBWui:
274 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000275 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000276 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000277 return 1;
278 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000279 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000280 case AArch64::LDRSHWui:
281 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000282 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000283 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000284 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000285 case AArch64::LDRSui:
286 case AArch64::LDURSi:
287 case AArch64::LDRSWui:
288 case AArch64::LDURSWi:
289 case AArch64::LDRWui:
290 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000291 case AArch64::STRSui:
292 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000293 case AArch64::STRWui:
294 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000295 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000296 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000297 case AArch64::LDPWi:
298 case AArch64::STPSi:
299 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000300 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000301 case AArch64::LDRDui:
302 case AArch64::LDURDi:
303 case AArch64::LDRXui:
304 case AArch64::LDURXi:
305 case AArch64::STRDui:
306 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000307 case AArch64::STRXui:
308 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000309 case AArch64::LDPDi:
310 case AArch64::LDPXi:
311 case AArch64::STPDi:
312 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000313 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000314 case AArch64::LDRQui:
315 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000316 case AArch64::STRQui:
317 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000318 case AArch64::LDPQi:
319 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000320 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000321 }
322}
323
Quentin Colombet66b61632015-03-06 22:42:10 +0000324static unsigned getMatchingNonSExtOpcode(unsigned Opc,
325 bool *IsValidLdStrOpc = nullptr) {
326 if (IsValidLdStrOpc)
327 *IsValidLdStrOpc = true;
328 switch (Opc) {
329 default:
330 if (IsValidLdStrOpc)
331 *IsValidLdStrOpc = false;
332 return UINT_MAX;
333 case AArch64::STRDui:
334 case AArch64::STURDi:
335 case AArch64::STRQui:
336 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000337 case AArch64::STRBBui:
338 case AArch64::STURBBi:
339 case AArch64::STRHHui:
340 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000341 case AArch64::STRWui:
342 case AArch64::STURWi:
343 case AArch64::STRXui:
344 case AArch64::STURXi:
345 case AArch64::LDRDui:
346 case AArch64::LDURDi:
347 case AArch64::LDRQui:
348 case AArch64::LDURQi:
349 case AArch64::LDRWui:
350 case AArch64::LDURWi:
351 case AArch64::LDRXui:
352 case AArch64::LDURXi:
353 case AArch64::STRSui:
354 case AArch64::STURSi:
355 case AArch64::LDRSui:
356 case AArch64::LDURSi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000357 case AArch64::LDRHHui:
358 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000359 case AArch64::LDRBBui:
360 case AArch64::LDURBBi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000361 return Opc;
362 case AArch64::LDRSWui:
363 return AArch64::LDRWui;
364 case AArch64::LDURSWi:
365 return AArch64::LDURWi;
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000366 case AArch64::LDRSBWui:
367 return AArch64::LDRBBui;
368 case AArch64::LDRSHWui:
369 return AArch64::LDRHHui;
370 case AArch64::LDURSBWi:
371 return AArch64::LDURBBi;
372 case AArch64::LDURSHWi:
373 return AArch64::LDURHHi;
Quentin Colombet66b61632015-03-06 22:42:10 +0000374 }
375}
376
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000377static unsigned getMatchingWideOpcode(unsigned Opc) {
378 switch (Opc) {
379 default:
380 llvm_unreachable("Opcode has no wide equivalent!");
381 case AArch64::STRBBui:
382 return AArch64::STRHHui;
383 case AArch64::STRHHui:
384 return AArch64::STRWui;
385 case AArch64::STURBBi:
386 return AArch64::STURHHi;
387 case AArch64::STURHHi:
388 return AArch64::STURWi;
389 case AArch64::LDRHHui:
390 case AArch64::LDRSHWui:
391 return AArch64::LDRWui;
392 case AArch64::LDURHHi:
393 case AArch64::LDURSHWi:
394 return AArch64::LDURWi;
395 case AArch64::LDRBBui:
396 case AArch64::LDRSBWui:
397 return AArch64::LDRHHui;
398 case AArch64::LDURBBi:
399 case AArch64::LDURSBWi:
400 return AArch64::LDURHHi;
401 }
402}
403
Tim Northover3b0846e2014-05-24 12:50:23 +0000404static unsigned getMatchingPairOpcode(unsigned Opc) {
405 switch (Opc) {
406 default:
407 llvm_unreachable("Opcode has no pairwise equivalent!");
408 case AArch64::STRSui:
409 case AArch64::STURSi:
410 return AArch64::STPSi;
411 case AArch64::STRDui:
412 case AArch64::STURDi:
413 return AArch64::STPDi;
414 case AArch64::STRQui:
415 case AArch64::STURQi:
416 return AArch64::STPQi;
417 case AArch64::STRWui:
418 case AArch64::STURWi:
419 return AArch64::STPWi;
420 case AArch64::STRXui:
421 case AArch64::STURXi:
422 return AArch64::STPXi;
423 case AArch64::LDRSui:
424 case AArch64::LDURSi:
425 return AArch64::LDPSi;
426 case AArch64::LDRDui:
427 case AArch64::LDURDi:
428 return AArch64::LDPDi;
429 case AArch64::LDRQui:
430 case AArch64::LDURQi:
431 return AArch64::LDPQi;
432 case AArch64::LDRWui:
433 case AArch64::LDURWi:
434 return AArch64::LDPWi;
435 case AArch64::LDRXui:
436 case AArch64::LDURXi:
437 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000438 case AArch64::LDRSWui:
439 case AArch64::LDURSWi:
440 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000441 }
442}
443
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000444static unsigned isMatchingStore(MachineInstr *LoadInst,
445 MachineInstr *StoreInst) {
446 unsigned LdOpc = LoadInst->getOpcode();
447 unsigned StOpc = StoreInst->getOpcode();
448 switch (LdOpc) {
449 default:
450 llvm_unreachable("Unsupported load instruction!");
451 case AArch64::LDRBBui:
452 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
453 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
454 case AArch64::LDURBBi:
455 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
456 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
457 case AArch64::LDRHHui:
458 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
459 StOpc == AArch64::STRXui;
460 case AArch64::LDURHHi:
461 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
462 StOpc == AArch64::STURXi;
463 case AArch64::LDRWui:
464 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
465 case AArch64::LDURWi:
466 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
467 case AArch64::LDRXui:
468 return StOpc == AArch64::STRXui;
469 case AArch64::LDURXi:
470 return StOpc == AArch64::STURXi;
471 }
472}
473
Tim Northover3b0846e2014-05-24 12:50:23 +0000474static unsigned getPreIndexedOpcode(unsigned Opc) {
475 switch (Opc) {
476 default:
477 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000478 case AArch64::STRSui:
479 return AArch64::STRSpre;
480 case AArch64::STRDui:
481 return AArch64::STRDpre;
482 case AArch64::STRQui:
483 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000484 case AArch64::STRBBui:
485 return AArch64::STRBBpre;
486 case AArch64::STRHHui:
487 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000488 case AArch64::STRWui:
489 return AArch64::STRWpre;
490 case AArch64::STRXui:
491 return AArch64::STRXpre;
492 case AArch64::LDRSui:
493 return AArch64::LDRSpre;
494 case AArch64::LDRDui:
495 return AArch64::LDRDpre;
496 case AArch64::LDRQui:
497 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000498 case AArch64::LDRBBui:
499 return AArch64::LDRBBpre;
500 case AArch64::LDRHHui:
501 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000502 case AArch64::LDRWui:
503 return AArch64::LDRWpre;
504 case AArch64::LDRXui:
505 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000506 case AArch64::LDRSWui:
507 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000508 case AArch64::LDPSi:
509 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000510 case AArch64::LDPSWi:
511 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000512 case AArch64::LDPDi:
513 return AArch64::LDPDpre;
514 case AArch64::LDPQi:
515 return AArch64::LDPQpre;
516 case AArch64::LDPWi:
517 return AArch64::LDPWpre;
518 case AArch64::LDPXi:
519 return AArch64::LDPXpre;
520 case AArch64::STPSi:
521 return AArch64::STPSpre;
522 case AArch64::STPDi:
523 return AArch64::STPDpre;
524 case AArch64::STPQi:
525 return AArch64::STPQpre;
526 case AArch64::STPWi:
527 return AArch64::STPWpre;
528 case AArch64::STPXi:
529 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 }
531}
532
533static unsigned getPostIndexedOpcode(unsigned Opc) {
534 switch (Opc) {
535 default:
536 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
537 case AArch64::STRSui:
538 return AArch64::STRSpost;
539 case AArch64::STRDui:
540 return AArch64::STRDpost;
541 case AArch64::STRQui:
542 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000543 case AArch64::STRBBui:
544 return AArch64::STRBBpost;
545 case AArch64::STRHHui:
546 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000547 case AArch64::STRWui:
548 return AArch64::STRWpost;
549 case AArch64::STRXui:
550 return AArch64::STRXpost;
551 case AArch64::LDRSui:
552 return AArch64::LDRSpost;
553 case AArch64::LDRDui:
554 return AArch64::LDRDpost;
555 case AArch64::LDRQui:
556 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000557 case AArch64::LDRBBui:
558 return AArch64::LDRBBpost;
559 case AArch64::LDRHHui:
560 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000561 case AArch64::LDRWui:
562 return AArch64::LDRWpost;
563 case AArch64::LDRXui:
564 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000565 case AArch64::LDRSWui:
566 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 case AArch64::LDPSi:
568 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000569 case AArch64::LDPSWi:
570 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000571 case AArch64::LDPDi:
572 return AArch64::LDPDpost;
573 case AArch64::LDPQi:
574 return AArch64::LDPQpost;
575 case AArch64::LDPWi:
576 return AArch64::LDPWpost;
577 case AArch64::LDPXi:
578 return AArch64::LDPXpost;
579 case AArch64::STPSi:
580 return AArch64::STPSpost;
581 case AArch64::STPDi:
582 return AArch64::STPDpost;
583 case AArch64::STPQi:
584 return AArch64::STPQpost;
585 case AArch64::STPWi:
586 return AArch64::STPWpost;
587 case AArch64::STPXi:
588 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 }
590}
591
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000592static bool isPairedLdSt(const MachineInstr *MI) {
593 switch (MI->getOpcode()) {
594 default:
595 return false;
596 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000597 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000598 case AArch64::LDPDi:
599 case AArch64::LDPQi:
600 case AArch64::LDPWi:
601 case AArch64::LDPXi:
602 case AArch64::STPSi:
603 case AArch64::STPDi:
604 case AArch64::STPQi:
605 case AArch64::STPWi:
606 case AArch64::STPXi:
607 return true;
608 }
609}
610
611static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
612 unsigned PairedRegOp = 0) {
613 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
614 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
615 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000616}
617
618static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000619 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
620 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000621}
622
623static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000624 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
625 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000626}
627
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000628static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
629 MachineInstr *StoreInst) {
630 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
631 int LoadSize = getMemScale(LoadInst);
632 int StoreSize = getMemScale(StoreInst);
633 int UnscaledStOffset = isUnscaledLdSt(StoreInst)
634 ? getLdStOffsetOp(StoreInst).getImm()
635 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
636 int UnscaledLdOffset = isUnscaledLdSt(LoadInst)
637 ? getLdStOffsetOp(LoadInst).getImm()
638 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
639 return (UnscaledStOffset <= UnscaledLdOffset) &&
640 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
641}
642
Tim Northover3b0846e2014-05-24 12:50:23 +0000643MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000644AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000645 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000646 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 MachineBasicBlock::iterator NextI = I;
648 ++NextI;
649 // If NextI is the second of the two instructions to be merged, we need
650 // to skip one further. Either way we merge will invalidate the iterator,
651 // and we don't need to scan the new instruction, as it's a pairwise
652 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000653 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000654 ++NextI;
655
Chad Rosierb5933d72016-02-09 19:02:12 +0000656 unsigned Opc = I->getOpcode();
Chad Rosier11eedc92016-02-09 19:17:18 +0000657 bool IsScaled = !isUnscaledLdSt(Opc);
658 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000659
Chad Rosier96a18a92015-07-21 17:42:04 +0000660 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000661 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000662 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000663 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000664 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000665 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000666 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000667 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000668
669 // Which register is Rt and which is Rt2 depends on the offset order.
670 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000671 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000672 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
673 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 Rt2MI = I;
675 } else {
676 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000677 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000678 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000679
James Molloy5b18b4c2015-10-23 10:41:38 +0000680 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000681 // Change the scaled offset from small to large type.
682 if (IsScaled) {
683 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
684 OffsetImm /= 2;
685 }
686
Chad Rosierc46ef882016-02-09 19:33:42 +0000687 DebugLoc DL = I->getDebugLoc();
688 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000689 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000690 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000691 // When merging small (< 32 bit) loads for big-endian targets, the order of
692 // the component parts gets swapped.
693 if (!Subtarget->isLittleEndian())
694 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000695 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000696 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000697 NewMemMI =
698 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
699 .addOperand(getLdStRegOp(RtNewDest))
700 .addOperand(BaseRegOp)
701 .addImm(OffsetImm)
702 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000703
704 DEBUG(
705 dbgs()
706 << "Creating the new load and extract. Replacing instructions:\n ");
707 DEBUG(I->print(dbgs()));
708 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000709 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000710 DEBUG(dbgs() << " with instructions:\n ");
711 DEBUG((NewMemMI)->print(dbgs()));
712
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000713 int Width = getMemScale(I) == 1 ? 8 : 16;
714 int LSBLow = 0;
715 int LSBHigh = Width;
716 int ImmsLow = LSBLow + Width - 1;
717 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000718 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000719 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000720 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000721 BitExtMI1 =
722 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
723 .addOperand(getLdStRegOp(Rt2MI))
724 .addReg(getLdStRegOp(RtNewDest).getReg())
725 .addImm(LSBHigh)
726 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000727 // Create the bitfield extract for low bits.
728 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
729 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000730 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000731 .addOperand(getLdStRegOp(RtMI))
732 .addReg(getLdStRegOp(RtNewDest).getReg())
733 .addImm(ImmsLow);
734 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000735 BitExtMI2 =
736 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
737 .addOperand(getLdStRegOp(RtMI))
738 .addReg(getLdStRegOp(RtNewDest).getReg())
739 .addImm(LSBLow)
740 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000741 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000742 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000743 // Create the bitfield extract for low bits.
744 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
745 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000746 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000747 .addOperand(getLdStRegOp(RtMI))
748 .addReg(getLdStRegOp(RtNewDest).getReg())
749 .addImm(ImmsLow);
750 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000751 BitExtMI1 =
752 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
753 .addOperand(getLdStRegOp(RtMI))
754 .addReg(getLdStRegOp(RtNewDest).getReg())
755 .addImm(LSBLow)
756 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000757 }
758
759 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000760 BitExtMI2 =
761 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
762 .addOperand(getLdStRegOp(Rt2MI))
763 .addReg(getLdStRegOp(RtNewDest).getReg())
764 .addImm(LSBHigh)
765 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000766 }
767 DEBUG(dbgs() << " ");
768 DEBUG((BitExtMI1)->print(dbgs()));
769 DEBUG(dbgs() << " ");
770 DEBUG((BitExtMI2)->print(dbgs()));
771 DEBUG(dbgs() << "\n");
772
773 // Erase the old instructions.
774 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000775 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000776 return NextI;
777 }
Chad Rosier11eedc92016-02-09 19:17:18 +0000778 assert(isNarrowStore(Opc) && "Expected narrow store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000779
Tim Northover3b0846e2014-05-24 12:50:23 +0000780 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000781 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000782 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000783 .addOperand(getLdStRegOp(I))
784 .addOperand(BaseRegOp)
785 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000786 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000787
Tim Northover3b0846e2014-05-24 12:50:23 +0000788 (void)MIB;
789
Chad Rosierb5933d72016-02-09 19:02:12 +0000790 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
791 DEBUG(I->print(dbgs()));
792 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000793 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000794 DEBUG(dbgs() << " with instruction:\n ");
795 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
796 DEBUG(dbgs() << "\n");
797
798 // Erase the old instructions.
799 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000800 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000801 return NextI;
802}
803
804MachineBasicBlock::iterator
805AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
806 MachineBasicBlock::iterator Paired,
807 const LdStPairFlags &Flags) {
808 MachineBasicBlock::iterator NextI = I;
809 ++NextI;
810 // If NextI is the second of the two instructions to be merged, we need
811 // to skip one further. Either way we merge will invalidate the iterator,
812 // and we don't need to scan the new instruction, as it's a pairwise
813 // instruction, which we're not considering for further action anyway.
814 if (NextI == Paired)
815 ++NextI;
816
817 int SExtIdx = Flags.getSExtIdx();
818 unsigned Opc =
819 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
820 bool IsUnscaled = isUnscaledLdSt(Opc);
821 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
822
823 bool MergeForward = Flags.getMergeForward();
824 // Insert our new paired instruction after whichever of the paired
825 // instructions MergeForward indicates.
826 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
827 // Also based on MergeForward is from where we copy the base register operand
828 // so we get the flags compatible with the input code.
829 const MachineOperand &BaseRegOp =
830 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
831
Chad Rosier00f9d232016-02-11 14:25:08 +0000832 int Offset = getLdStOffsetOp(I).getImm();
833 int PairedOffset = getLdStOffsetOp(Paired).getImm();
834 bool PairedIsUnscaled = isUnscaledLdSt(Paired->getOpcode());
835 if (IsUnscaled != PairedIsUnscaled) {
836 // We're trying to pair instructions that differ in how they are scaled. If
837 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
838 // the opposite (i.e., make Paired's offset unscaled).
839 int MemSize = getMemScale(Paired);
840 if (PairedIsUnscaled) {
841 // If the unscaled offset isn't a multiple of the MemSize, we can't
842 // pair the operations together.
843 assert(!(PairedOffset % getMemScale(Paired)) &&
844 "Offset should be a multiple of the stride!");
845 PairedOffset /= MemSize;
846 } else {
847 PairedOffset *= MemSize;
848 }
849 }
850
Chad Rosierb5933d72016-02-09 19:02:12 +0000851 // Which register is Rt and which is Rt2 depends on the offset order.
852 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000853 if (Offset == PairedOffset + OffsetStride) {
Chad Rosierb5933d72016-02-09 19:02:12 +0000854 RtMI = Paired;
855 Rt2MI = I;
856 // Here we swapped the assumption made for SExtIdx.
857 // I.e., we turn ldp I, Paired into ldp Paired, I.
858 // Update the index accordingly.
859 if (SExtIdx != -1)
860 SExtIdx = (SExtIdx + 1) % 2;
861 } else {
862 RtMI = I;
863 Rt2MI = Paired;
864 }
865 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000866 // Scale the immediate offset, if necessary.
867 if (isUnscaledLdSt(RtMI->getOpcode())) {
868 assert(!(OffsetImm % getMemScale(RtMI)) &&
869 "Unscaled offset cannot be scaled.");
870 OffsetImm /= getMemScale(RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000871 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000872
873 // Construct the new instruction.
874 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000875 DebugLoc DL = I->getDebugLoc();
876 MachineBasicBlock *MBB = I->getParent();
877 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000878 .addOperand(getLdStRegOp(RtMI))
879 .addOperand(getLdStRegOp(Rt2MI))
880 .addOperand(BaseRegOp)
881 .addImm(OffsetImm);
882 // FIXME: Copy the mem operands from the source instructions. The MI scheduler
883 // needs these to reason about loads/stores.
884
885 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000886
887 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
888 DEBUG(I->print(dbgs()));
889 DEBUG(dbgs() << " ");
890 DEBUG(Paired->print(dbgs()));
891 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000892 if (SExtIdx != -1) {
893 // Generate the sign extension for the proper result of the ldp.
894 // I.e., with X1, that would be:
895 // %W1<def> = KILL %W1, %X1<imp-def>
896 // %X1<def> = SBFMXri %X1<kill>, 0, 31
897 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
898 // Right now, DstMO has the extended register, since it comes from an
899 // extended opcode.
900 unsigned DstRegX = DstMO.getReg();
901 // Get the W variant of that register.
902 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
903 // Update the result of LDP to use the W instead of the X variant.
904 DstMO.setReg(DstRegW);
905 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
906 DEBUG(dbgs() << "\n");
907 // Make the machine verifier happy by providing a definition for
908 // the X register.
909 // Insert this definition right after the generated LDP, i.e., before
910 // InsertionPoint.
911 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000912 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000913 .addReg(DstRegW)
914 .addReg(DstRegX, RegState::Define);
915 MIBKill->getOperand(2).setImplicit();
916 // Create the sign extension.
917 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000918 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000919 .addReg(DstRegX)
920 .addImm(0)
921 .addImm(31);
922 (void)MIBSXTW;
923 DEBUG(dbgs() << " Extend operand:\n ");
924 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000925 } else {
926 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000927 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000928 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000929
930 // Erase the old instructions.
931 I->eraseFromParent();
932 Paired->eraseFromParent();
933
934 return NextI;
935}
936
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000937MachineBasicBlock::iterator
938AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
939 MachineBasicBlock::iterator StoreI) {
940 MachineBasicBlock::iterator NextI = LoadI;
941 ++NextI;
942
943 int LoadSize = getMemScale(LoadI);
944 int StoreSize = getMemScale(StoreI);
945 unsigned LdRt = getLdStRegOp(LoadI).getReg();
946 unsigned StRt = getLdStRegOp(StoreI).getReg();
947 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
948
949 assert((IsStoreXReg ||
950 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
951 "Unexpected RegClass");
952
953 MachineInstr *BitExtMI;
954 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
955 // Remove the load, if the destination register of the loads is the same
956 // register for stored value.
957 if (StRt == LdRt && LoadSize == 8) {
958 DEBUG(dbgs() << "Remove load instruction:\n ");
959 DEBUG(LoadI->print(dbgs()));
960 DEBUG(dbgs() << "\n");
961 LoadI->eraseFromParent();
962 return NextI;
963 }
964 // Replace the load with a mov if the load and store are in the same size.
965 BitExtMI =
966 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
967 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
968 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
969 .addReg(StRt)
970 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
971 } else {
972 // FIXME: Currently we disable this transformation in big-endian targets as
973 // performance and correctness are verified only in little-endian.
974 if (!Subtarget->isLittleEndian())
975 return NextI;
976 bool IsUnscaled = isUnscaledLdSt(LoadI);
977 assert(IsUnscaled == isUnscaledLdSt(StoreI) && "Unsupported ld/st match");
978 assert(LoadSize <= StoreSize && "Invalid load size");
979 int UnscaledLdOffset = IsUnscaled
980 ? getLdStOffsetOp(LoadI).getImm()
981 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
982 int UnscaledStOffset = IsUnscaled
983 ? getLdStOffsetOp(StoreI).getImm()
984 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
985 int Width = LoadSize * 8;
986 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
987 int Imms = Immr + Width - 1;
988 unsigned DestReg = IsStoreXReg
989 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
990 &AArch64::GPR64RegClass)
991 : LdRt;
992
993 assert((UnscaledLdOffset >= UnscaledStOffset &&
994 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
995 "Invalid offset");
996
997 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
998 Imms = Immr + Width - 1;
999 if (UnscaledLdOffset == UnscaledStOffset) {
1000 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1001 | ((Immr) << 6) // immr
1002 | ((Imms) << 0) // imms
1003 ;
1004
1005 BitExtMI =
1006 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1007 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1008 DestReg)
1009 .addReg(StRt)
1010 .addImm(AndMaskEncoded);
1011 } else {
1012 BitExtMI =
1013 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1014 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1015 DestReg)
1016 .addReg(StRt)
1017 .addImm(Immr)
1018 .addImm(Imms);
1019 }
1020 }
1021
1022 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1023 DEBUG(StoreI->print(dbgs()));
1024 DEBUG(dbgs() << " ");
1025 DEBUG(LoadI->print(dbgs()));
1026 DEBUG(dbgs() << " with instructions:\n ");
1027 DEBUG(StoreI->print(dbgs()));
1028 DEBUG(dbgs() << " ");
1029 DEBUG((BitExtMI)->print(dbgs()));
1030 DEBUG(dbgs() << "\n");
1031
1032 // Erase the old instructions.
1033 LoadI->eraseFromParent();
1034 return NextI;
1035}
1036
Tim Northover3b0846e2014-05-24 12:50:23 +00001037/// trackRegDefsUses - Remember what registers the specified instruction uses
1038/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001039static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001040 BitVector &UsedRegs,
1041 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001042 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001043 if (MO.isRegMask())
1044 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1045
1046 if (!MO.isReg())
1047 continue;
1048 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001049 if (!Reg)
1050 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001051 if (MO.isDef()) {
1052 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1053 ModifiedRegs.set(*AI);
1054 } else {
1055 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1056 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1057 UsedRegs.set(*AI);
1058 }
1059 }
1060}
1061
1062static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001063 // Convert the byte-offset used by unscaled into an "element" offset used
1064 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001065 if (IsUnscaled) {
1066 // If the byte-offset isn't a multiple of the stride, there's no point
1067 // trying to match it.
1068 if (Offset % OffsetStride)
1069 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001070 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001071 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001072 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001073}
1074
1075// Do alignment, specialized to power of 2 and for signed ints,
1076// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001077// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001078// FIXME: Move this function to include/MathExtras.h?
1079static int alignTo(int Num, int PowOf2) {
1080 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1081}
1082
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001083static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1084 const AArch64InstrInfo *TII) {
1085 // One of the instructions must modify memory.
1086 if (!MIa->mayStore() && !MIb->mayStore())
1087 return false;
1088
1089 // Both instructions must be memory operations.
1090 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1091 return false;
1092
1093 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1094}
1095
1096static bool mayAlias(MachineInstr *MIa,
1097 SmallVectorImpl<MachineInstr *> &MemInsns,
1098 const AArch64InstrInfo *TII) {
1099 for (auto &MIb : MemInsns)
1100 if (mayAlias(MIa, MIb, TII))
1101 return true;
1102
1103 return false;
1104}
1105
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001106bool AArch64LoadStoreOpt::findMatchingStore(
1107 MachineBasicBlock::iterator I, unsigned Limit,
1108 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001109 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001110 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001111 MachineInstr *LoadMI = I;
1112 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001113
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001114 // If the load is the first instruction in the block, there's obviously
1115 // not any matching store.
1116 if (MBBI == B)
1117 return false;
1118
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001119 // Track which registers have been modified and used between the first insn
1120 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001121 ModifiedRegs.reset();
1122 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001123
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001124 unsigned Count = 0;
1125 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001126 --MBBI;
1127 MachineInstr *MI = MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001128
1129 // Don't count DBG_VALUE instructions towards the search limit.
1130 if (!MI->isDebugValue())
1131 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001132
1133 // If the load instruction reads directly from the address to which the
1134 // store instruction writes and the stored value is not modified, we can
1135 // promote the load. Since we do not handle stores with pre-/post-index,
1136 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001137 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001138 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001139 isLdOffsetInRangeOfSt(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001140 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1141 StoreI = MBBI;
1142 return true;
1143 }
1144
1145 if (MI->isCall())
1146 return false;
1147
1148 // Update modified / uses register lists.
1149 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1150
1151 // Otherwise, if the base register is modified, we have no match, so
1152 // return early.
1153 if (ModifiedRegs[BaseReg])
1154 return false;
1155
1156 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001157 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001158 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001159 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001160 return false;
1161}
1162
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001163// Returns true if these two opcodes can be merged or paired. Otherwise,
1164// returns false.
1165static bool canMergeOpc(unsigned OpcA, unsigned OpcB, LdStPairFlags &Flags) {
1166 // Opcodes match: nothing more to check.
1167 if (OpcA == OpcB)
1168 return true;
1169
1170 // Try to match a sign-extended load/store with a zero-extended load/store.
1171 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1172 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1173 assert(IsValidLdStrOpc &&
1174 "Given Opc should be a Load or Store with an immediate");
1175 // OpcA will be the first instruction in the pair.
1176 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1177 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1178 return true;
1179 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001180
1181 // If the second instruction isn't even a load/store, bail out.
1182 if (!PairIsValidLdStrOpc)
1183 return false;
1184
1185 // FIXME: We don't support merging narrow loads/stores with mixed
1186 // scaled/unscaled offsets.
1187 if (isNarrowLoadOrStore(OpcA) || isNarrowLoadOrStore(OpcB))
1188 return false;
1189
1190 // Try to match an unscaled load/store with a scaled load/store.
1191 return isUnscaledLdSt(OpcA) != isUnscaledLdSt(OpcB) &&
1192 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1193
1194 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001195}
1196
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001197/// Scan the instructions looking for a load/store that can be combined with the
1198/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001199MachineBasicBlock::iterator
1200AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001201 LdStPairFlags &Flags, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001202 MachineBasicBlock::iterator E = I->getParent()->end();
1203 MachineBasicBlock::iterator MBBI = I;
1204 MachineInstr *FirstMI = I;
1205 ++MBBI;
1206
Matthias Braunfa3872e2015-05-18 20:27:55 +00001207 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001208 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +00001209 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001210 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1211 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1212 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001213 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001214 bool IsNarrowStore = isNarrowStore(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +00001215
1216 // Track which registers have been modified and used between the first insn
1217 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001218 ModifiedRegs.reset();
1219 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001220
1221 // Remember any instructions that read/write memory between FirstMI and MI.
1222 SmallVector<MachineInstr *, 4> MemInsns;
1223
Tim Northover3b0846e2014-05-24 12:50:23 +00001224 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1225 MachineInstr *MI = MBBI;
1226 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1227 // optimization by changing how far we scan.
1228 if (MI->isDebugValue())
1229 continue;
1230
1231 // Now that we know this is a real instruction, count it.
1232 ++Count;
1233
Chad Rosier18896c02016-02-04 16:01:40 +00001234 Flags.setSExtIdx(-1);
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001235 if (canMergeOpc(Opc, MI->getOpcode(), Flags) &&
1236 getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001237 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001238 // If we've found another instruction with the same opcode, check to see
1239 // if the base and offset are compatible with our starting instruction.
1240 // These instructions all have scaled immediate operands, so we just
1241 // check for +1/-1. Make sure to check the new instruction offset is
1242 // actually an immediate and not a symbolic reference destined for
1243 // a relocation.
1244 //
1245 // Pairwise instructions have a 7-bit signed offset field. Single insns
1246 // have a 12-bit unsigned offset field. To be a valid combine, the
1247 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001248 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1249 int MIOffset = getLdStOffsetOp(MI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +00001250 bool MIIsUnscaled = isUnscaledLdSt(MI);
1251 if (IsUnscaled != MIIsUnscaled) {
1252 // We're trying to pair instructions that differ in how they are scaled.
1253 // If FirstMI is scaled then scale the offset of MI accordingly.
1254 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1255 int MemSize = getMemScale(MI);
1256 if (MIIsUnscaled) {
1257 // If the unscaled offset isn't a multiple of the MemSize, we can't
1258 // pair the operations together: bail and keep looking.
1259 if (MIOffset % MemSize)
1260 continue;
1261 MIOffset /= MemSize;
1262 } else {
1263 MIOffset *= MemSize;
1264 }
1265 }
1266
Tim Northover3b0846e2014-05-24 12:50:23 +00001267 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1268 (Offset + OffsetStride == MIOffset))) {
1269 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1270 // If this is a volatile load/store that otherwise matched, stop looking
1271 // as something is going on that we don't have enough information to
1272 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1273 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1274 return E;
1275 // If the resultant immediate offset of merging these instructions
1276 // is out of range for a pairwise instruction, bail and keep looking.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001277 bool IsNarrowLoad = isNarrowLoad(MI->getOpcode());
1278 if (!IsNarrowLoad &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001279 !inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001280 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001281 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001282 continue;
1283 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001284
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001285 if (IsNarrowLoad || IsNarrowStore) {
1286 // If the alignment requirements of the scaled wide load/store
1287 // instruction can't express the offset of the scaled narrow
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001288 // input, bail and keep looking.
1289 if (!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) {
1290 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1291 MemInsns.push_back(MI);
1292 continue;
1293 }
1294 } else {
1295 // If the alignment requirements of the paired (scaled) instruction
1296 // can't express the offset of the unscaled input, bail and keep
1297 // looking.
1298 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1299 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1300 MemInsns.push_back(MI);
1301 continue;
1302 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001303 }
1304 // If the destination register of the loads is the same register, bail
1305 // and keep looking. A load-pair instruction with both destination
1306 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001307 // For narrow stores, allow only when the stored value is the same
1308 // (i.e., WZR).
1309 if ((MayLoad && Reg == getLdStRegOp(MI).getReg()) ||
1310 (IsNarrowStore && Reg != getLdStRegOp(MI).getReg())) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001311 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001312 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001313 continue;
1314 }
1315
1316 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001317 // the two instructions and none of the instructions between the second
1318 // and first alias with the second, we can combine the second into the
1319 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001320 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1321 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001322 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001323 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001324 return MBBI;
1325 }
1326
1327 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001328 // between the two instructions and none of the instructions between the
1329 // first and the second alias with the first, we can combine the first
1330 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001331 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001332 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001333 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001334 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001335 return MBBI;
1336 }
1337 // Unable to combine these instructions due to interference in between.
1338 // Keep looking.
1339 }
1340 }
1341
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001342 // If the instruction wasn't a matching load or store. Stop searching if we
1343 // encounter a call instruction that might modify memory.
1344 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001345 return E;
1346
1347 // Update modified / uses register lists.
1348 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1349
1350 // Otherwise, if the base register is modified, we have no match, so
1351 // return early.
1352 if (ModifiedRegs[BaseReg])
1353 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001354
1355 // Update list of instructions that read/write memory.
1356 if (MI->mayLoadOrStore())
1357 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001358 }
1359 return E;
1360}
1361
1362MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001363AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1364 MachineBasicBlock::iterator Update,
1365 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001366 assert((Update->getOpcode() == AArch64::ADDXri ||
1367 Update->getOpcode() == AArch64::SUBXri) &&
1368 "Unexpected base register update instruction to merge!");
1369 MachineBasicBlock::iterator NextI = I;
1370 // Return the instruction following the merged instruction, which is
1371 // the instruction following our unmerged load. Unless that's the add/sub
1372 // instruction we're merging, in which case it's the one after that.
1373 if (++NextI == Update)
1374 ++NextI;
1375
1376 int Value = Update->getOperand(2).getImm();
1377 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001378 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001379 if (Update->getOpcode() == AArch64::SUBXri)
1380 Value = -Value;
1381
Chad Rosier2dfd3542015-09-23 13:51:44 +00001382 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1383 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001384 MachineInstrBuilder MIB;
1385 if (!isPairedLdSt(I)) {
1386 // Non-paired instruction.
1387 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1388 .addOperand(getLdStRegOp(Update))
1389 .addOperand(getLdStRegOp(I))
1390 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001391 .addImm(Value)
1392 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393 } else {
1394 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001395 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001396 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1397 .addOperand(getLdStRegOp(Update))
1398 .addOperand(getLdStRegOp(I, 0))
1399 .addOperand(getLdStRegOp(I, 1))
1400 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001401 .addImm(Value / Scale)
1402 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001403 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001404 (void)MIB;
1405
Chad Rosier2dfd3542015-09-23 13:51:44 +00001406 if (IsPreIdx)
1407 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1408 else
1409 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001410 DEBUG(dbgs() << " Replacing instructions:\n ");
1411 DEBUG(I->print(dbgs()));
1412 DEBUG(dbgs() << " ");
1413 DEBUG(Update->print(dbgs()));
1414 DEBUG(dbgs() << " with instruction:\n ");
1415 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1416 DEBUG(dbgs() << "\n");
1417
1418 // Erase the old instructions for the block.
1419 I->eraseFromParent();
1420 Update->eraseFromParent();
1421
1422 return NextI;
1423}
1424
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001425bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1426 MachineInstr *MI,
1427 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001428 switch (MI->getOpcode()) {
1429 default:
1430 break;
1431 case AArch64::SUBXri:
1432 // Negate the offset for a SUB instruction.
1433 Offset *= -1;
1434 // FALLTHROUGH
1435 case AArch64::ADDXri:
1436 // Make sure it's a vanilla immediate operand, not a relocation or
1437 // anything else we can't handle.
1438 if (!MI->getOperand(2).isImm())
1439 break;
1440 // Watch out for 1 << 12 shifted value.
1441 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1442 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001443
1444 // The update instruction source and destination register must be the
1445 // same as the load/store base register.
1446 if (MI->getOperand(0).getReg() != BaseReg ||
1447 MI->getOperand(1).getReg() != BaseReg)
1448 break;
1449
1450 bool IsPairedInsn = isPairedLdSt(MemMI);
1451 int UpdateOffset = MI->getOperand(2).getImm();
1452 // For non-paired load/store instructions, the immediate must fit in a
1453 // signed 9-bit integer.
1454 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1455 break;
1456
1457 // For paired load/store instructions, the immediate must be a multiple of
1458 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1459 // integer.
1460 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001461 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001462 if (UpdateOffset % Scale != 0)
1463 break;
1464
1465 int ScaledOffset = UpdateOffset / Scale;
1466 if (ScaledOffset > 64 || ScaledOffset < -64)
1467 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001468 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001469
1470 // If we have a non-zero Offset, we check that it matches the amount
1471 // we're adding to the register.
1472 if (!Offset || Offset == MI->getOperand(2).getImm())
1473 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001474 break;
1475 }
1476 return false;
1477}
1478
1479MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001480 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001481 MachineBasicBlock::iterator E = I->getParent()->end();
1482 MachineInstr *MemMI = I;
1483 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001484
Chad Rosierf77e9092015-08-06 15:50:12 +00001485 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001486 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001487
Chad Rosierb7c5b912015-10-01 13:43:05 +00001488 // Scan forward looking for post-index opportunities. Updating instructions
1489 // can't be formed if the memory instruction doesn't have the offset we're
1490 // looking for.
1491 if (MIUnscaledOffset != UnscaledOffset)
1492 return E;
1493
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001494 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001495 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001496 bool IsPairedInsn = isPairedLdSt(MemMI);
1497 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1498 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1499 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1500 return E;
1501 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001502
Tim Northover3b0846e2014-05-24 12:50:23 +00001503 // Track which registers have been modified and used between the first insn
1504 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001505 ModifiedRegs.reset();
1506 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001507 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001508 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001509 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001510 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001511 if (MI->isDebugValue())
1512 continue;
1513
Chad Rosier35706ad2016-02-04 21:26:02 +00001514 // Now that we know this is a real instruction, count it.
1515 ++Count;
1516
Tim Northover3b0846e2014-05-24 12:50:23 +00001517 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001518 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001519 return MBBI;
1520
1521 // Update the status of what the instruction clobbered and used.
1522 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1523
1524 // Otherwise, if the base register is used or modified, we have no match, so
1525 // return early.
1526 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1527 return E;
1528 }
1529 return E;
1530}
1531
1532MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001533 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001534 MachineBasicBlock::iterator B = I->getParent()->begin();
1535 MachineBasicBlock::iterator E = I->getParent()->end();
1536 MachineInstr *MemMI = I;
1537 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001538
Chad Rosierf77e9092015-08-06 15:50:12 +00001539 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1540 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001541
1542 // If the load/store is the first instruction in the block, there's obviously
1543 // not any matching update. Ditto if the memory offset isn't zero.
1544 if (MBBI == B || Offset != 0)
1545 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001546 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001547 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001548 bool IsPairedInsn = isPairedLdSt(MemMI);
1549 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1550 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1551 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1552 return E;
1553 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001554
1555 // Track which registers have been modified and used between the first insn
1556 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001557 ModifiedRegs.reset();
1558 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001559 unsigned Count = 0;
1560 do {
1561 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001562 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001563
Geoff Berry173b14d2016-02-09 20:47:21 +00001564 // Don't count DBG_VALUE instructions towards the search limit.
1565 if (!MI->isDebugValue())
1566 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001567
Tim Northover3b0846e2014-05-24 12:50:23 +00001568 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001569 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001570 return MBBI;
1571
1572 // Update the status of what the instruction clobbered and used.
1573 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1574
1575 // Otherwise, if the base register is used or modified, we have no match, so
1576 // return early.
1577 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1578 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001579 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001580 return E;
1581}
1582
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001583bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1584 MachineBasicBlock::iterator &MBBI) {
1585 MachineInstr *MI = MBBI;
1586 // If this is a volatile load, don't mess with it.
1587 if (MI->hasOrderedMemoryRef())
1588 return false;
1589
1590 // Make sure this is a reg+imm.
1591 // FIXME: It is possible to extend it to handle reg+reg cases.
1592 if (!getLdStOffsetOp(MI).isImm())
1593 return false;
1594
Chad Rosier35706ad2016-02-04 21:26:02 +00001595 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001596 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001597 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001598 ++NumLoadsFromStoresPromoted;
1599 // Promote the load. Keeping the iterator straight is a
1600 // pain, so we let the merge routine tell us what the next instruction
1601 // is after it's done mucking about.
1602 MBBI = promoteLoadFromStore(MBBI, StoreI);
1603 return true;
1604 }
1605 return false;
1606}
1607
Chad Rosier24c46ad2016-02-09 18:10:20 +00001608bool AArch64LoadStoreOpt::isCandidateToMergeOrPair(MachineInstr *MI) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001609 // If this is a volatile load/store, don't mess with it.
1610 if (MI->hasOrderedMemoryRef())
1611 return false;
1612
1613 // Make sure this is a reg+imm (as opposed to an address reloc).
1614 if (!getLdStOffsetOp(MI).isImm())
1615 return false;
1616
Chad Rosiercc5d61f2016-02-09 20:44:41 +00001617 // Can't merge/pair if the instruction modifies the base register.
1618 // e.g., ldr x0, [x0]
1619 unsigned BaseReg = getLdStBaseOp(MI).getReg();
1620 if (MI->modifiesRegister(BaseReg, TRI))
1621 return false;
1622
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001623 // Check if this load/store has a hint to avoid pair formation.
1624 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1625 if (TII->isLdStPairSuppressed(MI))
1626 return false;
1627
Chad Rosier24c46ad2016-02-09 18:10:20 +00001628 return true;
1629}
1630
1631// Find narrow loads that can be converted into a single wider load with
1632// bitfield extract instructions. Also merge adjacent zero stores into a wider
1633// store.
1634bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1635 MachineBasicBlock::iterator &MBBI) {
1636 assert((isNarrowLoad(MBBI) || isNarrowStore(MBBI)) && "Expected narrow op.");
1637 MachineInstr *MI = MBBI;
1638 MachineBasicBlock::iterator E = MI->getParent()->end();
1639
1640 if (!isCandidateToMergeOrPair(MI))
1641 return false;
1642
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001643 // For narrow stores, find only the case where the stored value is WZR.
1644 if (isNarrowStore(MI) && getLdStRegOp(MI).getReg() != AArch64::WZR)
1645 return false;
1646
Chad Rosier24c46ad2016-02-09 18:10:20 +00001647 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001648 LdStPairFlags Flags;
Chad Rosierd7363db2016-02-09 19:09:22 +00001649 MachineBasicBlock::iterator MergeMI = findMatchingInsn(MBBI, Flags, LdStLimit);
1650 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001651 if (isNarrowLoad(MI)) {
1652 ++NumNarrowLoadsPromoted;
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001653 } else if (isNarrowStore(MI)) {
1654 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001655 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001656 // Keeping the iterator straight is a pain, so we let the merge routine tell
1657 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001658 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001659 return true;
1660 }
1661 return false;
1662}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001663
Chad Rosier24c46ad2016-02-09 18:10:20 +00001664// Find loads and stores that can be merged into a single load or store pair
1665// instruction.
1666bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1667 MachineInstr *MI = MBBI;
1668 MachineBasicBlock::iterator E = MI->getParent()->end();
1669
1670 if (!isCandidateToMergeOrPair(MI))
1671 return false;
1672
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001673 // Early exit if the offset is not possible to match. (6 bits of positive
1674 // range, plus allow an extra one in case we find a later insn that matches
1675 // with Offset-1)
1676 bool IsUnscaled = isUnscaledLdSt(MI);
1677 int Offset = getLdStOffsetOp(MI).getImm();
1678 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1679 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1680 return false;
1681
Chad Rosier24c46ad2016-02-09 18:10:20 +00001682 // Look ahead up to LdStLimit instructions for a pairable instruction.
1683 LdStPairFlags Flags;
1684 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, Flags, LdStLimit);
1685 if (Paired != E) {
1686 ++NumPairCreated;
1687 if (isUnscaledLdSt(MI))
1688 ++NumUnscaledPairCreated;
1689 // Keeping the iterator straight is a pain, so we let the merge routine tell
1690 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001691 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1692 return true;
1693 }
1694 return false;
1695}
1696
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001697bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1698 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001699 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001700 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001701 // 1) Find loads that directly read from stores and promote them by
1702 // replacing with mov instructions. If the store is wider than the load,
1703 // the load will be replaced with a bitfield extract.
1704 // e.g.,
1705 // str w1, [x0, #4]
1706 // ldrh w2, [x0, #6]
1707 // ; becomes
1708 // str w1, [x0, #4]
1709 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001710 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001711 MBBI != E;) {
1712 MachineInstr *MI = MBBI;
1713 switch (MI->getOpcode()) {
1714 default:
1715 // Just move on to the next instruction.
1716 ++MBBI;
1717 break;
1718 // Scaled instructions.
1719 case AArch64::LDRBBui:
1720 case AArch64::LDRHHui:
1721 case AArch64::LDRWui:
1722 case AArch64::LDRXui:
1723 // Unscaled instructions.
1724 case AArch64::LDURBBi:
1725 case AArch64::LDURHHi:
1726 case AArch64::LDURWi:
1727 case AArch64::LDURXi: {
1728 if (tryToPromoteLoadFromStore(MBBI)) {
1729 Modified = true;
1730 break;
1731 }
1732 ++MBBI;
1733 break;
1734 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001735 }
1736 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001737 // 2) Find narrow loads that can be converted into a single wider load
1738 // with bitfield extract instructions.
1739 // e.g.,
1740 // ldrh w0, [x2]
1741 // ldrh w1, [x2, #2]
1742 // ; becomes
1743 // ldr w0, [x2]
1744 // ubfx w1, w0, #16, #16
1745 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001746 //
1747 // Also merge adjacent zero stores into a wider store.
1748 // e.g.,
1749 // strh wzr, [x0]
1750 // strh wzr, [x0, #2]
1751 // ; becomes
1752 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001753 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001754 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001755 MachineInstr *MI = MBBI;
1756 switch (MI->getOpcode()) {
1757 default:
1758 // Just move on to the next instruction.
1759 ++MBBI;
1760 break;
1761 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001762 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001763 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001764 case AArch64::LDRSBWui:
1765 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001766 case AArch64::STRBBui:
1767 case AArch64::STRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001768 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001769 case AArch64::LDURBBi:
1770 case AArch64::LDURHHi:
1771 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001772 case AArch64::LDURSHWi:
1773 case AArch64::STURBBi:
1774 case AArch64::STURHHi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001775 if (tryToMergeLdStInst(MBBI)) {
1776 Modified = true;
1777 break;
1778 }
1779 ++MBBI;
1780 break;
1781 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001782 }
1783 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001784 // 3) Find loads and stores that can be merged into a single load or store
1785 // pair instruction.
1786 // e.g.,
1787 // ldr x0, [x2]
1788 // ldr x1, [x2, #8]
1789 // ; becomes
1790 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001791 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001792 MBBI != E;) {
1793 MachineInstr *MI = MBBI;
1794 switch (MI->getOpcode()) {
1795 default:
1796 // Just move on to the next instruction.
1797 ++MBBI;
1798 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001799 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001800 case AArch64::STRSui:
1801 case AArch64::STRDui:
1802 case AArch64::STRQui:
1803 case AArch64::STRXui:
1804 case AArch64::STRWui:
1805 case AArch64::LDRSui:
1806 case AArch64::LDRDui:
1807 case AArch64::LDRQui:
1808 case AArch64::LDRXui:
1809 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001810 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001811 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001812 case AArch64::STURSi:
1813 case AArch64::STURDi:
1814 case AArch64::STURQi:
1815 case AArch64::STURWi:
1816 case AArch64::STURXi:
1817 case AArch64::LDURSi:
1818 case AArch64::LDURDi:
1819 case AArch64::LDURQi:
1820 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001821 case AArch64::LDURXi:
1822 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001823 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001824 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001825 break;
1826 }
1827 ++MBBI;
1828 break;
1829 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001830 }
1831 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001832 // 4) Find base register updates that can be merged into the load or store
1833 // as a base-reg writeback.
1834 // e.g.,
1835 // ldr x0, [x2]
1836 // add x2, x2, #4
1837 // ; becomes
1838 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1840 MBBI != E;) {
1841 MachineInstr *MI = MBBI;
1842 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001843 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001844 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001845 switch (Opc) {
1846 default:
1847 // Just move on to the next instruction.
1848 ++MBBI;
1849 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001850 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001851 case AArch64::STRSui:
1852 case AArch64::STRDui:
1853 case AArch64::STRQui:
1854 case AArch64::STRXui:
1855 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001856 case AArch64::STRHHui:
1857 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001858 case AArch64::LDRSui:
1859 case AArch64::LDRDui:
1860 case AArch64::LDRQui:
1861 case AArch64::LDRXui:
1862 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001863 case AArch64::LDRHHui:
1864 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001865 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001866 case AArch64::STURSi:
1867 case AArch64::STURDi:
1868 case AArch64::STURQi:
1869 case AArch64::STURWi:
1870 case AArch64::STURXi:
1871 case AArch64::LDURSi:
1872 case AArch64::LDURDi:
1873 case AArch64::LDURQi:
1874 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001875 case AArch64::LDURXi:
1876 // Paired instructions.
1877 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001878 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001879 case AArch64::LDPDi:
1880 case AArch64::LDPQi:
1881 case AArch64::LDPWi:
1882 case AArch64::LDPXi:
1883 case AArch64::STPSi:
1884 case AArch64::STPDi:
1885 case AArch64::STPQi:
1886 case AArch64::STPWi:
1887 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001888 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001889 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001890 ++MBBI;
1891 break;
1892 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001893 // Look forward to try to form a post-index instruction. For example,
1894 // ldr x0, [x20]
1895 // add x20, x20, #32
1896 // merged into:
1897 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001898 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001899 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001900 if (Update != E) {
1901 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001902 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001903 Modified = true;
1904 ++NumPostFolded;
1905 break;
1906 }
1907 // Don't know how to handle pre/post-index versions, so move to the next
1908 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001909 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 ++MBBI;
1911 break;
1912 }
1913
1914 // Look back to try to find a pre-index instruction. For example,
1915 // add x0, x0, #8
1916 // ldr x1, [x0]
1917 // merged into:
1918 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001919 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001920 if (Update != E) {
1921 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001922 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001923 Modified = true;
1924 ++NumPreFolded;
1925 break;
1926 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001927 // The immediate in the load/store is scaled by the size of the memory
1928 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001929 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001930 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001931
Tim Northover3b0846e2014-05-24 12:50:23 +00001932 // Look forward to try to find a post-index instruction. For example,
1933 // ldr x1, [x0, #64]
1934 // add x0, x0, #64
1935 // merged into:
1936 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001937 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001938 if (Update != E) {
1939 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001940 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001941 Modified = true;
1942 ++NumPreFolded;
1943 break;
1944 }
1945
1946 // Nothing found. Just move to the next instruction.
1947 ++MBBI;
1948 break;
1949 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001950 }
1951 }
1952
1953 return Modified;
1954}
1955
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001956bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001957 bool ProfitableArch = Subtarget->isCortexA57();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001958 // FIXME: The benefit from converting narrow loads into a wider load could be
1959 // microarchitectural as it assumes that a single load with two bitfield
1960 // extracts is cheaper than two narrow loads. Currently, this conversion is
1961 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001962 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001963}
1964
Tim Northover3b0846e2014-05-24 12:50:23 +00001965bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001966 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1967 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1968 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001969
Chad Rosierbba881e2016-02-02 15:02:30 +00001970 // Resize the modified and used register bitfield trackers. We do this once
1971 // per function and then clear the bitfield each time we optimize a load or
1972 // store.
1973 ModifiedRegs.resize(TRI->getNumRegs());
1974 UsedRegs.resize(TRI->getNumRegs());
1975
Tim Northover3b0846e2014-05-24 12:50:23 +00001976 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001977 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001978 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001979 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001980
1981 return Modified;
1982}
1983
1984// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1985// loads and stores near one another?
1986
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001987// FIXME: When pairing store instructions it's very possible for this pass to
1988// hoist a store with a KILL marker above another use (without a KILL marker).
1989// The resulting IR is invalid, but nothing uses the KILL markers after this
1990// pass, so it's never caused a problem in practice.
1991
Chad Rosier43f5c842015-08-05 12:40:13 +00001992/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1993/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001994FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1995 return new AArch64LoadStoreOpt();
1996}