blob: d780644d884d8c49c3341c7ae22e10535bd72e7f [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 Lim80ec0d32015-11-20 21:14:07 +000041STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000042STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000043
Chad Rosier35706ad2016-02-04 21:26:02 +000044// The LdStLimit limits how far we search for load/store pairs.
45static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000046 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000047
Chad Rosier35706ad2016-02-04 21:26:02 +000048// The UpdateLimit limits how far we search for update instructions when we form
49// pre-/post-index instructions.
50static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
51 cl::Hidden);
52
Chad Rosier96530b32015-08-05 13:44:51 +000053#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
54
Tim Northover3b0846e2014-05-24 12:50:23 +000055namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000056
57typedef struct LdStPairFlags {
58 // If a matching instruction is found, MergeForward is set to true if the
59 // merge is to remove the first instruction and replace the second with
60 // a pair-wise insn, and false if the reverse is true.
61 bool MergeForward;
62
63 // SExtIdx gives the index of the result of the load pair that must be
64 // extended. The value of SExtIdx assumes that the paired load produces the
65 // value in this order: (I, returned iterator), i.e., -1 means no value has
66 // to be extended, 0 means I, and 1 means the returned iterator.
67 int SExtIdx;
68
69 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
70
71 void setMergeForward(bool V = true) { MergeForward = V; }
72 bool getMergeForward() const { return MergeForward; }
73
74 void setSExtIdx(int V) { SExtIdx = V; }
75 int getSExtIdx() const { return SExtIdx; }
76
77} LdStPairFlags;
78
Tim Northover3b0846e2014-05-24 12:50:23 +000079struct AArch64LoadStoreOpt : public MachineFunctionPass {
80 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000081 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000082 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
83 }
Tim Northover3b0846e2014-05-24 12:50:23 +000084
85 const AArch64InstrInfo *TII;
86 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000087 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000088
Chad Rosierbba881e2016-02-02 15:02:30 +000089 // Track which registers have been modified and used.
90 BitVector ModifiedRegs, UsedRegs;
91
Tim Northover3b0846e2014-05-24 12:50:23 +000092 // Scan the instructions looking for a load/store that can be combined
93 // with the current instruction into a load/store pair.
94 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +000095 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +000096 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +000097 unsigned Limit,
98 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000099
100 // Scan the instructions looking for a store that writes to the address from
101 // which the current load instruction reads. Return true if one is found.
102 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
103 MachineBasicBlock::iterator &StoreI);
104
Chad Rosierd6daac42016-11-07 15:27:22 +0000105 // Merge the two instructions indicated into a wider narrow store instruction.
Chad Rosierb5933d72016-02-09 19:02:12 +0000106 MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000107 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
108 MachineBasicBlock::iterator MergeMI,
109 const LdStPairFlags &Flags);
Chad Rosierb5933d72016-02-09 19:02:12 +0000110
Tim Northover3b0846e2014-05-24 12:50:23 +0000111 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000112 MachineBasicBlock::iterator
113 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000114 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000115 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000116
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000117 // Promote the load that reads directly from the address stored to.
118 MachineBasicBlock::iterator
119 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
120 MachineBasicBlock::iterator StoreI);
121
Tim Northover3b0846e2014-05-24 12:50:23 +0000122 // Scan the instruction list to find a base register update that can
123 // be combined with the current instruction (a load or store) using
124 // pre or post indexed addressing with writeback. Scan forwards.
125 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000126 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000127 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000128
129 // Scan the instruction list to find a base register update that can
130 // be combined with the current instruction (a load or store) using
131 // pre or post indexed addressing with writeback. Scan backwards.
132 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000133 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000134
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000135 // Find an instruction that updates the base register of the ld/st
136 // instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000137 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000138 unsigned BaseReg, int Offset);
139
Chad Rosier2dfd3542015-09-23 13:51:44 +0000140 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000141 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000142 mergeUpdateInsn(MachineBasicBlock::iterator I,
143 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000144
Chad Rosierd6daac42016-11-07 15:27:22 +0000145 // Find and merge zero store instructions.
146 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000147
Chad Rosier24c46ad2016-02-09 18:10:20 +0000148 // Find and pair ldr/str instructions.
149 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
150
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000151 // Find and promote load instructions which read directly from store.
152 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
153
Chad Rosierd6daac42016-11-07 15:27:22 +0000154 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000155
156 bool runOnMachineFunction(MachineFunction &Fn) override;
157
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000158 MachineFunctionProperties getRequiredProperties() const override {
159 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000160 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000161 }
162
Mehdi Amini117296c2016-10-01 02:56:57 +0000163 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000164};
165char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000166} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000167
Chad Rosier96530b32015-08-05 13:44:51 +0000168INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
169 AARCH64_LOAD_STORE_OPT_NAME, false, false)
170
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000171static bool isNarrowStore(unsigned Opc) {
172 switch (Opc) {
173 default:
174 return false;
175 case AArch64::STRBBui:
176 case AArch64::STURBBi:
177 case AArch64::STRHHui:
178 case AArch64::STURHHi:
179 return true;
180 }
181}
182
Chad Rosier32d4d372015-09-29 16:07:32 +0000183// Scaling factor for unscaled load or store.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000184static int getMemScale(MachineInstr &MI) {
185 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000187 llvm_unreachable("Opcode has unknown scale!");
188 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000189 case AArch64::LDURBBi:
190 case AArch64::LDRSBWui:
191 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000192 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000193 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000194 return 1;
195 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000196 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000197 case AArch64::LDRSHWui:
198 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000199 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000200 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000201 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000202 case AArch64::LDRSui:
203 case AArch64::LDURSi:
204 case AArch64::LDRSWui:
205 case AArch64::LDURSWi:
206 case AArch64::LDRWui:
207 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000208 case AArch64::STRSui:
209 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000210 case AArch64::STRWui:
211 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000212 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000213 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000214 case AArch64::LDPWi:
215 case AArch64::STPSi:
216 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000217 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000218 case AArch64::LDRDui:
219 case AArch64::LDURDi:
220 case AArch64::LDRXui:
221 case AArch64::LDURXi:
222 case AArch64::STRDui:
223 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000224 case AArch64::STRXui:
225 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000226 case AArch64::LDPDi:
227 case AArch64::LDPXi:
228 case AArch64::STPDi:
229 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000230 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000231 case AArch64::LDRQui:
232 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000233 case AArch64::STRQui:
234 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000235 case AArch64::LDPQi:
236 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000237 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000238 }
239}
240
Quentin Colombet66b61632015-03-06 22:42:10 +0000241static unsigned getMatchingNonSExtOpcode(unsigned Opc,
242 bool *IsValidLdStrOpc = nullptr) {
243 if (IsValidLdStrOpc)
244 *IsValidLdStrOpc = true;
245 switch (Opc) {
246 default:
247 if (IsValidLdStrOpc)
248 *IsValidLdStrOpc = false;
249 return UINT_MAX;
250 case AArch64::STRDui:
251 case AArch64::STURDi:
252 case AArch64::STRQui:
253 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000254 case AArch64::STRBBui:
255 case AArch64::STURBBi:
256 case AArch64::STRHHui:
257 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000258 case AArch64::STRWui:
259 case AArch64::STURWi:
260 case AArch64::STRXui:
261 case AArch64::STURXi:
262 case AArch64::LDRDui:
263 case AArch64::LDURDi:
264 case AArch64::LDRQui:
265 case AArch64::LDURQi:
266 case AArch64::LDRWui:
267 case AArch64::LDURWi:
268 case AArch64::LDRXui:
269 case AArch64::LDURXi:
270 case AArch64::STRSui:
271 case AArch64::STURSi:
272 case AArch64::LDRSui:
273 case AArch64::LDURSi:
274 return Opc;
275 case AArch64::LDRSWui:
276 return AArch64::LDRWui;
277 case AArch64::LDURSWi:
278 return AArch64::LDURWi;
279 }
280}
281
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000282static unsigned getMatchingWideOpcode(unsigned Opc) {
283 switch (Opc) {
284 default:
285 llvm_unreachable("Opcode has no wide equivalent!");
286 case AArch64::STRBBui:
287 return AArch64::STRHHui;
288 case AArch64::STRHHui:
289 return AArch64::STRWui;
290 case AArch64::STURBBi:
291 return AArch64::STURHHi;
292 case AArch64::STURHHi:
293 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000294 case AArch64::STURWi:
295 return AArch64::STURXi;
296 case AArch64::STRWui:
297 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000298 }
299}
300
Tim Northover3b0846e2014-05-24 12:50:23 +0000301static unsigned getMatchingPairOpcode(unsigned Opc) {
302 switch (Opc) {
303 default:
304 llvm_unreachable("Opcode has no pairwise equivalent!");
305 case AArch64::STRSui:
306 case AArch64::STURSi:
307 return AArch64::STPSi;
308 case AArch64::STRDui:
309 case AArch64::STURDi:
310 return AArch64::STPDi;
311 case AArch64::STRQui:
312 case AArch64::STURQi:
313 return AArch64::STPQi;
314 case AArch64::STRWui:
315 case AArch64::STURWi:
316 return AArch64::STPWi;
317 case AArch64::STRXui:
318 case AArch64::STURXi:
319 return AArch64::STPXi;
320 case AArch64::LDRSui:
321 case AArch64::LDURSi:
322 return AArch64::LDPSi;
323 case AArch64::LDRDui:
324 case AArch64::LDURDi:
325 return AArch64::LDPDi;
326 case AArch64::LDRQui:
327 case AArch64::LDURQi:
328 return AArch64::LDPQi;
329 case AArch64::LDRWui:
330 case AArch64::LDURWi:
331 return AArch64::LDPWi;
332 case AArch64::LDRXui:
333 case AArch64::LDURXi:
334 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000335 case AArch64::LDRSWui:
336 case AArch64::LDURSWi:
337 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000338 }
339}
340
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000341static unsigned isMatchingStore(MachineInstr &LoadInst,
342 MachineInstr &StoreInst) {
343 unsigned LdOpc = LoadInst.getOpcode();
344 unsigned StOpc = StoreInst.getOpcode();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000345 switch (LdOpc) {
346 default:
347 llvm_unreachable("Unsupported load instruction!");
348 case AArch64::LDRBBui:
349 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
350 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
351 case AArch64::LDURBBi:
352 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
353 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
354 case AArch64::LDRHHui:
355 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
356 StOpc == AArch64::STRXui;
357 case AArch64::LDURHHi:
358 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
359 StOpc == AArch64::STURXi;
360 case AArch64::LDRWui:
361 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
362 case AArch64::LDURWi:
363 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
364 case AArch64::LDRXui:
365 return StOpc == AArch64::STRXui;
366 case AArch64::LDURXi:
367 return StOpc == AArch64::STURXi;
368 }
369}
370
Tim Northover3b0846e2014-05-24 12:50:23 +0000371static unsigned getPreIndexedOpcode(unsigned Opc) {
372 switch (Opc) {
373 default:
374 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000375 case AArch64::STRSui:
376 return AArch64::STRSpre;
377 case AArch64::STRDui:
378 return AArch64::STRDpre;
379 case AArch64::STRQui:
380 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000381 case AArch64::STRBBui:
382 return AArch64::STRBBpre;
383 case AArch64::STRHHui:
384 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000385 case AArch64::STRWui:
386 return AArch64::STRWpre;
387 case AArch64::STRXui:
388 return AArch64::STRXpre;
389 case AArch64::LDRSui:
390 return AArch64::LDRSpre;
391 case AArch64::LDRDui:
392 return AArch64::LDRDpre;
393 case AArch64::LDRQui:
394 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000395 case AArch64::LDRBBui:
396 return AArch64::LDRBBpre;
397 case AArch64::LDRHHui:
398 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000399 case AArch64::LDRWui:
400 return AArch64::LDRWpre;
401 case AArch64::LDRXui:
402 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000403 case AArch64::LDRSWui:
404 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000405 case AArch64::LDPSi:
406 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000407 case AArch64::LDPSWi:
408 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000409 case AArch64::LDPDi:
410 return AArch64::LDPDpre;
411 case AArch64::LDPQi:
412 return AArch64::LDPQpre;
413 case AArch64::LDPWi:
414 return AArch64::LDPWpre;
415 case AArch64::LDPXi:
416 return AArch64::LDPXpre;
417 case AArch64::STPSi:
418 return AArch64::STPSpre;
419 case AArch64::STPDi:
420 return AArch64::STPDpre;
421 case AArch64::STPQi:
422 return AArch64::STPQpre;
423 case AArch64::STPWi:
424 return AArch64::STPWpre;
425 case AArch64::STPXi:
426 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000427 }
428}
429
430static unsigned getPostIndexedOpcode(unsigned Opc) {
431 switch (Opc) {
432 default:
433 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
434 case AArch64::STRSui:
435 return AArch64::STRSpost;
436 case AArch64::STRDui:
437 return AArch64::STRDpost;
438 case AArch64::STRQui:
439 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000440 case AArch64::STRBBui:
441 return AArch64::STRBBpost;
442 case AArch64::STRHHui:
443 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000444 case AArch64::STRWui:
445 return AArch64::STRWpost;
446 case AArch64::STRXui:
447 return AArch64::STRXpost;
448 case AArch64::LDRSui:
449 return AArch64::LDRSpost;
450 case AArch64::LDRDui:
451 return AArch64::LDRDpost;
452 case AArch64::LDRQui:
453 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000454 case AArch64::LDRBBui:
455 return AArch64::LDRBBpost;
456 case AArch64::LDRHHui:
457 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000458 case AArch64::LDRWui:
459 return AArch64::LDRWpost;
460 case AArch64::LDRXui:
461 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000462 case AArch64::LDRSWui:
463 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000464 case AArch64::LDPSi:
465 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000466 case AArch64::LDPSWi:
467 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000468 case AArch64::LDPDi:
469 return AArch64::LDPDpost;
470 case AArch64::LDPQi:
471 return AArch64::LDPQpost;
472 case AArch64::LDPWi:
473 return AArch64::LDPWpost;
474 case AArch64::LDPXi:
475 return AArch64::LDPXpost;
476 case AArch64::STPSi:
477 return AArch64::STPSpost;
478 case AArch64::STPDi:
479 return AArch64::STPDpost;
480 case AArch64::STPQi:
481 return AArch64::STPQpost;
482 case AArch64::STPWi:
483 return AArch64::STPWpost;
484 case AArch64::STPXi:
485 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000486 }
487}
488
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000489static bool isPairedLdSt(const MachineInstr &MI) {
490 switch (MI.getOpcode()) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000491 default:
492 return false;
493 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000494 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000495 case AArch64::LDPDi:
496 case AArch64::LDPQi:
497 case AArch64::LDPWi:
498 case AArch64::LDPXi:
499 case AArch64::STPSi:
500 case AArch64::STPDi:
501 case AArch64::STPQi:
502 case AArch64::STPWi:
503 case AArch64::STPXi:
504 return true;
505 }
506}
507
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000508static const MachineOperand &getLdStRegOp(const MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000509 unsigned PairedRegOp = 0) {
510 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
511 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000512 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000513}
514
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000515static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000516 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000517 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000518}
519
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000520static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000521 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000522 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000523}
524
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000525static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
526 MachineInstr &StoreInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000527 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000528 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
529 int LoadSize = getMemScale(LoadInst);
530 int StoreSize = getMemScale(StoreInst);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000531 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000532 ? getLdStOffsetOp(StoreInst).getImm()
533 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000534 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000535 ? getLdStOffsetOp(LoadInst).getImm()
536 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
537 return (UnscaledStOffset <= UnscaledLdOffset) &&
538 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
539}
540
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000541static bool isPromotableZeroStoreInst(MachineInstr &MI) {
Chad Rosierd6daac42016-11-07 15:27:22 +0000542 unsigned Opc = MI.getOpcode();
543 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
544 isNarrowStore(Opc)) &&
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000545 getLdStRegOp(MI).getReg() == AArch64::WZR;
546}
547
Tim Northover3b0846e2014-05-24 12:50:23 +0000548MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000549AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
550 MachineBasicBlock::iterator MergeMI,
551 const LdStPairFlags &Flags) {
552 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
553 "Expected promotable zero stores.");
554
Tim Northover3b0846e2014-05-24 12:50:23 +0000555 MachineBasicBlock::iterator NextI = I;
556 ++NextI;
557 // If NextI is the second of the two instructions to be merged, we need
558 // to skip one further. Either way we merge will invalidate the iterator,
559 // and we don't need to scan the new instruction, as it's a pairwise
560 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000561 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000562 ++NextI;
563
Chad Rosierb5933d72016-02-09 19:02:12 +0000564 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000565 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000566 int OffsetStride = IsScaled ? 1 : getMemScale(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000567
Chad Rosier96a18a92015-07-21 17:42:04 +0000568 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000569 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000570 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000571 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000572 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000573 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000574 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000575 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000576
577 // Which register is Rt and which is Rt2 depends on the offset order.
Davide Italiano5df60662016-11-07 19:11:25 +0000578 MachineInstr *RtMI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000579 if (getLdStOffsetOp(*I).getImm() ==
Davide Italiano5df60662016-11-07 19:11:25 +0000580 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000581 RtMI = &*MergeMI;
Davide Italiano5df60662016-11-07 19:11:25 +0000582 else
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000583 RtMI = &*I;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000584
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000585 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000586 // Change the scaled offset from small to large type.
587 if (IsScaled) {
588 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
589 OffsetImm /= 2;
590 }
591
Chad Rosierd6daac42016-11-07 15:27:22 +0000592 // Construct the new instruction.
Chad Rosierc46ef882016-02-09 19:33:42 +0000593 DebugLoc DL = I->getDebugLoc();
594 MachineBasicBlock *MBB = I->getParent();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000595 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000596 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000597 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Diana Picus116bbab2017-01-13 09:58:52 +0000598 .add(BaseRegOp)
Chad Rosierb5933d72016-02-09 19:02:12 +0000599 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000600 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000601 (void)MIB;
602
Chad Rosierd6daac42016-11-07 15:27:22 +0000603 DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
Chad Rosierb5933d72016-02-09 19:02:12 +0000604 DEBUG(I->print(dbgs()));
605 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000606 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000607 DEBUG(dbgs() << " with instruction:\n ");
608 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
609 DEBUG(dbgs() << "\n");
610
611 // Erase the old instructions.
612 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000613 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000614 return NextI;
615}
616
617MachineBasicBlock::iterator
618AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
619 MachineBasicBlock::iterator Paired,
620 const LdStPairFlags &Flags) {
621 MachineBasicBlock::iterator NextI = I;
622 ++NextI;
623 // If NextI is the second of the two instructions to be merged, we need
624 // to skip one further. Either way we merge will invalidate the iterator,
625 // and we don't need to scan the new instruction, as it's a pairwise
626 // instruction, which we're not considering for further action anyway.
627 if (NextI == Paired)
628 ++NextI;
629
630 int SExtIdx = Flags.getSExtIdx();
631 unsigned Opc =
632 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000633 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000634 int OffsetStride = IsUnscaled ? getMemScale(*I) : 1;
Chad Rosierb5933d72016-02-09 19:02:12 +0000635
636 bool MergeForward = Flags.getMergeForward();
637 // Insert our new paired instruction after whichever of the paired
638 // instructions MergeForward indicates.
639 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
640 // Also based on MergeForward is from where we copy the base register operand
641 // so we get the flags compatible with the input code.
642 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000643 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
Chad Rosierb5933d72016-02-09 19:02:12 +0000644
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000645 int Offset = getLdStOffsetOp(*I).getImm();
646 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000647 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000648 if (IsUnscaled != PairedIsUnscaled) {
649 // We're trying to pair instructions that differ in how they are scaled. If
650 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
651 // the opposite (i.e., make Paired's offset unscaled).
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000652 int MemSize = getMemScale(*Paired);
Chad Rosier00f9d232016-02-11 14:25:08 +0000653 if (PairedIsUnscaled) {
654 // If the unscaled offset isn't a multiple of the MemSize, we can't
655 // pair the operations together.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000656 assert(!(PairedOffset % getMemScale(*Paired)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000657 "Offset should be a multiple of the stride!");
658 PairedOffset /= MemSize;
659 } else {
660 PairedOffset *= MemSize;
661 }
662 }
663
Chad Rosierb5933d72016-02-09 19:02:12 +0000664 // Which register is Rt and which is Rt2 depends on the offset order.
665 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000666 if (Offset == PairedOffset + OffsetStride) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000667 RtMI = &*Paired;
668 Rt2MI = &*I;
Chad Rosierb5933d72016-02-09 19:02:12 +0000669 // Here we swapped the assumption made for SExtIdx.
670 // I.e., we turn ldp I, Paired into ldp Paired, I.
671 // Update the index accordingly.
672 if (SExtIdx != -1)
673 SExtIdx = (SExtIdx + 1) % 2;
674 } else {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000675 RtMI = &*I;
676 Rt2MI = &*Paired;
Chad Rosierb5933d72016-02-09 19:02:12 +0000677 }
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000678 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000679 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000680 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000681 assert(!(OffsetImm % getMemScale(*RtMI)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000682 "Unscaled offset cannot be scaled.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000683 OffsetImm /= getMemScale(*RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000684 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000685
686 // Construct the new instruction.
687 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000688 DebugLoc DL = I->getDebugLoc();
689 MachineBasicBlock *MBB = I->getParent();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000690 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
691 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
692 // Kill flags may become invalid when moving stores for pairing.
693 if (RegOp0.isUse()) {
694 if (!MergeForward) {
695 // Clear kill flags on store if moving upwards. Example:
696 // STRWui %w0, ...
697 // USE %w1
698 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
699 RegOp0.setIsKill(false);
700 RegOp1.setIsKill(false);
701 } else {
702 // Clear kill flags of the first stores register. Example:
703 // STRWui %w1, ...
704 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
705 // STRW %w0
706 unsigned Reg = getLdStRegOp(*I).getReg();
707 for (MachineInstr &MI : make_range(std::next(I), Paired))
708 MI.clearRegisterKills(Reg, TRI);
709 }
710 }
Chad Rosierc46ef882016-02-09 19:33:42 +0000711 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000712 .add(RegOp0)
713 .add(RegOp1)
Diana Picus116bbab2017-01-13 09:58:52 +0000714 .add(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000715 .addImm(OffsetImm)
716 .setMemRefs(I->mergeMemRefsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000717
718 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000719
720 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
721 DEBUG(I->print(dbgs()));
722 DEBUG(dbgs() << " ");
723 DEBUG(Paired->print(dbgs()));
724 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000725 if (SExtIdx != -1) {
726 // Generate the sign extension for the proper result of the ldp.
727 // I.e., with X1, that would be:
728 // %W1<def> = KILL %W1, %X1<imp-def>
729 // %X1<def> = SBFMXri %X1<kill>, 0, 31
730 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
731 // Right now, DstMO has the extended register, since it comes from an
732 // extended opcode.
733 unsigned DstRegX = DstMO.getReg();
734 // Get the W variant of that register.
735 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
736 // Update the result of LDP to use the W instead of the X variant.
737 DstMO.setReg(DstRegW);
738 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
739 DEBUG(dbgs() << "\n");
740 // Make the machine verifier happy by providing a definition for
741 // the X register.
742 // Insert this definition right after the generated LDP, i.e., before
743 // InsertionPoint.
744 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000745 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000746 .addReg(DstRegW)
747 .addReg(DstRegX, RegState::Define);
748 MIBKill->getOperand(2).setImplicit();
749 // Create the sign extension.
750 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000751 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000752 .addReg(DstRegX)
753 .addImm(0)
754 .addImm(31);
755 (void)MIBSXTW;
756 DEBUG(dbgs() << " Extend operand:\n ");
757 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000758 } else {
759 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000760 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000761 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000762
763 // Erase the old instructions.
764 I->eraseFromParent();
765 Paired->eraseFromParent();
766
767 return NextI;
768}
769
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000770MachineBasicBlock::iterator
771AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
772 MachineBasicBlock::iterator StoreI) {
773 MachineBasicBlock::iterator NextI = LoadI;
774 ++NextI;
775
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000776 int LoadSize = getMemScale(*LoadI);
777 int StoreSize = getMemScale(*StoreI);
778 unsigned LdRt = getLdStRegOp(*LoadI).getReg();
779 unsigned StRt = getLdStRegOp(*StoreI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000780 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
781
782 assert((IsStoreXReg ||
783 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
784 "Unexpected RegClass");
785
786 MachineInstr *BitExtMI;
787 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
788 // Remove the load, if the destination register of the loads is the same
789 // register for stored value.
790 if (StRt == LdRt && LoadSize == 8) {
Matthias Braun76bb4132016-12-16 23:55:43 +0000791 StoreI->clearRegisterKills(StRt, TRI);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000792 DEBUG(dbgs() << "Remove load instruction:\n ");
793 DEBUG(LoadI->print(dbgs()));
794 DEBUG(dbgs() << "\n");
795 LoadI->eraseFromParent();
796 return NextI;
797 }
798 // Replace the load with a mov if the load and store are in the same size.
799 BitExtMI =
800 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
801 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
802 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
803 .addReg(StRt)
804 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
805 } else {
806 // FIXME: Currently we disable this transformation in big-endian targets as
807 // performance and correctness are verified only in little-endian.
808 if (!Subtarget->isLittleEndian())
809 return NextI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000810 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
811 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000812 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000813 assert(LoadSize <= StoreSize && "Invalid load size");
814 int UnscaledLdOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000815 ? getLdStOffsetOp(*LoadI).getImm()
816 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000817 int UnscaledStOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000818 ? getLdStOffsetOp(*StoreI).getImm()
819 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000820 int Width = LoadSize * 8;
821 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
822 int Imms = Immr + Width - 1;
823 unsigned DestReg = IsStoreXReg
824 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
825 &AArch64::GPR64RegClass)
826 : LdRt;
827
828 assert((UnscaledLdOffset >= UnscaledStOffset &&
829 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
830 "Invalid offset");
831
832 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
833 Imms = Immr + Width - 1;
834 if (UnscaledLdOffset == UnscaledStOffset) {
835 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
836 | ((Immr) << 6) // immr
837 | ((Imms) << 0) // imms
838 ;
839
840 BitExtMI =
841 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
842 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
843 DestReg)
844 .addReg(StRt)
845 .addImm(AndMaskEncoded);
846 } else {
847 BitExtMI =
848 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
849 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
850 DestReg)
851 .addReg(StRt)
852 .addImm(Immr)
853 .addImm(Imms);
854 }
855 }
Matthias Braun76bb4132016-12-16 23:55:43 +0000856 StoreI->clearRegisterKills(StRt, TRI);
857
Chad Rosierf7ac5f22016-03-30 18:08:51 +0000858 (void)BitExtMI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000859
860 DEBUG(dbgs() << "Promoting load by replacing :\n ");
861 DEBUG(StoreI->print(dbgs()));
862 DEBUG(dbgs() << " ");
863 DEBUG(LoadI->print(dbgs()));
864 DEBUG(dbgs() << " with instructions:\n ");
865 DEBUG(StoreI->print(dbgs()));
866 DEBUG(dbgs() << " ");
867 DEBUG((BitExtMI)->print(dbgs()));
868 DEBUG(dbgs() << "\n");
869
870 // Erase the old instructions.
871 LoadI->eraseFromParent();
872 return NextI;
873}
874
Tim Northover3b0846e2014-05-24 12:50:23 +0000875/// trackRegDefsUses - Remember what registers the specified instruction uses
876/// and modifies.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000877static void trackRegDefsUses(const MachineInstr &MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000878 BitVector &UsedRegs,
879 const TargetRegisterInfo *TRI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000880 for (const MachineOperand &MO : MI.operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000881 if (MO.isRegMask())
882 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
883
884 if (!MO.isReg())
885 continue;
886 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +0000887 if (!Reg)
888 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +0000889 if (MO.isDef()) {
Geoff Berrye0bf52f2016-11-21 22:51:10 +0000890 // WZR/XZR are not modified even when used as a destination register.
891 if (Reg != AArch64::WZR && Reg != AArch64::XZR)
892 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
893 ModifiedRegs.set(*AI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000894 } else {
895 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
896 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
897 UsedRegs.set(*AI);
898 }
899 }
900}
901
902static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +0000903 // Convert the byte-offset used by unscaled into an "element" offset used
904 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +0000905 if (IsUnscaled) {
906 // If the byte-offset isn't a multiple of the stride, there's no point
907 // trying to match it.
908 if (Offset % OffsetStride)
909 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +0000910 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +0000911 }
Chad Rosier3dd0e942015-08-18 16:20:03 +0000912 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +0000913}
914
915// Do alignment, specialized to power of 2 and for signed ints,
916// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000917// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +0000918// FIXME: Move this function to include/MathExtras.h?
919static int alignTo(int Num, int PowOf2) {
920 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
921}
922
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000923static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000924 const AArch64InstrInfo *TII) {
925 // One of the instructions must modify memory.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000926 if (!MIa.mayStore() && !MIb.mayStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000927 return false;
928
929 // Both instructions must be memory operations.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000930 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000931 return false;
932
933 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
934}
935
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000936static bool mayAlias(MachineInstr &MIa,
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000937 SmallVectorImpl<MachineInstr *> &MemInsns,
938 const AArch64InstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000939 for (MachineInstr *MIb : MemInsns)
940 if (mayAlias(MIa, *MIb, TII))
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000941 return true;
942
943 return false;
944}
945
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000946bool AArch64LoadStoreOpt::findMatchingStore(
947 MachineBasicBlock::iterator I, unsigned Limit,
948 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +0000949 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000950 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000951 MachineInstr &LoadMI = *I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +0000952 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000953
Jun Bum Lim633b2d82016-02-11 16:18:24 +0000954 // If the load is the first instruction in the block, there's obviously
955 // not any matching store.
956 if (MBBI == B)
957 return false;
958
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000959 // Track which registers have been modified and used between the first insn
960 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +0000961 ModifiedRegs.reset();
962 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000963
Jun Bum Lim633b2d82016-02-11 16:18:24 +0000964 unsigned Count = 0;
965 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000966 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000967 MachineInstr &MI = *MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +0000968
Geoff Berry4ff2e362016-07-21 15:20:25 +0000969 // Don't count transient instructions towards the search limit since there
970 // may be different numbers of them if e.g. debug information is present.
971 if (!MI.isTransient())
Jun Bum Lim633b2d82016-02-11 16:18:24 +0000972 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000973
974 // If the load instruction reads directly from the address to which the
975 // store instruction writes and the stored value is not modified, we can
976 // promote the load. Since we do not handle stores with pre-/post-index,
977 // it's unnecessary to check if BaseReg is modified by the store itself.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000978 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000979 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000980 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000981 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
982 StoreI = MBBI;
983 return true;
984 }
985
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000986 if (MI.isCall())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000987 return false;
988
989 // Update modified / uses register lists.
990 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
991
992 // Otherwise, if the base register is modified, we have no match, so
993 // return early.
994 if (ModifiedRegs[BaseReg])
995 return false;
996
997 // If we encounter a store aliased with the load, return early.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000998 if (MI.mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000999 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001000 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001001 return false;
1002}
1003
Chad Rosierc5083c22016-06-10 20:47:14 +00001004// Returns true if FirstMI and MI are candidates for merging or pairing.
1005// Otherwise, returns false.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001006static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
Chad Rosierc5083c22016-06-10 20:47:14 +00001007 LdStPairFlags &Flags,
1008 const AArch64InstrInfo *TII) {
1009 // If this is volatile or if pairing is suppressed, not a candidate.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001010 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
Chad Rosierc5083c22016-06-10 20:47:14 +00001011 return false;
1012
1013 // We should have already checked FirstMI for pair suppression and volatility.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001014 assert(!FirstMI.hasOrderedMemoryRef() &&
1015 !TII->isLdStPairSuppressed(FirstMI) &&
Chad Rosierc5083c22016-06-10 20:47:14 +00001016 "FirstMI shouldn't get here if either of these checks are true.");
1017
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001018 unsigned OpcA = FirstMI.getOpcode();
1019 unsigned OpcB = MI.getOpcode();
Chad Rosierc5083c22016-06-10 20:47:14 +00001020
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001021 // Opcodes match: nothing more to check.
1022 if (OpcA == OpcB)
1023 return true;
1024
1025 // Try to match a sign-extended load/store with a zero-extended load/store.
1026 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1027 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1028 assert(IsValidLdStrOpc &&
1029 "Given Opc should be a Load or Store with an immediate");
1030 // OpcA will be the first instruction in the pair.
1031 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1032 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1033 return true;
1034 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001035
Chad Rosierd6daac42016-11-07 15:27:22 +00001036 // If the second instruction isn't even a mergable/pairable load/store, bail
1037 // out.
Chad Rosier00f9d232016-02-11 14:25:08 +00001038 if (!PairIsValidLdStrOpc)
1039 return false;
1040
Chad Rosierd6daac42016-11-07 15:27:22 +00001041 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1042 // offsets.
1043 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
Chad Rosier00f9d232016-02-11 14:25:08 +00001044 return false;
1045
1046 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001047 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001048 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1049
1050 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001051}
1052
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001053/// Scan the instructions looking for a load/store that can be combined with the
1054/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001055MachineBasicBlock::iterator
1056AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001057 LdStPairFlags &Flags, unsigned Limit,
1058 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001059 MachineBasicBlock::iterator E = I->getParent()->end();
1060 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001061 MachineInstr &FirstMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001062 ++MBBI;
1063
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001064 bool MayLoad = FirstMI.mayLoad();
1065 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001066 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1067 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1068 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001069 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001070 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001071
1072 // Track which registers have been modified and used between the first insn
1073 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001074 ModifiedRegs.reset();
1075 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001076
1077 // Remember any instructions that read/write memory between FirstMI and MI.
1078 SmallVector<MachineInstr *, 4> MemInsns;
1079
Tim Northover3b0846e2014-05-24 12:50:23 +00001080 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001081 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001082
Geoff Berry4ff2e362016-07-21 15:20:25 +00001083 // Don't count transient instructions towards the search limit since there
1084 // may be different numbers of them if e.g. debug information is present.
1085 if (!MI.isTransient())
1086 ++Count;
Tim Northover3b0846e2014-05-24 12:50:23 +00001087
Chad Rosier18896c02016-02-04 16:01:40 +00001088 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001089 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001090 getLdStOffsetOp(MI).isImm()) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001091 assert(MI.mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001092 // If we've found another instruction with the same opcode, check to see
1093 // if the base and offset are compatible with our starting instruction.
1094 // These instructions all have scaled immediate operands, so we just
1095 // check for +1/-1. Make sure to check the new instruction offset is
1096 // actually an immediate and not a symbolic reference destined for
1097 // a relocation.
Chad Rosierf77e9092015-08-06 15:50:12 +00001098 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1099 int MIOffset = getLdStOffsetOp(MI).getImm();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001100 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001101 if (IsUnscaled != MIIsUnscaled) {
1102 // We're trying to pair instructions that differ in how they are scaled.
1103 // If FirstMI is scaled then scale the offset of MI accordingly.
1104 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1105 int MemSize = getMemScale(MI);
1106 if (MIIsUnscaled) {
1107 // If the unscaled offset isn't a multiple of the MemSize, we can't
1108 // pair the operations together: bail and keep looking.
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001109 if (MIOffset % MemSize) {
1110 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1111 MemInsns.push_back(&MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001112 continue;
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001113 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001114 MIOffset /= MemSize;
1115 } else {
1116 MIOffset *= MemSize;
1117 }
1118 }
1119
Tim Northover3b0846e2014-05-24 12:50:23 +00001120 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1121 (Offset + OffsetStride == MIOffset))) {
1122 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001123 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001124 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001125 // instruction can't express the offset of the scaled narrow input,
1126 // bail and keep looking. For promotable zero stores, allow only when
1127 // the stored value is the same (i.e., WZR).
1128 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1129 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001130 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001131 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001132 continue;
1133 }
1134 } else {
Chad Rosierd1f6c842016-06-10 20:49:18 +00001135 // Pairwise instructions have a 7-bit signed offset field. Single
1136 // insns have a 12-bit unsigned offset field. If the resultant
1137 // immediate offset of merging these instructions is out of range for
1138 // a pairwise instruction, bail and keep looking.
Jun Bum Limcf974432016-03-31 14:47:24 +00001139 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1140 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001141 MemInsns.push_back(&MI);
Jun Bum Limcf974432016-03-31 14:47:24 +00001142 continue;
1143 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001144 // If the alignment requirements of the paired (scaled) instruction
1145 // can't express the offset of the unscaled input, bail and keep
1146 // looking.
1147 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1148 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001149 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001150 continue;
1151 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001152 }
1153 // If the destination register of the loads is the same register, bail
1154 // and keep looking. A load-pair instruction with both destination
1155 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001156 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001157 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001158 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001159 continue;
1160 }
1161
1162 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001163 // the two instructions and none of the instructions between the second
1164 // and first alias with the second, we can combine the second into the
1165 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001166 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001167 !(MI.mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
1168 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001169 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001170 return MBBI;
1171 }
1172
1173 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001174 // between the two instructions and none of the instructions between the
1175 // first and the second alias with the first, we can combine the first
1176 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001177 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001178 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001179 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001180 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001181 return MBBI;
1182 }
1183 // Unable to combine these instructions due to interference in between.
1184 // Keep looking.
1185 }
1186 }
1187
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001188 // If the instruction wasn't a matching load or store. Stop searching if we
1189 // encounter a call instruction that might modify memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001190 if (MI.isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001191 return E;
1192
1193 // Update modified / uses register lists.
1194 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1195
1196 // Otherwise, if the base register is modified, we have no match, so
1197 // return early.
1198 if (ModifiedRegs[BaseReg])
1199 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001200
1201 // Update list of instructions that read/write memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001202 if (MI.mayLoadOrStore())
1203 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001204 }
1205 return E;
1206}
1207
1208MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001209AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1210 MachineBasicBlock::iterator Update,
1211 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 assert((Update->getOpcode() == AArch64::ADDXri ||
1213 Update->getOpcode() == AArch64::SUBXri) &&
1214 "Unexpected base register update instruction to merge!");
1215 MachineBasicBlock::iterator NextI = I;
1216 // Return the instruction following the merged instruction, which is
1217 // the instruction following our unmerged load. Unless that's the add/sub
1218 // instruction we're merging, in which case it's the one after that.
1219 if (++NextI == Update)
1220 ++NextI;
1221
1222 int Value = Update->getOperand(2).getImm();
1223 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001224 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001225 if (Update->getOpcode() == AArch64::SUBXri)
1226 Value = -Value;
1227
Chad Rosier2dfd3542015-09-23 13:51:44 +00001228 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1229 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001230 MachineInstrBuilder MIB;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001231 if (!isPairedLdSt(*I)) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001232 // Non-paired instruction.
1233 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001234 .add(getLdStRegOp(*Update))
1235 .add(getLdStRegOp(*I))
1236 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001237 .addImm(Value)
1238 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001239 } else {
1240 // Paired instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001241 int Scale = getMemScale(*I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001242 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001243 .add(getLdStRegOp(*Update))
1244 .add(getLdStRegOp(*I, 0))
1245 .add(getLdStRegOp(*I, 1))
1246 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001247 .addImm(Value / Scale)
1248 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001249 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001250 (void)MIB;
1251
Chad Rosier2dfd3542015-09-23 13:51:44 +00001252 if (IsPreIdx)
1253 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1254 else
1255 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001256 DEBUG(dbgs() << " Replacing instructions:\n ");
1257 DEBUG(I->print(dbgs()));
1258 DEBUG(dbgs() << " ");
1259 DEBUG(Update->print(dbgs()));
1260 DEBUG(dbgs() << " with instruction:\n ");
1261 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1262 DEBUG(dbgs() << "\n");
1263
1264 // Erase the old instructions for the block.
1265 I->eraseFromParent();
1266 Update->eraseFromParent();
1267
1268 return NextI;
1269}
1270
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001271bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1272 MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001273 unsigned BaseReg, int Offset) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001274 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001275 default:
1276 break;
1277 case AArch64::SUBXri:
Tim Northover3b0846e2014-05-24 12:50:23 +00001278 case AArch64::ADDXri:
1279 // Make sure it's a vanilla immediate operand, not a relocation or
1280 // anything else we can't handle.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001281 if (!MI.getOperand(2).isImm())
Tim Northover3b0846e2014-05-24 12:50:23 +00001282 break;
1283 // Watch out for 1 << 12 shifted value.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001284 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
Tim Northover3b0846e2014-05-24 12:50:23 +00001285 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001286
1287 // The update instruction source and destination register must be the
1288 // same as the load/store base register.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001289 if (MI.getOperand(0).getReg() != BaseReg ||
1290 MI.getOperand(1).getReg() != BaseReg)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001291 break;
1292
1293 bool IsPairedInsn = isPairedLdSt(MemMI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001294 int UpdateOffset = MI.getOperand(2).getImm();
Eli Friedman8585e9d2016-08-12 20:28:02 +00001295 if (MI.getOpcode() == AArch64::SUBXri)
1296 UpdateOffset = -UpdateOffset;
1297
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001298 // For non-paired load/store instructions, the immediate must fit in a
1299 // signed 9-bit integer.
1300 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1301 break;
1302
1303 // For paired load/store instructions, the immediate must be a multiple of
1304 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1305 // integer.
1306 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001307 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001308 if (UpdateOffset % Scale != 0)
1309 break;
1310
1311 int ScaledOffset = UpdateOffset / Scale;
Eli Friedman8585e9d2016-08-12 20:28:02 +00001312 if (ScaledOffset > 63 || ScaledOffset < -64)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001313 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001314 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001315
1316 // If we have a non-zero Offset, we check that it matches the amount
1317 // we're adding to the register.
Eli Friedman8585e9d2016-08-12 20:28:02 +00001318 if (!Offset || Offset == UpdateOffset)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001319 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001320 break;
1321 }
1322 return false;
1323}
1324
1325MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001326 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001327 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001328 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001329 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001330
Chad Rosierf77e9092015-08-06 15:50:12 +00001331 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001332 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001333
Chad Rosierb7c5b912015-10-01 13:43:05 +00001334 // Scan forward looking for post-index opportunities. Updating instructions
1335 // can't be formed if the memory instruction doesn't have the offset we're
1336 // looking for.
1337 if (MIUnscaledOffset != UnscaledOffset)
1338 return E;
1339
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001340 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001341 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001342 bool IsPairedInsn = isPairedLdSt(MemMI);
1343 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1344 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1345 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1346 return E;
1347 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001348
Tim Northover3b0846e2014-05-24 12:50:23 +00001349 // Track which registers have been modified and used between the first insn
1350 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001351 ModifiedRegs.reset();
1352 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001353 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001354 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001355 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001356
Geoff Berry4ff2e362016-07-21 15:20:25 +00001357 // Don't count transient instructions towards the search limit since there
1358 // may be different numbers of them if e.g. debug information is present.
1359 if (!MI.isTransient())
1360 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001361
Tim Northover3b0846e2014-05-24 12:50:23 +00001362 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001363 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001364 return MBBI;
1365
1366 // Update the status of what the instruction clobbered and used.
1367 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1368
1369 // Otherwise, if the base register is used or modified, we have no match, so
1370 // return early.
1371 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1372 return E;
1373 }
1374 return E;
1375}
1376
1377MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001378 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001379 MachineBasicBlock::iterator B = I->getParent()->begin();
1380 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001381 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001382 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001383
Chad Rosierf77e9092015-08-06 15:50:12 +00001384 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1385 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001386
1387 // If the load/store is the first instruction in the block, there's obviously
1388 // not any matching update. Ditto if the memory offset isn't zero.
1389 if (MBBI == B || Offset != 0)
1390 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001391 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001392 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393 bool IsPairedInsn = isPairedLdSt(MemMI);
1394 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1395 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1396 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1397 return E;
1398 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001399
1400 // Track which registers have been modified and used between the first insn
1401 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001402 ModifiedRegs.reset();
1403 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001404 unsigned Count = 0;
1405 do {
1406 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001407 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001408
Geoff Berry4ff2e362016-07-21 15:20:25 +00001409 // Don't count transient instructions towards the search limit since there
1410 // may be different numbers of them if e.g. debug information is present.
1411 if (!MI.isTransient())
Geoff Berry173b14d2016-02-09 20:47:21 +00001412 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001413
Tim Northover3b0846e2014-05-24 12:50:23 +00001414 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001415 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001416 return MBBI;
1417
1418 // Update the status of what the instruction clobbered and used.
1419 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1420
1421 // Otherwise, if the base register is used or modified, we have no match, so
1422 // return early.
1423 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1424 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001425 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001426 return E;
1427}
1428
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001429bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1430 MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001431 MachineInstr &MI = *MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001432 // If this is a volatile load, don't mess with it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001433 if (MI.hasOrderedMemoryRef())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001434 return false;
1435
1436 // Make sure this is a reg+imm.
1437 // FIXME: It is possible to extend it to handle reg+reg cases.
1438 if (!getLdStOffsetOp(MI).isImm())
1439 return false;
1440
Chad Rosier35706ad2016-02-04 21:26:02 +00001441 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001442 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001443 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001444 ++NumLoadsFromStoresPromoted;
1445 // Promote the load. Keeping the iterator straight is a
1446 // pain, so we let the merge routine tell us what the next instruction
1447 // is after it's done mucking about.
1448 MBBI = promoteLoadFromStore(MBBI, StoreI);
1449 return true;
1450 }
1451 return false;
1452}
1453
Chad Rosierd6daac42016-11-07 15:27:22 +00001454// Merge adjacent zero stores into a wider store.
1455bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
Chad Rosier24c46ad2016-02-09 18:10:20 +00001456 MachineBasicBlock::iterator &MBBI) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001457 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001458 MachineInstr &MI = *MBBI;
1459 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001460
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001461 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001462 return false;
1463
1464 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001465 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001466 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001467 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001468 if (MergeMI != E) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001469 ++NumZeroStoresPromoted;
1470
Chad Rosier24c46ad2016-02-09 18:10:20 +00001471 // Keeping the iterator straight is a pain, so we let the merge routine tell
1472 // us what the next instruction is after it's done mucking about.
Chad Rosierd6daac42016-11-07 15:27:22 +00001473 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001474 return true;
1475 }
1476 return false;
1477}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001478
Chad Rosier24c46ad2016-02-09 18:10:20 +00001479// Find loads and stores that can be merged into a single load or store pair
1480// instruction.
1481bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001482 MachineInstr &MI = *MBBI;
1483 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001484
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001485 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001486 return false;
1487
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001488 // Early exit if the offset is not possible to match. (6 bits of positive
1489 // range, plus allow an extra one in case we find a later insn that matches
1490 // with Offset-1)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001491 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001492 int Offset = getLdStOffsetOp(MI).getImm();
1493 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
Nirav Dave0f9d1112017-01-04 21:21:46 +00001494 // Allow one more for offset.
1495 if (Offset > 0)
1496 Offset -= OffsetStride;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001497 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1498 return false;
1499
Chad Rosier24c46ad2016-02-09 18:10:20 +00001500 // Look ahead up to LdStLimit instructions for a pairable instruction.
1501 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001502 MachineBasicBlock::iterator Paired =
1503 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001504 if (Paired != E) {
1505 ++NumPairCreated;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001506 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001507 ++NumUnscaledPairCreated;
1508 // Keeping the iterator straight is a pain, so we let the merge routine tell
1509 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001510 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1511 return true;
1512 }
1513 return false;
1514}
1515
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001516bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
Chad Rosierd6daac42016-11-07 15:27:22 +00001517 bool EnableNarrowZeroStOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001518 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001519 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001520 // 1) Find loads that directly read from stores and promote them by
1521 // replacing with mov instructions. If the store is wider than the load,
1522 // the load will be replaced with a bitfield extract.
1523 // e.g.,
1524 // str w1, [x0, #4]
1525 // ldrh w2, [x0, #6]
1526 // ; becomes
1527 // str w1, [x0, #4]
NAKAMURA Takumife1202c2016-06-20 00:37:41 +00001528 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001529 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001530 MBBI != E;) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001531 MachineInstr &MI = *MBBI;
1532 switch (MI.getOpcode()) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001533 default:
1534 // Just move on to the next instruction.
1535 ++MBBI;
1536 break;
1537 // Scaled instructions.
1538 case AArch64::LDRBBui:
1539 case AArch64::LDRHHui:
1540 case AArch64::LDRWui:
1541 case AArch64::LDRXui:
1542 // Unscaled instructions.
1543 case AArch64::LDURBBi:
1544 case AArch64::LDURHHi:
1545 case AArch64::LDURWi:
1546 case AArch64::LDURXi: {
1547 if (tryToPromoteLoadFromStore(MBBI)) {
1548 Modified = true;
1549 break;
1550 }
1551 ++MBBI;
1552 break;
1553 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001554 }
1555 }
Chad Rosierd6daac42016-11-07 15:27:22 +00001556 // 2) Merge adjacent zero stores into a wider store.
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001557 // e.g.,
1558 // strh wzr, [x0]
1559 // strh wzr, [x0, #2]
1560 // ; becomes
1561 // str wzr, [x0]
Chad Rosierd6daac42016-11-07 15:27:22 +00001562 // e.g.,
1563 // str wzr, [x0]
1564 // str wzr, [x0, #4]
1565 // ; becomes
1566 // str xzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001567 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Chad Rosierd6daac42016-11-07 15:27:22 +00001568 EnableNarrowZeroStOpt && MBBI != E;) {
1569 if (isPromotableZeroStoreInst(*MBBI)) {
1570 if (tryToMergeZeroStInst(MBBI)) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001571 Modified = true;
Jun Bum Lim33be4992016-05-06 15:08:57 +00001572 } else
1573 ++MBBI;
1574 } else
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001575 ++MBBI;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001576 }
Jun Bum Lim33be4992016-05-06 15:08:57 +00001577
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001578 // 3) Find loads and stores that can be merged into a single load or store
1579 // pair instruction.
1580 // e.g.,
1581 // ldr x0, [x2]
1582 // ldr x1, [x2, #8]
1583 // ; becomes
1584 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001585 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001586 MBBI != E;) {
Geoff Berry22dfbc52016-08-12 15:26:00 +00001587 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
1588 Modified = true;
1589 else
Tim Northover3b0846e2014-05-24 12:50:23 +00001590 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001591 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001592 // 4) Find base register updates that can be merged into the load or store
1593 // as a base-reg writeback.
1594 // e.g.,
1595 // ldr x0, [x2]
1596 // add x2, x2, #4
1597 // ; becomes
1598 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001599 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1600 MBBI != E;) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001601 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001602 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001603 // switchs, though not strictly necessary.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001604 unsigned Opc = MI.getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001605 switch (Opc) {
1606 default:
1607 // Just move on to the next instruction.
1608 ++MBBI;
1609 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001610 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001611 case AArch64::STRSui:
1612 case AArch64::STRDui:
1613 case AArch64::STRQui:
1614 case AArch64::STRXui:
1615 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001616 case AArch64::STRHHui:
1617 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001618 case AArch64::LDRSui:
1619 case AArch64::LDRDui:
1620 case AArch64::LDRQui:
1621 case AArch64::LDRXui:
1622 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001623 case AArch64::LDRHHui:
1624 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001625 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001626 case AArch64::STURSi:
1627 case AArch64::STURDi:
1628 case AArch64::STURQi:
1629 case AArch64::STURWi:
1630 case AArch64::STURXi:
1631 case AArch64::LDURSi:
1632 case AArch64::LDURDi:
1633 case AArch64::LDURQi:
1634 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001635 case AArch64::LDURXi:
1636 // Paired instructions.
1637 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001638 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001639 case AArch64::LDPDi:
1640 case AArch64::LDPQi:
1641 case AArch64::LDPWi:
1642 case AArch64::LDPXi:
1643 case AArch64::STPSi:
1644 case AArch64::STPDi:
1645 case AArch64::STPQi:
1646 case AArch64::STPWi:
1647 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001648 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001649 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001650 ++MBBI;
1651 break;
1652 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001653 // Look forward to try to form a post-index instruction. For example,
1654 // ldr x0, [x20]
1655 // add x20, x20, #32
1656 // merged into:
1657 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001658 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001659 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001660 if (Update != E) {
1661 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001662 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001663 Modified = true;
1664 ++NumPostFolded;
1665 break;
1666 }
1667 // Don't know how to handle pre/post-index versions, so move to the next
1668 // instruction.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001669 if (TII->isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001670 ++MBBI;
1671 break;
1672 }
1673
1674 // Look back to try to find a pre-index instruction. For example,
1675 // add x0, x0, #8
1676 // ldr x1, [x0]
1677 // merged into:
1678 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001679 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001680 if (Update != E) {
1681 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001682 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001683 Modified = true;
1684 ++NumPreFolded;
1685 break;
1686 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001687 // The immediate in the load/store is scaled by the size of the memory
1688 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001689 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001690 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001691
Tim Northover3b0846e2014-05-24 12:50:23 +00001692 // Look forward to try to find a post-index instruction. For example,
1693 // ldr x1, [x0, #64]
1694 // add x0, x0, #64
1695 // merged into:
1696 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001697 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001698 if (Update != E) {
1699 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001700 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001701 Modified = true;
1702 ++NumPreFolded;
1703 break;
1704 }
1705
1706 // Nothing found. Just move to the next instruction.
1707 ++MBBI;
1708 break;
1709 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001710 }
1711 }
1712
1713 return Modified;
1714}
1715
1716bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00001717 if (skipFunction(*Fn.getFunction()))
1718 return false;
1719
Oliver Stannardd414c992015-11-10 11:04:18 +00001720 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1721 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1722 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001723
Chad Rosierbba881e2016-02-02 15:02:30 +00001724 // Resize the modified and used register bitfield trackers. We do this once
1725 // per function and then clear the bitfield each time we optimize a load or
1726 // store.
1727 ModifiedRegs.resize(TRI->getNumRegs());
1728 UsedRegs.resize(TRI->getNumRegs());
1729
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 bool Modified = false;
Chad Rosier10c7aaa2016-11-11 14:10:12 +00001731 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
Tim Northover3b0846e2014-05-24 12:50:23 +00001732 for (auto &MBB : Fn)
Chad Rosierd6daac42016-11-07 15:27:22 +00001733 Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001734
1735 return Modified;
1736}
1737
Chad Rosier8ade0342016-11-11 19:52:45 +00001738// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
1739// stores near one another? Note: The pre-RA instruction scheduler already has
1740// hooks to try and schedule pairable loads/stores together to improve pairing
1741// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
Tim Northover3b0846e2014-05-24 12:50:23 +00001742
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001743// FIXME: When pairing store instructions it's very possible for this pass to
1744// hoist a store with a KILL marker above another use (without a KILL marker).
1745// The resulting IR is invalid, but nothing uses the KILL markers after this
1746// pass, so it's never caused a problem in practice.
1747
Chad Rosier43f5c842015-08-05 12:40:13 +00001748/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1749/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001750FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1751 return new AArch64LoadStoreOpt();
1752}