blob: 2ffb0ed1889e9b7b30bb6c1cd6c991e342b28a12 [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,
Jun Bum Limcf974432016-03-31 14:47:24 +0000102 unsigned Limit,
103 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000104
105 // Scan the instructions looking for a store that writes to the address from
106 // which the current load instruction reads. Return true if one is found.
107 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
108 MachineBasicBlock::iterator &StoreI);
109
Chad Rosierb5933d72016-02-09 19:02:12 +0000110 // Merge the two instructions indicated into a wider instruction.
111 MachineBasicBlock::iterator
112 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000113 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000114 const LdStPairFlags &Flags);
115
Tim Northover3b0846e2014-05-24 12:50:23 +0000116 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000117 MachineBasicBlock::iterator
118 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000119 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000120 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000121
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000122 // Promote the load that reads directly from the address stored to.
123 MachineBasicBlock::iterator
124 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
125 MachineBasicBlock::iterator StoreI);
126
Tim Northover3b0846e2014-05-24 12:50:23 +0000127 // Scan the instruction list to find a base register update that can
128 // be combined with the current instruction (a load or store) using
129 // pre or post indexed addressing with writeback. Scan forwards.
130 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000131 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000132 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000133
134 // Scan the instruction list to find a base register update that can
135 // be combined with the current instruction (a load or store) using
136 // pre or post indexed addressing with writeback. Scan backwards.
137 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000138 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000139
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000140 // Find an instruction that updates the base register of the ld/st
141 // instruction.
142 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
143 unsigned BaseReg, int Offset);
144
Chad Rosier2dfd3542015-09-23 13:51:44 +0000145 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000146 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000147 mergeUpdateInsn(MachineBasicBlock::iterator I,
148 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000149
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000150 // Find and merge foldable ldr/str instructions.
151 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
152
Chad Rosier24c46ad2016-02-09 18:10:20 +0000153 // Find and pair ldr/str instructions.
154 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
155
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000156 // Find and promote load instructions which read directly from store.
157 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
158
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000159 // Check if converting two narrow loads into a single wider load with
160 // bitfield extracts could be enabled.
161 bool enableNarrowLdMerge(MachineFunction &Fn);
162
163 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000164
165 bool runOnMachineFunction(MachineFunction &Fn) override;
166
167 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000168 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000169 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000170};
171char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000172} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000173
Chad Rosier96530b32015-08-05 13:44:51 +0000174INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
175 AARCH64_LOAD_STORE_OPT_NAME, false, false)
176
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000177static unsigned getBitExtrOpcode(MachineInstr *MI) {
178 switch (MI->getOpcode()) {
179 default:
180 llvm_unreachable("Unexpected opcode.");
181 case AArch64::LDRBBui:
182 case AArch64::LDURBBi:
183 case AArch64::LDRHHui:
184 case AArch64::LDURHHi:
185 return AArch64::UBFMWri;
186 case AArch64::LDRSBWui:
187 case AArch64::LDURSBWi:
188 case AArch64::LDRSHWui:
189 case AArch64::LDURSHWi:
190 return AArch64::SBFMWri;
191 }
192}
193
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000194static bool isNarrowStore(unsigned Opc) {
195 switch (Opc) {
196 default:
197 return false;
198 case AArch64::STRBBui:
199 case AArch64::STURBBi:
200 case AArch64::STRHHui:
201 case AArch64::STURHHi:
202 return true;
203 }
204}
205
Jun Bum Limc12c2792015-11-19 18:41:27 +0000206static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000207 switch (Opc) {
208 default:
209 return false;
210 case AArch64::LDRHHui:
211 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000212 case AArch64::LDRBBui:
213 case AArch64::LDURBBi:
214 case AArch64::LDRSHWui:
215 case AArch64::LDURSHWi:
216 case AArch64::LDRSBWui:
217 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000218 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000219 }
220}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000221
Jun Bum Limc12c2792015-11-19 18:41:27 +0000222static bool isNarrowLoad(MachineInstr *MI) {
223 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000224}
225
Chad Rosier00f9d232016-02-11 14:25:08 +0000226static bool isNarrowLoadOrStore(unsigned Opc) {
227 return isNarrowLoad(Opc) || isNarrowStore(Opc);
228}
229
Chad Rosier32d4d372015-09-29 16:07:32 +0000230// Scaling factor for unscaled load or store.
231static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000232 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000233 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000234 llvm_unreachable("Opcode has unknown scale!");
235 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000236 case AArch64::LDURBBi:
237 case AArch64::LDRSBWui:
238 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000239 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000240 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000241 return 1;
242 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000243 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000244 case AArch64::LDRSHWui:
245 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000246 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000247 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000248 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000249 case AArch64::LDRSui:
250 case AArch64::LDURSi:
251 case AArch64::LDRSWui:
252 case AArch64::LDURSWi:
253 case AArch64::LDRWui:
254 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000255 case AArch64::STRSui:
256 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000257 case AArch64::STRWui:
258 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000259 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000260 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000261 case AArch64::LDPWi:
262 case AArch64::STPSi:
263 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000265 case AArch64::LDRDui:
266 case AArch64::LDURDi:
267 case AArch64::LDRXui:
268 case AArch64::LDURXi:
269 case AArch64::STRDui:
270 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000271 case AArch64::STRXui:
272 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000273 case AArch64::LDPDi:
274 case AArch64::LDPXi:
275 case AArch64::STPDi:
276 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000277 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000278 case AArch64::LDRQui:
279 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000280 case AArch64::STRQui:
281 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000282 case AArch64::LDPQi:
283 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000284 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000285 }
286}
287
Quentin Colombet66b61632015-03-06 22:42:10 +0000288static unsigned getMatchingNonSExtOpcode(unsigned Opc,
289 bool *IsValidLdStrOpc = nullptr) {
290 if (IsValidLdStrOpc)
291 *IsValidLdStrOpc = true;
292 switch (Opc) {
293 default:
294 if (IsValidLdStrOpc)
295 *IsValidLdStrOpc = false;
296 return UINT_MAX;
297 case AArch64::STRDui:
298 case AArch64::STURDi:
299 case AArch64::STRQui:
300 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000301 case AArch64::STRBBui:
302 case AArch64::STURBBi:
303 case AArch64::STRHHui:
304 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000305 case AArch64::STRWui:
306 case AArch64::STURWi:
307 case AArch64::STRXui:
308 case AArch64::STURXi:
309 case AArch64::LDRDui:
310 case AArch64::LDURDi:
311 case AArch64::LDRQui:
312 case AArch64::LDURQi:
313 case AArch64::LDRWui:
314 case AArch64::LDURWi:
315 case AArch64::LDRXui:
316 case AArch64::LDURXi:
317 case AArch64::STRSui:
318 case AArch64::STURSi:
319 case AArch64::LDRSui:
320 case AArch64::LDURSi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000321 case AArch64::LDRHHui:
322 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000323 case AArch64::LDRBBui:
324 case AArch64::LDURBBi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000325 return Opc;
326 case AArch64::LDRSWui:
327 return AArch64::LDRWui;
328 case AArch64::LDURSWi:
329 return AArch64::LDURWi;
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000330 case AArch64::LDRSBWui:
331 return AArch64::LDRBBui;
332 case AArch64::LDRSHWui:
333 return AArch64::LDRHHui;
334 case AArch64::LDURSBWi:
335 return AArch64::LDURBBi;
336 case AArch64::LDURSHWi:
337 return AArch64::LDURHHi;
Quentin Colombet66b61632015-03-06 22:42:10 +0000338 }
339}
340
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000341static unsigned getMatchingWideOpcode(unsigned Opc) {
342 switch (Opc) {
343 default:
344 llvm_unreachable("Opcode has no wide equivalent!");
345 case AArch64::STRBBui:
346 return AArch64::STRHHui;
347 case AArch64::STRHHui:
348 return AArch64::STRWui;
349 case AArch64::STURBBi:
350 return AArch64::STURHHi;
351 case AArch64::STURHHi:
352 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000353 case AArch64::STURWi:
354 return AArch64::STURXi;
355 case AArch64::STRWui:
356 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000357 case AArch64::LDRHHui:
358 case AArch64::LDRSHWui:
359 return AArch64::LDRWui;
360 case AArch64::LDURHHi:
361 case AArch64::LDURSHWi:
362 return AArch64::LDURWi;
363 case AArch64::LDRBBui:
364 case AArch64::LDRSBWui:
365 return AArch64::LDRHHui;
366 case AArch64::LDURBBi:
367 case AArch64::LDURSBWi:
368 return AArch64::LDURHHi;
369 }
370}
371
Tim Northover3b0846e2014-05-24 12:50:23 +0000372static unsigned getMatchingPairOpcode(unsigned Opc) {
373 switch (Opc) {
374 default:
375 llvm_unreachable("Opcode has no pairwise equivalent!");
376 case AArch64::STRSui:
377 case AArch64::STURSi:
378 return AArch64::STPSi;
379 case AArch64::STRDui:
380 case AArch64::STURDi:
381 return AArch64::STPDi;
382 case AArch64::STRQui:
383 case AArch64::STURQi:
384 return AArch64::STPQi;
385 case AArch64::STRWui:
386 case AArch64::STURWi:
387 return AArch64::STPWi;
388 case AArch64::STRXui:
389 case AArch64::STURXi:
390 return AArch64::STPXi;
391 case AArch64::LDRSui:
392 case AArch64::LDURSi:
393 return AArch64::LDPSi;
394 case AArch64::LDRDui:
395 case AArch64::LDURDi:
396 return AArch64::LDPDi;
397 case AArch64::LDRQui:
398 case AArch64::LDURQi:
399 return AArch64::LDPQi;
400 case AArch64::LDRWui:
401 case AArch64::LDURWi:
402 return AArch64::LDPWi;
403 case AArch64::LDRXui:
404 case AArch64::LDURXi:
405 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000406 case AArch64::LDRSWui:
407 case AArch64::LDURSWi:
408 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000409 }
410}
411
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000412static unsigned isMatchingStore(MachineInstr *LoadInst,
413 MachineInstr *StoreInst) {
414 unsigned LdOpc = LoadInst->getOpcode();
415 unsigned StOpc = StoreInst->getOpcode();
416 switch (LdOpc) {
417 default:
418 llvm_unreachable("Unsupported load instruction!");
419 case AArch64::LDRBBui:
420 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
421 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
422 case AArch64::LDURBBi:
423 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
424 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
425 case AArch64::LDRHHui:
426 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
427 StOpc == AArch64::STRXui;
428 case AArch64::LDURHHi:
429 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
430 StOpc == AArch64::STURXi;
431 case AArch64::LDRWui:
432 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
433 case AArch64::LDURWi:
434 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
435 case AArch64::LDRXui:
436 return StOpc == AArch64::STRXui;
437 case AArch64::LDURXi:
438 return StOpc == AArch64::STURXi;
439 }
440}
441
Tim Northover3b0846e2014-05-24 12:50:23 +0000442static unsigned getPreIndexedOpcode(unsigned Opc) {
443 switch (Opc) {
444 default:
445 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000446 case AArch64::STRSui:
447 return AArch64::STRSpre;
448 case AArch64::STRDui:
449 return AArch64::STRDpre;
450 case AArch64::STRQui:
451 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000452 case AArch64::STRBBui:
453 return AArch64::STRBBpre;
454 case AArch64::STRHHui:
455 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000456 case AArch64::STRWui:
457 return AArch64::STRWpre;
458 case AArch64::STRXui:
459 return AArch64::STRXpre;
460 case AArch64::LDRSui:
461 return AArch64::LDRSpre;
462 case AArch64::LDRDui:
463 return AArch64::LDRDpre;
464 case AArch64::LDRQui:
465 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000466 case AArch64::LDRBBui:
467 return AArch64::LDRBBpre;
468 case AArch64::LDRHHui:
469 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000470 case AArch64::LDRWui:
471 return AArch64::LDRWpre;
472 case AArch64::LDRXui:
473 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000474 case AArch64::LDRSWui:
475 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000476 case AArch64::LDPSi:
477 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000478 case AArch64::LDPSWi:
479 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000480 case AArch64::LDPDi:
481 return AArch64::LDPDpre;
482 case AArch64::LDPQi:
483 return AArch64::LDPQpre;
484 case AArch64::LDPWi:
485 return AArch64::LDPWpre;
486 case AArch64::LDPXi:
487 return AArch64::LDPXpre;
488 case AArch64::STPSi:
489 return AArch64::STPSpre;
490 case AArch64::STPDi:
491 return AArch64::STPDpre;
492 case AArch64::STPQi:
493 return AArch64::STPQpre;
494 case AArch64::STPWi:
495 return AArch64::STPWpre;
496 case AArch64::STPXi:
497 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000498 }
499}
500
501static unsigned getPostIndexedOpcode(unsigned Opc) {
502 switch (Opc) {
503 default:
504 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
505 case AArch64::STRSui:
506 return AArch64::STRSpost;
507 case AArch64::STRDui:
508 return AArch64::STRDpost;
509 case AArch64::STRQui:
510 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000511 case AArch64::STRBBui:
512 return AArch64::STRBBpost;
513 case AArch64::STRHHui:
514 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000515 case AArch64::STRWui:
516 return AArch64::STRWpost;
517 case AArch64::STRXui:
518 return AArch64::STRXpost;
519 case AArch64::LDRSui:
520 return AArch64::LDRSpost;
521 case AArch64::LDRDui:
522 return AArch64::LDRDpost;
523 case AArch64::LDRQui:
524 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000525 case AArch64::LDRBBui:
526 return AArch64::LDRBBpost;
527 case AArch64::LDRHHui:
528 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000529 case AArch64::LDRWui:
530 return AArch64::LDRWpost;
531 case AArch64::LDRXui:
532 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000533 case AArch64::LDRSWui:
534 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000535 case AArch64::LDPSi:
536 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000537 case AArch64::LDPSWi:
538 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000539 case AArch64::LDPDi:
540 return AArch64::LDPDpost;
541 case AArch64::LDPQi:
542 return AArch64::LDPQpost;
543 case AArch64::LDPWi:
544 return AArch64::LDPWpost;
545 case AArch64::LDPXi:
546 return AArch64::LDPXpost;
547 case AArch64::STPSi:
548 return AArch64::STPSpost;
549 case AArch64::STPDi:
550 return AArch64::STPDpost;
551 case AArch64::STPQi:
552 return AArch64::STPQpost;
553 case AArch64::STPWi:
554 return AArch64::STPWpost;
555 case AArch64::STPXi:
556 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000557 }
558}
559
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000560static bool isPairedLdSt(const MachineInstr *MI) {
561 switch (MI->getOpcode()) {
562 default:
563 return false;
564 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000565 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000566 case AArch64::LDPDi:
567 case AArch64::LDPQi:
568 case AArch64::LDPWi:
569 case AArch64::LDPXi:
570 case AArch64::STPSi:
571 case AArch64::STPDi:
572 case AArch64::STPQi:
573 case AArch64::STPWi:
574 case AArch64::STPXi:
575 return true;
576 }
577}
578
579static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
580 unsigned PairedRegOp = 0) {
581 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
582 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
583 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000584}
585
586static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000587 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
588 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000589}
590
591static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000592 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
593 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000594}
595
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000596static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000597 MachineInstr *StoreInst,
598 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000599 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
600 int LoadSize = getMemScale(LoadInst);
601 int StoreSize = getMemScale(StoreInst);
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000602 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000603 ? getLdStOffsetOp(StoreInst).getImm()
604 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000605 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000606 ? getLdStOffsetOp(LoadInst).getImm()
607 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
608 return (UnscaledStOffset <= UnscaledLdOffset) &&
609 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
610}
611
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000612static bool isPromotableZeroStoreOpcode(MachineInstr *MI) {
613 unsigned Opc = MI->getOpcode();
614 return isNarrowStore(Opc) || Opc == AArch64::STRWui || Opc == AArch64::STURWi;
615}
616
617static bool isPromotableZeroStoreInst(MachineInstr *MI) {
618 return (isPromotableZeroStoreOpcode(MI)) &&
619 getLdStRegOp(MI).getReg() == AArch64::WZR;
620}
621
Tim Northover3b0846e2014-05-24 12:50:23 +0000622MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000623AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000624 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000625 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000626 MachineBasicBlock::iterator NextI = I;
627 ++NextI;
628 // If NextI is the second of the two instructions to be merged, we need
629 // to skip one further. Either way we merge will invalidate the iterator,
630 // and we don't need to scan the new instruction, as it's a pairwise
631 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000632 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 ++NextI;
634
Chad Rosierb5933d72016-02-09 19:02:12 +0000635 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000636 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Chad Rosier11eedc92016-02-09 19:17:18 +0000637 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000638
Chad Rosier96a18a92015-07-21 17:42:04 +0000639 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000640 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000641 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000642 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000643 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000644 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000645 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000646 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000647
648 // Which register is Rt and which is Rt2 depends on the offset order.
649 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000650 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000651 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
652 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000653 Rt2MI = I;
654 } else {
655 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000656 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000658
James Molloy5b18b4c2015-10-23 10:41:38 +0000659 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000660 // Change the scaled offset from small to large type.
661 if (IsScaled) {
662 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
663 OffsetImm /= 2;
664 }
665
Chad Rosierc46ef882016-02-09 19:33:42 +0000666 DebugLoc DL = I->getDebugLoc();
667 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000668 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000669 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000670 // When merging small (< 32 bit) loads for big-endian targets, the order of
671 // the component parts gets swapped.
672 if (!Subtarget->isLittleEndian())
673 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000674 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000675 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000676 NewMemMI =
677 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
678 .addOperand(getLdStRegOp(RtNewDest))
679 .addOperand(BaseRegOp)
680 .addImm(OffsetImm)
681 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Chad Rosierf7ac5f22016-03-30 18:08:51 +0000682 (void)NewMemMI;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000683
684 DEBUG(
685 dbgs()
686 << "Creating the new load and extract. Replacing instructions:\n ");
687 DEBUG(I->print(dbgs()));
688 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000689 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000690 DEBUG(dbgs() << " with instructions:\n ");
691 DEBUG((NewMemMI)->print(dbgs()));
692
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000693 int Width = getMemScale(I) == 1 ? 8 : 16;
694 int LSBLow = 0;
695 int LSBHigh = Width;
696 int ImmsLow = LSBLow + Width - 1;
697 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000698 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000699 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000700 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000701 BitExtMI1 =
702 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
703 .addOperand(getLdStRegOp(Rt2MI))
704 .addReg(getLdStRegOp(RtNewDest).getReg())
705 .addImm(LSBHigh)
706 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000707 // Create the bitfield extract for low bits.
708 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
709 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000710 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000711 .addOperand(getLdStRegOp(RtMI))
712 .addReg(getLdStRegOp(RtNewDest).getReg())
713 .addImm(ImmsLow);
714 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000715 BitExtMI2 =
716 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
717 .addOperand(getLdStRegOp(RtMI))
718 .addReg(getLdStRegOp(RtNewDest).getReg())
719 .addImm(LSBLow)
720 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000721 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000722 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000723 // Create the bitfield extract for low bits.
724 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
725 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000726 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000727 .addOperand(getLdStRegOp(RtMI))
728 .addReg(getLdStRegOp(RtNewDest).getReg())
729 .addImm(ImmsLow);
730 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000731 BitExtMI1 =
732 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
733 .addOperand(getLdStRegOp(RtMI))
734 .addReg(getLdStRegOp(RtNewDest).getReg())
735 .addImm(LSBLow)
736 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000737 }
738
739 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000740 BitExtMI2 =
741 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
742 .addOperand(getLdStRegOp(Rt2MI))
743 .addReg(getLdStRegOp(RtNewDest).getReg())
744 .addImm(LSBHigh)
745 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000746 }
Chad Rosierf7ac5f22016-03-30 18:08:51 +0000747 (void)BitExtMI1;
748 (void)BitExtMI2;
749
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000750 DEBUG(dbgs() << " ");
751 DEBUG((BitExtMI1)->print(dbgs()));
752 DEBUG(dbgs() << " ");
753 DEBUG((BitExtMI2)->print(dbgs()));
754 DEBUG(dbgs() << "\n");
755
756 // Erase the old instructions.
757 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000758 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000759 return NextI;
760 }
Jun Bum Limcf974432016-03-31 14:47:24 +0000761 assert(isPromotableZeroStoreInst(I) && isPromotableZeroStoreInst(MergeMI) &&
762 "Expected promotable zero store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000763
Tim Northover3b0846e2014-05-24 12:50:23 +0000764 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000765 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000766 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000767 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Chad Rosierb5933d72016-02-09 19:02:12 +0000768 .addOperand(BaseRegOp)
769 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000770 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000771 (void)MIB;
772
Chad Rosierb5933d72016-02-09 19:02:12 +0000773 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
774 DEBUG(I->print(dbgs()));
775 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000776 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000777 DEBUG(dbgs() << " with instruction:\n ");
778 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
779 DEBUG(dbgs() << "\n");
780
781 // Erase the old instructions.
782 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000783 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000784 return NextI;
785}
786
787MachineBasicBlock::iterator
788AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
789 MachineBasicBlock::iterator Paired,
790 const LdStPairFlags &Flags) {
791 MachineBasicBlock::iterator NextI = I;
792 ++NextI;
793 // If NextI is the second of the two instructions to be merged, we need
794 // to skip one further. Either way we merge will invalidate the iterator,
795 // and we don't need to scan the new instruction, as it's a pairwise
796 // instruction, which we're not considering for further action anyway.
797 if (NextI == Paired)
798 ++NextI;
799
800 int SExtIdx = Flags.getSExtIdx();
801 unsigned Opc =
802 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000803 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Chad Rosierb5933d72016-02-09 19:02:12 +0000804 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
805
806 bool MergeForward = Flags.getMergeForward();
807 // Insert our new paired instruction after whichever of the paired
808 // instructions MergeForward indicates.
809 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
810 // Also based on MergeForward is from where we copy the base register operand
811 // so we get the flags compatible with the input code.
812 const MachineOperand &BaseRegOp =
813 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
814
Chad Rosier00f9d232016-02-11 14:25:08 +0000815 int Offset = getLdStOffsetOp(I).getImm();
816 int PairedOffset = getLdStOffsetOp(Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000817 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000818 if (IsUnscaled != PairedIsUnscaled) {
819 // We're trying to pair instructions that differ in how they are scaled. If
820 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
821 // the opposite (i.e., make Paired's offset unscaled).
822 int MemSize = getMemScale(Paired);
823 if (PairedIsUnscaled) {
824 // If the unscaled offset isn't a multiple of the MemSize, we can't
825 // pair the operations together.
826 assert(!(PairedOffset % getMemScale(Paired)) &&
827 "Offset should be a multiple of the stride!");
828 PairedOffset /= MemSize;
829 } else {
830 PairedOffset *= MemSize;
831 }
832 }
833
Chad Rosierb5933d72016-02-09 19:02:12 +0000834 // Which register is Rt and which is Rt2 depends on the offset order.
835 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000836 if (Offset == PairedOffset + OffsetStride) {
Chad Rosierb5933d72016-02-09 19:02:12 +0000837 RtMI = Paired;
838 Rt2MI = I;
839 // Here we swapped the assumption made for SExtIdx.
840 // I.e., we turn ldp I, Paired into ldp Paired, I.
841 // Update the index accordingly.
842 if (SExtIdx != -1)
843 SExtIdx = (SExtIdx + 1) % 2;
844 } else {
845 RtMI = I;
846 Rt2MI = Paired;
847 }
848 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000849 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000850 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Chad Rosier00f9d232016-02-11 14:25:08 +0000851 assert(!(OffsetImm % getMemScale(RtMI)) &&
852 "Unscaled offset cannot be scaled.");
853 OffsetImm /= getMemScale(RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000854 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000855
856 // Construct the new instruction.
857 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000858 DebugLoc DL = I->getDebugLoc();
859 MachineBasicBlock *MBB = I->getParent();
860 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000861 .addOperand(getLdStRegOp(RtMI))
862 .addOperand(getLdStRegOp(Rt2MI))
863 .addOperand(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000864 .addImm(OffsetImm)
865 .setMemRefs(I->mergeMemRefsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000866
867 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000868
869 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
870 DEBUG(I->print(dbgs()));
871 DEBUG(dbgs() << " ");
872 DEBUG(Paired->print(dbgs()));
873 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000874 if (SExtIdx != -1) {
875 // Generate the sign extension for the proper result of the ldp.
876 // I.e., with X1, that would be:
877 // %W1<def> = KILL %W1, %X1<imp-def>
878 // %X1<def> = SBFMXri %X1<kill>, 0, 31
879 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
880 // Right now, DstMO has the extended register, since it comes from an
881 // extended opcode.
882 unsigned DstRegX = DstMO.getReg();
883 // Get the W variant of that register.
884 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
885 // Update the result of LDP to use the W instead of the X variant.
886 DstMO.setReg(DstRegW);
887 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
888 DEBUG(dbgs() << "\n");
889 // Make the machine verifier happy by providing a definition for
890 // the X register.
891 // Insert this definition right after the generated LDP, i.e., before
892 // InsertionPoint.
893 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000894 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000895 .addReg(DstRegW)
896 .addReg(DstRegX, RegState::Define);
897 MIBKill->getOperand(2).setImplicit();
898 // Create the sign extension.
899 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000900 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000901 .addReg(DstRegX)
902 .addImm(0)
903 .addImm(31);
904 (void)MIBSXTW;
905 DEBUG(dbgs() << " Extend operand:\n ");
906 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000907 } else {
908 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000909 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000910 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000911
912 // Erase the old instructions.
913 I->eraseFromParent();
914 Paired->eraseFromParent();
915
916 return NextI;
917}
918
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000919MachineBasicBlock::iterator
920AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
921 MachineBasicBlock::iterator StoreI) {
922 MachineBasicBlock::iterator NextI = LoadI;
923 ++NextI;
924
925 int LoadSize = getMemScale(LoadI);
926 int StoreSize = getMemScale(StoreI);
927 unsigned LdRt = getLdStRegOp(LoadI).getReg();
928 unsigned StRt = getLdStRegOp(StoreI).getReg();
929 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
930
931 assert((IsStoreXReg ||
932 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
933 "Unexpected RegClass");
934
935 MachineInstr *BitExtMI;
936 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
937 // Remove the load, if the destination register of the loads is the same
938 // register for stored value.
939 if (StRt == LdRt && LoadSize == 8) {
940 DEBUG(dbgs() << "Remove load instruction:\n ");
941 DEBUG(LoadI->print(dbgs()));
942 DEBUG(dbgs() << "\n");
943 LoadI->eraseFromParent();
944 return NextI;
945 }
946 // Replace the load with a mov if the load and store are in the same size.
947 BitExtMI =
948 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
949 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
950 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
951 .addReg(StRt)
952 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
953 } else {
954 // FIXME: Currently we disable this transformation in big-endian targets as
955 // performance and correctness are verified only in little-endian.
956 if (!Subtarget->isLittleEndian())
957 return NextI;
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000958 bool IsUnscaled = TII->isUnscaledLdSt(LoadI);
959 assert(IsUnscaled == TII->isUnscaledLdSt(StoreI) &&
960 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000961 assert(LoadSize <= StoreSize && "Invalid load size");
962 int UnscaledLdOffset = IsUnscaled
963 ? getLdStOffsetOp(LoadI).getImm()
964 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
965 int UnscaledStOffset = IsUnscaled
966 ? getLdStOffsetOp(StoreI).getImm()
967 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
968 int Width = LoadSize * 8;
969 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
970 int Imms = Immr + Width - 1;
971 unsigned DestReg = IsStoreXReg
972 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
973 &AArch64::GPR64RegClass)
974 : LdRt;
975
976 assert((UnscaledLdOffset >= UnscaledStOffset &&
977 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
978 "Invalid offset");
979
980 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
981 Imms = Immr + Width - 1;
982 if (UnscaledLdOffset == UnscaledStOffset) {
983 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
984 | ((Immr) << 6) // immr
985 | ((Imms) << 0) // imms
986 ;
987
988 BitExtMI =
989 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
990 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
991 DestReg)
992 .addReg(StRt)
993 .addImm(AndMaskEncoded);
994 } else {
995 BitExtMI =
996 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
997 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
998 DestReg)
999 .addReg(StRt)
1000 .addImm(Immr)
1001 .addImm(Imms);
1002 }
1003 }
Chad Rosierf7ac5f22016-03-30 18:08:51 +00001004 (void)BitExtMI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001005
1006 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1007 DEBUG(StoreI->print(dbgs()));
1008 DEBUG(dbgs() << " ");
1009 DEBUG(LoadI->print(dbgs()));
1010 DEBUG(dbgs() << " with instructions:\n ");
1011 DEBUG(StoreI->print(dbgs()));
1012 DEBUG(dbgs() << " ");
1013 DEBUG((BitExtMI)->print(dbgs()));
1014 DEBUG(dbgs() << "\n");
1015
1016 // Erase the old instructions.
1017 LoadI->eraseFromParent();
1018 return NextI;
1019}
1020
Tim Northover3b0846e2014-05-24 12:50:23 +00001021/// trackRegDefsUses - Remember what registers the specified instruction uses
1022/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001023static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001024 BitVector &UsedRegs,
1025 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001026 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001027 if (MO.isRegMask())
1028 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1029
1030 if (!MO.isReg())
1031 continue;
1032 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001033 if (!Reg)
1034 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001035 if (MO.isDef()) {
1036 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1037 ModifiedRegs.set(*AI);
1038 } else {
1039 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1040 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1041 UsedRegs.set(*AI);
1042 }
1043 }
1044}
1045
1046static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001047 // Convert the byte-offset used by unscaled into an "element" offset used
1048 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001049 if (IsUnscaled) {
1050 // If the byte-offset isn't a multiple of the stride, there's no point
1051 // trying to match it.
1052 if (Offset % OffsetStride)
1053 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001054 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001055 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001056 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001057}
1058
1059// Do alignment, specialized to power of 2 and for signed ints,
1060// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001061// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001062// FIXME: Move this function to include/MathExtras.h?
1063static int alignTo(int Num, int PowOf2) {
1064 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1065}
1066
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001067static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1068 const AArch64InstrInfo *TII) {
1069 // One of the instructions must modify memory.
1070 if (!MIa->mayStore() && !MIb->mayStore())
1071 return false;
1072
1073 // Both instructions must be memory operations.
1074 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1075 return false;
1076
1077 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1078}
1079
1080static bool mayAlias(MachineInstr *MIa,
1081 SmallVectorImpl<MachineInstr *> &MemInsns,
1082 const AArch64InstrInfo *TII) {
1083 for (auto &MIb : MemInsns)
1084 if (mayAlias(MIa, MIb, TII))
1085 return true;
1086
1087 return false;
1088}
1089
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001090bool AArch64LoadStoreOpt::findMatchingStore(
1091 MachineBasicBlock::iterator I, unsigned Limit,
1092 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001093 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001094 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001095 MachineInstr *LoadMI = I;
1096 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001097
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001098 // If the load is the first instruction in the block, there's obviously
1099 // not any matching store.
1100 if (MBBI == B)
1101 return false;
1102
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001103 // Track which registers have been modified and used between the first insn
1104 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001105 ModifiedRegs.reset();
1106 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001107
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001108 unsigned Count = 0;
1109 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001110 --MBBI;
1111 MachineInstr *MI = MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001112
1113 // Don't count DBG_VALUE instructions towards the search limit.
1114 if (!MI->isDebugValue())
1115 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001116
1117 // If the load instruction reads directly from the address to which the
1118 // store instruction writes and the stored value is not modified, we can
1119 // promote the load. Since we do not handle stores with pre-/post-index,
1120 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001121 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001122 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001123 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001124 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1125 StoreI = MBBI;
1126 return true;
1127 }
1128
1129 if (MI->isCall())
1130 return false;
1131
1132 // Update modified / uses register lists.
1133 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1134
1135 // Otherwise, if the base register is modified, we have no match, so
1136 // return early.
1137 if (ModifiedRegs[BaseReg])
1138 return false;
1139
1140 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001141 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001142 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001143 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001144 return false;
1145}
1146
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001147// Returns true if these two opcodes can be merged or paired. Otherwise,
1148// returns false.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001149static bool canMergeOpc(unsigned OpcA, unsigned OpcB, LdStPairFlags &Flags,
1150 const AArch64InstrInfo *TII) {
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001151 // Opcodes match: nothing more to check.
1152 if (OpcA == OpcB)
1153 return true;
1154
1155 // Try to match a sign-extended load/store with a zero-extended load/store.
1156 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1157 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1158 assert(IsValidLdStrOpc &&
1159 "Given Opc should be a Load or Store with an immediate");
1160 // OpcA will be the first instruction in the pair.
1161 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1162 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1163 return true;
1164 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001165
1166 // If the second instruction isn't even a load/store, bail out.
1167 if (!PairIsValidLdStrOpc)
1168 return false;
1169
1170 // FIXME: We don't support merging narrow loads/stores with mixed
1171 // scaled/unscaled offsets.
1172 if (isNarrowLoadOrStore(OpcA) || isNarrowLoadOrStore(OpcB))
1173 return false;
1174
1175 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001176 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001177 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1178
1179 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001180}
1181
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001182/// Scan the instructions looking for a load/store that can be combined with the
1183/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001184MachineBasicBlock::iterator
1185AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001186 LdStPairFlags &Flags, unsigned Limit,
1187 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001188 MachineBasicBlock::iterator E = I->getParent()->end();
1189 MachineBasicBlock::iterator MBBI = I;
1190 MachineInstr *FirstMI = I;
1191 ++MBBI;
1192
Matthias Braunfa3872e2015-05-18 20:27:55 +00001193 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001194 bool MayLoad = FirstMI->mayLoad();
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001195 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001196 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1197 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1198 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001199 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001200 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001201
1202 // Track which registers have been modified and used between the first insn
1203 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001204 ModifiedRegs.reset();
1205 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001206
1207 // Remember any instructions that read/write memory between FirstMI and MI.
1208 SmallVector<MachineInstr *, 4> MemInsns;
1209
Tim Northover3b0846e2014-05-24 12:50:23 +00001210 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1211 MachineInstr *MI = MBBI;
1212 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1213 // optimization by changing how far we scan.
1214 if (MI->isDebugValue())
1215 continue;
1216
1217 // Now that we know this is a real instruction, count it.
1218 ++Count;
1219
Chad Rosier18896c02016-02-04 16:01:40 +00001220 Flags.setSExtIdx(-1);
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001221 if (canMergeOpc(Opc, MI->getOpcode(), Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001222 getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001223 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001224 // If we've found another instruction with the same opcode, check to see
1225 // if the base and offset are compatible with our starting instruction.
1226 // These instructions all have scaled immediate operands, so we just
1227 // check for +1/-1. Make sure to check the new instruction offset is
1228 // actually an immediate and not a symbolic reference destined for
1229 // a relocation.
1230 //
1231 // Pairwise instructions have a 7-bit signed offset field. Single insns
1232 // have a 12-bit unsigned offset field. To be a valid combine, the
1233 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001234 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1235 int MIOffset = getLdStOffsetOp(MI).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001236 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001237 if (IsUnscaled != MIIsUnscaled) {
1238 // We're trying to pair instructions that differ in how they are scaled.
1239 // If FirstMI is scaled then scale the offset of MI accordingly.
1240 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1241 int MemSize = getMemScale(MI);
1242 if (MIIsUnscaled) {
1243 // If the unscaled offset isn't a multiple of the MemSize, we can't
1244 // pair the operations together: bail and keep looking.
1245 if (MIOffset % MemSize)
1246 continue;
1247 MIOffset /= MemSize;
1248 } else {
1249 MIOffset *= MemSize;
1250 }
1251 }
1252
Tim Northover3b0846e2014-05-24 12:50:23 +00001253 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1254 (Offset + OffsetStride == MIOffset))) {
1255 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1256 // If this is a volatile load/store that otherwise matched, stop looking
1257 // as something is going on that we don't have enough information to
1258 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1259 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1260 return E;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001261
Jun Bum Limcf974432016-03-31 14:47:24 +00001262 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001263 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001264 // instruction can't express the offset of the scaled narrow input,
1265 // bail and keep looking. For promotable zero stores, allow only when
1266 // the stored value is the same (i.e., WZR).
1267 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1268 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001269 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1270 MemInsns.push_back(MI);
1271 continue;
1272 }
1273 } else {
Jun Bum Limcf974432016-03-31 14:47:24 +00001274 // If the resultant immediate offset of merging these instructions
1275 // is out of range for a pairwise instruction, bail and keep looking.
1276 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1277 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1278 MemInsns.push_back(MI);
1279 continue;
1280 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001281 // If the alignment requirements of the paired (scaled) instruction
1282 // can't express the offset of the unscaled input, bail and keep
1283 // looking.
1284 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1285 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1286 MemInsns.push_back(MI);
1287 continue;
1288 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001289 }
1290 // If the destination register of the loads is the same register, bail
1291 // and keep looking. A load-pair instruction with both destination
1292 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001293 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001294 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001295 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001296 continue;
1297 }
1298
1299 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001300 // the two instructions and none of the instructions between the second
1301 // and first alias with the second, we can combine the second into the
1302 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001303 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1304 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001305 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001306 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001307 return MBBI;
1308 }
1309
1310 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001311 // between the two instructions and none of the instructions between the
1312 // first and the second alias with the first, we can combine the first
1313 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001314 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001315 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001316 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001317 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001318 return MBBI;
1319 }
1320 // Unable to combine these instructions due to interference in between.
1321 // Keep looking.
1322 }
1323 }
1324
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001325 // If the instruction wasn't a matching load or store. Stop searching if we
1326 // encounter a call instruction that might modify memory.
1327 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001328 return E;
1329
1330 // Update modified / uses register lists.
1331 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1332
1333 // Otherwise, if the base register is modified, we have no match, so
1334 // return early.
1335 if (ModifiedRegs[BaseReg])
1336 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001337
1338 // Update list of instructions that read/write memory.
1339 if (MI->mayLoadOrStore())
1340 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001341 }
1342 return E;
1343}
1344
1345MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001346AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1347 MachineBasicBlock::iterator Update,
1348 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001349 assert((Update->getOpcode() == AArch64::ADDXri ||
1350 Update->getOpcode() == AArch64::SUBXri) &&
1351 "Unexpected base register update instruction to merge!");
1352 MachineBasicBlock::iterator NextI = I;
1353 // Return the instruction following the merged instruction, which is
1354 // the instruction following our unmerged load. Unless that's the add/sub
1355 // instruction we're merging, in which case it's the one after that.
1356 if (++NextI == Update)
1357 ++NextI;
1358
1359 int Value = Update->getOperand(2).getImm();
1360 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001361 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001362 if (Update->getOpcode() == AArch64::SUBXri)
1363 Value = -Value;
1364
Chad Rosier2dfd3542015-09-23 13:51:44 +00001365 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1366 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001367 MachineInstrBuilder MIB;
1368 if (!isPairedLdSt(I)) {
1369 // Non-paired instruction.
1370 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1371 .addOperand(getLdStRegOp(Update))
1372 .addOperand(getLdStRegOp(I))
1373 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001374 .addImm(Value)
1375 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001376 } else {
1377 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001378 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001379 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1380 .addOperand(getLdStRegOp(Update))
1381 .addOperand(getLdStRegOp(I, 0))
1382 .addOperand(getLdStRegOp(I, 1))
1383 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001384 .addImm(Value / Scale)
1385 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001386 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001387 (void)MIB;
1388
Chad Rosier2dfd3542015-09-23 13:51:44 +00001389 if (IsPreIdx)
1390 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1391 else
1392 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001393 DEBUG(dbgs() << " Replacing instructions:\n ");
1394 DEBUG(I->print(dbgs()));
1395 DEBUG(dbgs() << " ");
1396 DEBUG(Update->print(dbgs()));
1397 DEBUG(dbgs() << " with instruction:\n ");
1398 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1399 DEBUG(dbgs() << "\n");
1400
1401 // Erase the old instructions for the block.
1402 I->eraseFromParent();
1403 Update->eraseFromParent();
1404
1405 return NextI;
1406}
1407
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001408bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1409 MachineInstr *MI,
1410 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001411 switch (MI->getOpcode()) {
1412 default:
1413 break;
1414 case AArch64::SUBXri:
1415 // Negate the offset for a SUB instruction.
1416 Offset *= -1;
1417 // FALLTHROUGH
1418 case AArch64::ADDXri:
1419 // Make sure it's a vanilla immediate operand, not a relocation or
1420 // anything else we can't handle.
1421 if (!MI->getOperand(2).isImm())
1422 break;
1423 // Watch out for 1 << 12 shifted value.
1424 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1425 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001426
1427 // The update instruction source and destination register must be the
1428 // same as the load/store base register.
1429 if (MI->getOperand(0).getReg() != BaseReg ||
1430 MI->getOperand(1).getReg() != BaseReg)
1431 break;
1432
1433 bool IsPairedInsn = isPairedLdSt(MemMI);
1434 int UpdateOffset = MI->getOperand(2).getImm();
1435 // For non-paired load/store instructions, the immediate must fit in a
1436 // signed 9-bit integer.
1437 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1438 break;
1439
1440 // For paired load/store instructions, the immediate must be a multiple of
1441 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1442 // integer.
1443 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001444 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001445 if (UpdateOffset % Scale != 0)
1446 break;
1447
1448 int ScaledOffset = UpdateOffset / Scale;
1449 if (ScaledOffset > 64 || ScaledOffset < -64)
1450 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001451 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001452
1453 // If we have a non-zero Offset, we check that it matches the amount
1454 // we're adding to the register.
1455 if (!Offset || Offset == MI->getOperand(2).getImm())
1456 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001457 break;
1458 }
1459 return false;
1460}
1461
1462MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001463 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001464 MachineBasicBlock::iterator E = I->getParent()->end();
1465 MachineInstr *MemMI = I;
1466 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001467
Chad Rosierf77e9092015-08-06 15:50:12 +00001468 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001469 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001470
Chad Rosierb7c5b912015-10-01 13:43:05 +00001471 // Scan forward looking for post-index opportunities. Updating instructions
1472 // can't be formed if the memory instruction doesn't have the offset we're
1473 // looking for.
1474 if (MIUnscaledOffset != UnscaledOffset)
1475 return E;
1476
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001477 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001479 bool IsPairedInsn = isPairedLdSt(MemMI);
1480 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1481 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1482 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1483 return E;
1484 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001485
Tim Northover3b0846e2014-05-24 12:50:23 +00001486 // Track which registers have been modified and used between the first insn
1487 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001488 ModifiedRegs.reset();
1489 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001491 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001492 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001493 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001494 if (MI->isDebugValue())
1495 continue;
1496
Chad Rosier35706ad2016-02-04 21:26:02 +00001497 // Now that we know this is a real instruction, count it.
1498 ++Count;
1499
Tim Northover3b0846e2014-05-24 12:50:23 +00001500 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001501 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001502 return MBBI;
1503
1504 // Update the status of what the instruction clobbered and used.
1505 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1506
1507 // Otherwise, if the base register is used or modified, we have no match, so
1508 // return early.
1509 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1510 return E;
1511 }
1512 return E;
1513}
1514
1515MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001516 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001517 MachineBasicBlock::iterator B = I->getParent()->begin();
1518 MachineBasicBlock::iterator E = I->getParent()->end();
1519 MachineInstr *MemMI = I;
1520 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001521
Chad Rosierf77e9092015-08-06 15:50:12 +00001522 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1523 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001524
1525 // If the load/store is the first instruction in the block, there's obviously
1526 // not any matching update. Ditto if the memory offset isn't zero.
1527 if (MBBI == B || Offset != 0)
1528 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001529 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001530 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001531 bool IsPairedInsn = isPairedLdSt(MemMI);
1532 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1533 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1534 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1535 return E;
1536 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001537
1538 // Track which registers have been modified and used between the first insn
1539 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001540 ModifiedRegs.reset();
1541 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001542 unsigned Count = 0;
1543 do {
1544 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001545 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001546
Geoff Berry173b14d2016-02-09 20:47:21 +00001547 // Don't count DBG_VALUE instructions towards the search limit.
1548 if (!MI->isDebugValue())
1549 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001550
Tim Northover3b0846e2014-05-24 12:50:23 +00001551 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001552 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001553 return MBBI;
1554
1555 // Update the status of what the instruction clobbered and used.
1556 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1557
1558 // Otherwise, if the base register is used or modified, we have no match, so
1559 // return early.
1560 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1561 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001562 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001563 return E;
1564}
1565
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001566bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1567 MachineBasicBlock::iterator &MBBI) {
1568 MachineInstr *MI = MBBI;
1569 // If this is a volatile load, don't mess with it.
1570 if (MI->hasOrderedMemoryRef())
1571 return false;
1572
1573 // Make sure this is a reg+imm.
1574 // FIXME: It is possible to extend it to handle reg+reg cases.
1575 if (!getLdStOffsetOp(MI).isImm())
1576 return false;
1577
Chad Rosier35706ad2016-02-04 21:26:02 +00001578 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001579 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001580 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001581 ++NumLoadsFromStoresPromoted;
1582 // Promote the load. Keeping the iterator straight is a
1583 // pain, so we let the merge routine tell us what the next instruction
1584 // is after it's done mucking about.
1585 MBBI = promoteLoadFromStore(MBBI, StoreI);
1586 return true;
1587 }
1588 return false;
1589}
1590
Chad Rosier24c46ad2016-02-09 18:10:20 +00001591// Find narrow loads that can be converted into a single wider load with
1592// bitfield extract instructions. Also merge adjacent zero stores into a wider
1593// store.
1594bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1595 MachineBasicBlock::iterator &MBBI) {
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001596 assert((isNarrowLoad(MBBI) || isPromotableZeroStoreOpcode(MBBI)) &&
1597 "Expected narrow op.");
Chad Rosier24c46ad2016-02-09 18:10:20 +00001598 MachineInstr *MI = MBBI;
1599 MachineBasicBlock::iterator E = MI->getParent()->end();
1600
Chad Rosiercdfd7e72016-03-18 19:21:02 +00001601 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001602 return false;
1603
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001604 // For promotable zero stores, the stored value should be WZR.
1605 if (isPromotableZeroStoreOpcode(MI) &&
1606 getLdStRegOp(MI).getReg() != AArch64::WZR)
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001607 return false;
1608
Chad Rosier24c46ad2016-02-09 18:10:20 +00001609 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001610 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001611 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001612 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001613 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001614 if (isNarrowLoad(MI)) {
1615 ++NumNarrowLoadsPromoted;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001616 } else if (isPromotableZeroStoreInst(MI)) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001617 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001618 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001619 // Keeping the iterator straight is a pain, so we let the merge routine tell
1620 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001621 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001622 return true;
1623 }
1624 return false;
1625}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001626
Chad Rosier24c46ad2016-02-09 18:10:20 +00001627// Find loads and stores that can be merged into a single load or store pair
1628// instruction.
1629bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1630 MachineInstr *MI = MBBI;
1631 MachineBasicBlock::iterator E = MI->getParent()->end();
1632
Chad Rosiercdfd7e72016-03-18 19:21:02 +00001633 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001634 return false;
1635
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001636 // Early exit if the offset is not possible to match. (6 bits of positive
1637 // range, plus allow an extra one in case we find a later insn that matches
1638 // with Offset-1)
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001639 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001640 int Offset = getLdStOffsetOp(MI).getImm();
1641 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1642 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1643 return false;
1644
Chad Rosier24c46ad2016-02-09 18:10:20 +00001645 // Look ahead up to LdStLimit instructions for a pairable instruction.
1646 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001647 MachineBasicBlock::iterator Paired =
1648 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001649 if (Paired != E) {
1650 ++NumPairCreated;
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001651 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001652 ++NumUnscaledPairCreated;
1653 // Keeping the iterator straight is a pain, so we let the merge routine tell
1654 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001655 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1656 return true;
1657 }
1658 return false;
1659}
1660
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001661bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1662 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001663 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001664 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001665 // 1) Find loads that directly read from stores and promote them by
1666 // replacing with mov instructions. If the store is wider than the load,
1667 // the load will be replaced with a bitfield extract.
1668 // e.g.,
1669 // str w1, [x0, #4]
1670 // ldrh w2, [x0, #6]
1671 // ; becomes
1672 // str w1, [x0, #4]
1673 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001674 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001675 MBBI != E;) {
1676 MachineInstr *MI = MBBI;
1677 switch (MI->getOpcode()) {
1678 default:
1679 // Just move on to the next instruction.
1680 ++MBBI;
1681 break;
1682 // Scaled instructions.
1683 case AArch64::LDRBBui:
1684 case AArch64::LDRHHui:
1685 case AArch64::LDRWui:
1686 case AArch64::LDRXui:
1687 // Unscaled instructions.
1688 case AArch64::LDURBBi:
1689 case AArch64::LDURHHi:
1690 case AArch64::LDURWi:
1691 case AArch64::LDURXi: {
1692 if (tryToPromoteLoadFromStore(MBBI)) {
1693 Modified = true;
1694 break;
1695 }
1696 ++MBBI;
1697 break;
1698 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001699 }
1700 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001701 // 2) Find narrow loads that can be converted into a single wider load
1702 // with bitfield extract instructions.
1703 // e.g.,
1704 // ldrh w0, [x2]
1705 // ldrh w1, [x2, #2]
1706 // ; becomes
1707 // ldr w0, [x2]
1708 // ubfx w1, w0, #16, #16
1709 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001710 //
1711 // Also merge adjacent zero stores into a wider store.
1712 // e.g.,
1713 // strh wzr, [x0]
1714 // strh wzr, [x0, #2]
1715 // ; becomes
1716 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001717 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001718 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001719 MachineInstr *MI = MBBI;
1720 switch (MI->getOpcode()) {
1721 default:
1722 // Just move on to the next instruction.
1723 ++MBBI;
1724 break;
1725 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001726 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001727 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001728 case AArch64::LDRSBWui:
1729 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001730 case AArch64::STRBBui:
1731 case AArch64::STRHHui:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001732 case AArch64::STRWui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001733 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001734 case AArch64::LDURBBi:
1735 case AArch64::LDURHHi:
1736 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001737 case AArch64::LDURSHWi:
1738 case AArch64::STURBBi:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001739 case AArch64::STURHHi:
1740 case AArch64::STURWi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001741 if (tryToMergeLdStInst(MBBI)) {
1742 Modified = true;
1743 break;
1744 }
1745 ++MBBI;
1746 break;
1747 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001748 }
1749 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001750 // 3) Find loads and stores that can be merged into a single load or store
1751 // pair instruction.
1752 // e.g.,
1753 // ldr x0, [x2]
1754 // ldr x1, [x2, #8]
1755 // ; becomes
1756 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001757 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001758 MBBI != E;) {
1759 MachineInstr *MI = MBBI;
1760 switch (MI->getOpcode()) {
1761 default:
1762 // Just move on to the next instruction.
1763 ++MBBI;
1764 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001765 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001766 case AArch64::STRSui:
1767 case AArch64::STRDui:
1768 case AArch64::STRQui:
1769 case AArch64::STRXui:
1770 case AArch64::STRWui:
1771 case AArch64::LDRSui:
1772 case AArch64::LDRDui:
1773 case AArch64::LDRQui:
1774 case AArch64::LDRXui:
1775 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001776 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001777 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001778 case AArch64::STURSi:
1779 case AArch64::STURDi:
1780 case AArch64::STURQi:
1781 case AArch64::STURWi:
1782 case AArch64::STURXi:
1783 case AArch64::LDURSi:
1784 case AArch64::LDURDi:
1785 case AArch64::LDURQi:
1786 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001787 case AArch64::LDURXi:
1788 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001789 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001790 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001791 break;
1792 }
1793 ++MBBI;
1794 break;
1795 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001796 }
1797 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001798 // 4) Find base register updates that can be merged into the load or store
1799 // as a base-reg writeback.
1800 // e.g.,
1801 // ldr x0, [x2]
1802 // add x2, x2, #4
1803 // ; becomes
1804 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001805 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1806 MBBI != E;) {
1807 MachineInstr *MI = MBBI;
1808 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001809 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001810 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001811 switch (Opc) {
1812 default:
1813 // Just move on to the next instruction.
1814 ++MBBI;
1815 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001816 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001817 case AArch64::STRSui:
1818 case AArch64::STRDui:
1819 case AArch64::STRQui:
1820 case AArch64::STRXui:
1821 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001822 case AArch64::STRHHui:
1823 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001824 case AArch64::LDRSui:
1825 case AArch64::LDRDui:
1826 case AArch64::LDRQui:
1827 case AArch64::LDRXui:
1828 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001829 case AArch64::LDRHHui:
1830 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001831 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001832 case AArch64::STURSi:
1833 case AArch64::STURDi:
1834 case AArch64::STURQi:
1835 case AArch64::STURWi:
1836 case AArch64::STURXi:
1837 case AArch64::LDURSi:
1838 case AArch64::LDURDi:
1839 case AArch64::LDURQi:
1840 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001841 case AArch64::LDURXi:
1842 // Paired instructions.
1843 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001844 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001845 case AArch64::LDPDi:
1846 case AArch64::LDPQi:
1847 case AArch64::LDPWi:
1848 case AArch64::LDPXi:
1849 case AArch64::STPSi:
1850 case AArch64::STPDi:
1851 case AArch64::STPQi:
1852 case AArch64::STPWi:
1853 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001854 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001855 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001856 ++MBBI;
1857 break;
1858 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001859 // Look forward to try to form a post-index instruction. For example,
1860 // ldr x0, [x20]
1861 // add x20, x20, #32
1862 // merged into:
1863 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001864 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001865 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001866 if (Update != E) {
1867 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001868 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001869 Modified = true;
1870 ++NumPostFolded;
1871 break;
1872 }
1873 // Don't know how to handle pre/post-index versions, so move to the next
1874 // instruction.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001875 if (TII->isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001876 ++MBBI;
1877 break;
1878 }
1879
1880 // Look back to try to find a pre-index instruction. For example,
1881 // add x0, x0, #8
1882 // ldr x1, [x0]
1883 // merged into:
1884 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001885 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001886 if (Update != E) {
1887 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001888 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001889 Modified = true;
1890 ++NumPreFolded;
1891 break;
1892 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001893 // The immediate in the load/store is scaled by the size of the memory
1894 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001895 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001896 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001897
Tim Northover3b0846e2014-05-24 12:50:23 +00001898 // Look forward to try to find a post-index instruction. For example,
1899 // ldr x1, [x0, #64]
1900 // add x0, x0, #64
1901 // merged into:
1902 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001903 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001904 if (Update != E) {
1905 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001906 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 Modified = true;
1908 ++NumPreFolded;
1909 break;
1910 }
1911
1912 // Nothing found. Just move to the next instruction.
1913 ++MBBI;
1914 break;
1915 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001916 }
1917 }
1918
1919 return Modified;
1920}
1921
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001922bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Chad Rosiercd2be7f2016-02-12 15:51:51 +00001923 bool ProfitableArch = Subtarget->isCortexA57() || Subtarget->isKryo();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001924 // FIXME: The benefit from converting narrow loads into a wider load could be
1925 // microarchitectural as it assumes that a single load with two bitfield
1926 // extracts is cheaper than two narrow loads. Currently, this conversion is
1927 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001928 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001929}
1930
Tim Northover3b0846e2014-05-24 12:50:23 +00001931bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001932 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1933 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1934 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001935
Chad Rosierbba881e2016-02-02 15:02:30 +00001936 // Resize the modified and used register bitfield trackers. We do this once
1937 // per function and then clear the bitfield each time we optimize a load or
1938 // store.
1939 ModifiedRegs.resize(TRI->getNumRegs());
1940 UsedRegs.resize(TRI->getNumRegs());
1941
Tim Northover3b0846e2014-05-24 12:50:23 +00001942 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001943 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001944 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001945 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001946
1947 return Modified;
1948}
1949
1950// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1951// loads and stores near one another?
1952
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001953// FIXME: When pairing store instructions it's very possible for this pass to
1954// hoist a store with a KILL marker above another use (without a KILL marker).
1955// The resulting IR is invalid, but nothing uses the KILL markers after this
1956// pass, so it's never caused a problem in practice.
1957
Chad Rosier43f5c842015-08-05 12:40:13 +00001958/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1959/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001960FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1961 return new AArch64LoadStoreOpt();
1962}