blob: 14b9e675176848e956f8d4259978ee2cc71f1e72 [file] [log] [blame]
Eugene Zelenko96d933d2017-07-25 23:51:02 +00001//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
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"
Eugene Zelenko11f69072017-01-25 00:29:26 +000021#include "llvm/ADT/StringRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/iterator_range.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000023#include "llvm/Analysis/AliasAnalysis.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000024#include "llvm/CodeGen/MachineBasicBlock.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000025#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000029#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000030#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000031#include "llvm/IR/DebugLoc.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/Pass.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000038#include <cassert>
39#include <cstdint>
40#include <iterator>
41#include <limits>
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043using namespace llvm;
44
45#define DEBUG_TYPE "aarch64-ldst-opt"
46
Tim Northover3b0846e2014-05-24 12:50:23 +000047STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
48STATISTIC(NumPostFolded, "Number of post-index updates folded");
49STATISTIC(NumPreFolded, "Number of pre-index updates folded");
50STATISTIC(NumUnscaledPairCreated,
51 "Number of load/store from unscaled generated");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000052STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000053STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000054
Chad Rosier35706ad2016-02-04 21:26:02 +000055// The LdStLimit limits how far we search for load/store pairs.
56static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000057 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000058
Chad Rosier35706ad2016-02-04 21:26:02 +000059// The UpdateLimit limits how far we search for update instructions when we form
60// pre-/post-index instructions.
61static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
62 cl::Hidden);
63
Chad Rosier96530b32015-08-05 13:44:51 +000064#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
65
Tim Northover3b0846e2014-05-24 12:50:23 +000066namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000067
Eugene Zelenko96d933d2017-07-25 23:51:02 +000068using LdStPairFlags = struct LdStPairFlags {
Chad Rosier96a18a92015-07-21 17:42:04 +000069 // If a matching instruction is found, MergeForward is set to true if the
70 // merge is to remove the first instruction and replace the second with
71 // a pair-wise insn, and false if the reverse is true.
Eugene Zelenko11f69072017-01-25 00:29:26 +000072 bool MergeForward = false;
Chad Rosier96a18a92015-07-21 17:42:04 +000073
74 // SExtIdx gives the index of the result of the load pair that must be
75 // extended. The value of SExtIdx assumes that the paired load produces the
76 // value in this order: (I, returned iterator), i.e., -1 means no value has
77 // to be extended, 0 means I, and 1 means the returned iterator.
Eugene Zelenko11f69072017-01-25 00:29:26 +000078 int SExtIdx = -1;
Chad Rosier96a18a92015-07-21 17:42:04 +000079
Eugene Zelenko11f69072017-01-25 00:29:26 +000080 LdStPairFlags() = default;
Chad Rosier96a18a92015-07-21 17:42:04 +000081
82 void setMergeForward(bool V = true) { MergeForward = V; }
83 bool getMergeForward() const { return MergeForward; }
84
85 void setSExtIdx(int V) { SExtIdx = V; }
86 int getSExtIdx() const { return SExtIdx; }
Eugene Zelenko96d933d2017-07-25 23:51:02 +000087};
Chad Rosier96a18a92015-07-21 17:42:04 +000088
Tim Northover3b0846e2014-05-24 12:50:23 +000089struct AArch64LoadStoreOpt : public MachineFunctionPass {
90 static char ID;
Eugene Zelenko11f69072017-01-25 00:29:26 +000091
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000092 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000093 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
94 }
Tim Northover3b0846e2014-05-24 12:50:23 +000095
Chad Rosiera69dcb62017-03-17 14:19:55 +000096 AliasAnalysis *AA;
Tim Northover3b0846e2014-05-24 12:50:23 +000097 const AArch64InstrInfo *TII;
98 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000099 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +0000100
Jun Bum Lim47aece12018-04-27 18:44:37 +0000101 // Track which register units have been modified and used.
102 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
Chad Rosierbba881e2016-02-02 15:02:30 +0000103
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000104 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiera69dcb62017-03-17 14:19:55 +0000105 AU.addRequired<AAResultsWrapperPass>();
106 MachineFunctionPass::getAnalysisUsage(AU);
107 }
108
Tim Northover3b0846e2014-05-24 12:50:23 +0000109 // Scan the instructions looking for a load/store that can be combined
110 // with the current instruction into a load/store pair.
111 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000112 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000113 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +0000114 unsigned Limit,
115 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000116
117 // Scan the instructions looking for a store that writes to the address from
118 // which the current load instruction reads. Return true if one is found.
119 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
120 MachineBasicBlock::iterator &StoreI);
121
Chad Rosierd6daac42016-11-07 15:27:22 +0000122 // Merge the two instructions indicated into a wider narrow store instruction.
Chad Rosierb5933d72016-02-09 19:02:12 +0000123 MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000124 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
125 MachineBasicBlock::iterator MergeMI,
126 const LdStPairFlags &Flags);
Chad Rosierb5933d72016-02-09 19:02:12 +0000127
Tim Northover3b0846e2014-05-24 12:50:23 +0000128 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000129 MachineBasicBlock::iterator
130 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000131 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000132 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000133
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000134 // Promote the load that reads directly from the address stored to.
135 MachineBasicBlock::iterator
136 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
137 MachineBasicBlock::iterator StoreI);
138
Tim Northover3b0846e2014-05-24 12:50:23 +0000139 // Scan the instruction list to find a base register update that can
140 // be combined with the current instruction (a load or store) using
141 // pre or post indexed addressing with writeback. Scan forwards.
142 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000143 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000144 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000145
146 // Scan the instruction list to find a base register update that can
147 // be combined with the current instruction (a load or store) using
148 // pre or post indexed addressing with writeback. Scan backwards.
149 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000150 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000152 // Find an instruction that updates the base register of the ld/st
153 // instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000154 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000155 unsigned BaseReg, int Offset);
156
Chad Rosier2dfd3542015-09-23 13:51:44 +0000157 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000159 mergeUpdateInsn(MachineBasicBlock::iterator I,
160 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000161
Chad Rosierd6daac42016-11-07 15:27:22 +0000162 // Find and merge zero store instructions.
163 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000164
Chad Rosier24c46ad2016-02-09 18:10:20 +0000165 // Find and pair ldr/str instructions.
166 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
167
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000168 // Find and promote load instructions which read directly from store.
169 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
170
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000171 // Find and merge a base register updates before or after a ld/st instruction.
172 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
173
Chad Rosierd6daac42016-11-07 15:27:22 +0000174 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000175
176 bool runOnMachineFunction(MachineFunction &Fn) override;
177
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000178 MachineFunctionProperties getRequiredProperties() const override {
179 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000180 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000181 }
182
Mehdi Amini117296c2016-10-01 02:56:57 +0000183 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000184};
Eugene Zelenko11f69072017-01-25 00:29:26 +0000185
Tim Northover3b0846e2014-05-24 12:50:23 +0000186char AArch64LoadStoreOpt::ID = 0;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000187
188} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000189
Chad Rosier96530b32015-08-05 13:44:51 +0000190INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
191 AARCH64_LOAD_STORE_OPT_NAME, false, false)
192
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000193static bool isNarrowStore(unsigned Opc) {
194 switch (Opc) {
195 default:
196 return false;
197 case AArch64::STRBBui:
198 case AArch64::STURBBi:
199 case AArch64::STRHHui:
200 case AArch64::STURHHi:
201 return true;
202 }
203}
204
Chad Rosier32d4d372015-09-29 16:07:32 +0000205// Scaling factor for unscaled load or store.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000206static int getMemScale(MachineInstr &MI) {
207 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000208 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000209 llvm_unreachable("Opcode has unknown scale!");
210 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000211 case AArch64::LDURBBi:
212 case AArch64::LDRSBWui:
213 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000214 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000215 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000216 return 1;
217 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000218 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000219 case AArch64::LDRSHWui:
220 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000221 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000222 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000223 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000224 case AArch64::LDRSui:
225 case AArch64::LDURSi:
226 case AArch64::LDRSWui:
227 case AArch64::LDURSWi:
228 case AArch64::LDRWui:
229 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000230 case AArch64::STRSui:
231 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000232 case AArch64::STRWui:
233 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000234 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000235 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000236 case AArch64::LDPWi:
237 case AArch64::STPSi:
238 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000239 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000240 case AArch64::LDRDui:
241 case AArch64::LDURDi:
242 case AArch64::LDRXui:
243 case AArch64::LDURXi:
244 case AArch64::STRDui:
245 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000246 case AArch64::STRXui:
247 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000248 case AArch64::LDPDi:
249 case AArch64::LDPXi:
250 case AArch64::STPDi:
251 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000252 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000253 case AArch64::LDRQui:
254 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000255 case AArch64::STRQui:
256 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000257 case AArch64::LDPQi:
258 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000259 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000260 }
261}
262
Quentin Colombet66b61632015-03-06 22:42:10 +0000263static unsigned getMatchingNonSExtOpcode(unsigned Opc,
264 bool *IsValidLdStrOpc = nullptr) {
265 if (IsValidLdStrOpc)
266 *IsValidLdStrOpc = true;
267 switch (Opc) {
268 default:
269 if (IsValidLdStrOpc)
270 *IsValidLdStrOpc = false;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000271 return std::numeric_limits<unsigned>::max();
Quentin Colombet66b61632015-03-06 22:42:10 +0000272 case AArch64::STRDui:
273 case AArch64::STURDi:
274 case AArch64::STRQui:
275 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000276 case AArch64::STRBBui:
277 case AArch64::STURBBi:
278 case AArch64::STRHHui:
279 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000280 case AArch64::STRWui:
281 case AArch64::STURWi:
282 case AArch64::STRXui:
283 case AArch64::STURXi:
284 case AArch64::LDRDui:
285 case AArch64::LDURDi:
286 case AArch64::LDRQui:
287 case AArch64::LDURQi:
288 case AArch64::LDRWui:
289 case AArch64::LDURWi:
290 case AArch64::LDRXui:
291 case AArch64::LDURXi:
292 case AArch64::STRSui:
293 case AArch64::STURSi:
294 case AArch64::LDRSui:
295 case AArch64::LDURSi:
296 return Opc;
297 case AArch64::LDRSWui:
298 return AArch64::LDRWui;
299 case AArch64::LDURSWi:
300 return AArch64::LDURWi;
301 }
302}
303
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000304static unsigned getMatchingWideOpcode(unsigned Opc) {
305 switch (Opc) {
306 default:
307 llvm_unreachable("Opcode has no wide equivalent!");
308 case AArch64::STRBBui:
309 return AArch64::STRHHui;
310 case AArch64::STRHHui:
311 return AArch64::STRWui;
312 case AArch64::STURBBi:
313 return AArch64::STURHHi;
314 case AArch64::STURHHi:
315 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000316 case AArch64::STURWi:
317 return AArch64::STURXi;
318 case AArch64::STRWui:
319 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000320 }
321}
322
Tim Northover3b0846e2014-05-24 12:50:23 +0000323static unsigned getMatchingPairOpcode(unsigned Opc) {
324 switch (Opc) {
325 default:
326 llvm_unreachable("Opcode has no pairwise equivalent!");
327 case AArch64::STRSui:
328 case AArch64::STURSi:
329 return AArch64::STPSi;
330 case AArch64::STRDui:
331 case AArch64::STURDi:
332 return AArch64::STPDi;
333 case AArch64::STRQui:
334 case AArch64::STURQi:
335 return AArch64::STPQi;
336 case AArch64::STRWui:
337 case AArch64::STURWi:
338 return AArch64::STPWi;
339 case AArch64::STRXui:
340 case AArch64::STURXi:
341 return AArch64::STPXi;
342 case AArch64::LDRSui:
343 case AArch64::LDURSi:
344 return AArch64::LDPSi;
345 case AArch64::LDRDui:
346 case AArch64::LDURDi:
347 return AArch64::LDPDi;
348 case AArch64::LDRQui:
349 case AArch64::LDURQi:
350 return AArch64::LDPQi;
351 case AArch64::LDRWui:
352 case AArch64::LDURWi:
353 return AArch64::LDPWi;
354 case AArch64::LDRXui:
355 case AArch64::LDURXi:
356 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000357 case AArch64::LDRSWui:
358 case AArch64::LDURSWi:
359 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000360 }
361}
362
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000363static unsigned isMatchingStore(MachineInstr &LoadInst,
364 MachineInstr &StoreInst) {
365 unsigned LdOpc = LoadInst.getOpcode();
366 unsigned StOpc = StoreInst.getOpcode();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000367 switch (LdOpc) {
368 default:
369 llvm_unreachable("Unsupported load instruction!");
370 case AArch64::LDRBBui:
371 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
372 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
373 case AArch64::LDURBBi:
374 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
375 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
376 case AArch64::LDRHHui:
377 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
378 StOpc == AArch64::STRXui;
379 case AArch64::LDURHHi:
380 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
381 StOpc == AArch64::STURXi;
382 case AArch64::LDRWui:
383 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
384 case AArch64::LDURWi:
385 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
386 case AArch64::LDRXui:
387 return StOpc == AArch64::STRXui;
388 case AArch64::LDURXi:
389 return StOpc == AArch64::STURXi;
390 }
391}
392
Tim Northover3b0846e2014-05-24 12:50:23 +0000393static unsigned getPreIndexedOpcode(unsigned Opc) {
Chad Rosier14fc82a2017-08-04 16:44:06 +0000394 // FIXME: We don't currently support creating pre-indexed loads/stores when
395 // the load or store is the unscaled version. If we decide to perform such an
396 // optimization in the future the cases for the unscaled loads/stores will
397 // need to be added here.
Tim Northover3b0846e2014-05-24 12:50:23 +0000398 switch (Opc) {
399 default:
400 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000401 case AArch64::STRSui:
402 return AArch64::STRSpre;
403 case AArch64::STRDui:
404 return AArch64::STRDpre;
405 case AArch64::STRQui:
406 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000407 case AArch64::STRBBui:
408 return AArch64::STRBBpre;
409 case AArch64::STRHHui:
410 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000411 case AArch64::STRWui:
412 return AArch64::STRWpre;
413 case AArch64::STRXui:
414 return AArch64::STRXpre;
415 case AArch64::LDRSui:
416 return AArch64::LDRSpre;
417 case AArch64::LDRDui:
418 return AArch64::LDRDpre;
419 case AArch64::LDRQui:
420 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000421 case AArch64::LDRBBui:
422 return AArch64::LDRBBpre;
423 case AArch64::LDRHHui:
424 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000425 case AArch64::LDRWui:
426 return AArch64::LDRWpre;
427 case AArch64::LDRXui:
428 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000429 case AArch64::LDRSWui:
430 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000431 case AArch64::LDPSi:
432 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000433 case AArch64::LDPSWi:
434 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000435 case AArch64::LDPDi:
436 return AArch64::LDPDpre;
437 case AArch64::LDPQi:
438 return AArch64::LDPQpre;
439 case AArch64::LDPWi:
440 return AArch64::LDPWpre;
441 case AArch64::LDPXi:
442 return AArch64::LDPXpre;
443 case AArch64::STPSi:
444 return AArch64::STPSpre;
445 case AArch64::STPDi:
446 return AArch64::STPDpre;
447 case AArch64::STPQi:
448 return AArch64::STPQpre;
449 case AArch64::STPWi:
450 return AArch64::STPWpre;
451 case AArch64::STPXi:
452 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 }
454}
455
456static unsigned getPostIndexedOpcode(unsigned Opc) {
457 switch (Opc) {
458 default:
459 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
460 case AArch64::STRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000461 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000462 return AArch64::STRSpost;
463 case AArch64::STRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000464 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000465 return AArch64::STRDpost;
466 case AArch64::STRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000467 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000468 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000469 case AArch64::STRBBui:
470 return AArch64::STRBBpost;
471 case AArch64::STRHHui:
472 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000473 case AArch64::STRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000474 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000475 return AArch64::STRWpost;
476 case AArch64::STRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000477 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000478 return AArch64::STRXpost;
479 case AArch64::LDRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000480 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000481 return AArch64::LDRSpost;
482 case AArch64::LDRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000483 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000484 return AArch64::LDRDpost;
485 case AArch64::LDRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000486 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000487 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000488 case AArch64::LDRBBui:
489 return AArch64::LDRBBpost;
490 case AArch64::LDRHHui:
491 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000492 case AArch64::LDRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000493 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000494 return AArch64::LDRWpost;
495 case AArch64::LDRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000496 case AArch64::LDURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000497 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000498 case AArch64::LDRSWui:
499 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000500 case AArch64::LDPSi:
501 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000502 case AArch64::LDPSWi:
503 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000504 case AArch64::LDPDi:
505 return AArch64::LDPDpost;
506 case AArch64::LDPQi:
507 return AArch64::LDPQpost;
508 case AArch64::LDPWi:
509 return AArch64::LDPWpost;
510 case AArch64::LDPXi:
511 return AArch64::LDPXpost;
512 case AArch64::STPSi:
513 return AArch64::STPSpost;
514 case AArch64::STPDi:
515 return AArch64::STPDpost;
516 case AArch64::STPQi:
517 return AArch64::STPQpost;
518 case AArch64::STPWi:
519 return AArch64::STPWpost;
520 case AArch64::STPXi:
521 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 }
523}
524
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000525static bool isPairedLdSt(const MachineInstr &MI) {
526 switch (MI.getOpcode()) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000527 default:
528 return false;
529 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000530 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000531 case AArch64::LDPDi:
532 case AArch64::LDPQi:
533 case AArch64::LDPWi:
534 case AArch64::LDPXi:
535 case AArch64::STPSi:
536 case AArch64::STPDi:
537 case AArch64::STPQi:
538 case AArch64::STPWi:
539 case AArch64::STPXi:
540 return true;
541 }
542}
543
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000544static const MachineOperand &getLdStRegOp(const MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000545 unsigned PairedRegOp = 0) {
546 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
547 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000548 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000549}
550
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000551static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000552 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000553 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000554}
555
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000556static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000557 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000558 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000559}
560
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000561static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
562 MachineInstr &StoreInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000563 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000564 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
565 int LoadSize = getMemScale(LoadInst);
566 int StoreSize = getMemScale(StoreInst);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000567 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000568 ? getLdStOffsetOp(StoreInst).getImm()
569 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000570 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000571 ? getLdStOffsetOp(LoadInst).getImm()
572 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
573 return (UnscaledStOffset <= UnscaledLdOffset) &&
574 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
575}
576
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000577static bool isPromotableZeroStoreInst(MachineInstr &MI) {
Chad Rosierd6daac42016-11-07 15:27:22 +0000578 unsigned Opc = MI.getOpcode();
579 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
580 isNarrowStore(Opc)) &&
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000581 getLdStRegOp(MI).getReg() == AArch64::WZR;
582}
583
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000584static bool isPromotableLoadFromStore(MachineInstr &MI) {
585 switch (MI.getOpcode()) {
586 default:
587 return false;
588 // Scaled instructions.
589 case AArch64::LDRBBui:
590 case AArch64::LDRHHui:
591 case AArch64::LDRWui:
592 case AArch64::LDRXui:
593 // Unscaled instructions.
594 case AArch64::LDURBBi:
595 case AArch64::LDURHHi:
596 case AArch64::LDURWi:
597 case AArch64::LDURXi:
598 return true;
599 }
600}
601
602static bool isMergeableLdStUpdate(MachineInstr &MI) {
603 unsigned Opc = MI.getOpcode();
604 switch (Opc) {
605 default:
606 return false;
607 // Scaled instructions.
608 case AArch64::STRSui:
609 case AArch64::STRDui:
610 case AArch64::STRQui:
611 case AArch64::STRXui:
612 case AArch64::STRWui:
613 case AArch64::STRHHui:
614 case AArch64::STRBBui:
615 case AArch64::LDRSui:
616 case AArch64::LDRDui:
617 case AArch64::LDRQui:
618 case AArch64::LDRXui:
619 case AArch64::LDRWui:
620 case AArch64::LDRHHui:
621 case AArch64::LDRBBui:
622 // Unscaled instructions.
623 case AArch64::STURSi:
624 case AArch64::STURDi:
625 case AArch64::STURQi:
626 case AArch64::STURWi:
627 case AArch64::STURXi:
628 case AArch64::LDURSi:
629 case AArch64::LDURDi:
630 case AArch64::LDURQi:
631 case AArch64::LDURWi:
632 case AArch64::LDURXi:
633 // Paired instructions.
634 case AArch64::LDPSi:
635 case AArch64::LDPSWi:
636 case AArch64::LDPDi:
637 case AArch64::LDPQi:
638 case AArch64::LDPWi:
639 case AArch64::LDPXi:
640 case AArch64::STPSi:
641 case AArch64::STPDi:
642 case AArch64::STPQi:
643 case AArch64::STPWi:
644 case AArch64::STPXi:
645 // Make sure this is a reg+imm (as opposed to an address reloc).
646 if (!getLdStOffsetOp(MI).isImm())
647 return false;
648
649 return true;
650 }
651}
652
Tim Northover3b0846e2014-05-24 12:50:23 +0000653MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000654AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
655 MachineBasicBlock::iterator MergeMI,
656 const LdStPairFlags &Flags) {
657 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
658 "Expected promotable zero stores.");
659
Tim Northover3b0846e2014-05-24 12:50:23 +0000660 MachineBasicBlock::iterator NextI = I;
661 ++NextI;
662 // If NextI is the second of the two instructions to be merged, we need
663 // to skip one further. Either way we merge will invalidate the iterator,
664 // and we don't need to scan the new instruction, as it's a pairwise
665 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000666 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000667 ++NextI;
668
Chad Rosierb5933d72016-02-09 19:02:12 +0000669 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000670 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000671 int OffsetStride = IsScaled ? 1 : getMemScale(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000672
Chad Rosier96a18a92015-07-21 17:42:04 +0000673 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000675 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000676 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000677 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000678 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000679 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000680 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000681
682 // Which register is Rt and which is Rt2 depends on the offset order.
Davide Italiano5df60662016-11-07 19:11:25 +0000683 MachineInstr *RtMI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000684 if (getLdStOffsetOp(*I).getImm() ==
Davide Italiano5df60662016-11-07 19:11:25 +0000685 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000686 RtMI = &*MergeMI;
Davide Italiano5df60662016-11-07 19:11:25 +0000687 else
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000688 RtMI = &*I;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000689
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000690 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000691 // Change the scaled offset from small to large type.
692 if (IsScaled) {
693 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
694 OffsetImm /= 2;
695 }
696
Chad Rosierd6daac42016-11-07 15:27:22 +0000697 // Construct the new instruction.
Chad Rosierc46ef882016-02-09 19:33:42 +0000698 DebugLoc DL = I->getDebugLoc();
699 MachineBasicBlock *MBB = I->getParent();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000700 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000701 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000702 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Diana Picus116bbab2017-01-13 09:58:52 +0000703 .add(BaseRegOp)
Chad Rosierb5933d72016-02-09 19:02:12 +0000704 .addImm(OffsetImm)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000705 .setMemRefs(I->mergeMemRefsWith(*MergeMI))
706 .setMIFlags(I->mergeFlagsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000707 (void)MIB;
708
Chad Rosierd6daac42016-11-07 15:27:22 +0000709 DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
Chad Rosierb5933d72016-02-09 19:02:12 +0000710 DEBUG(I->print(dbgs()));
711 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000712 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000713 DEBUG(dbgs() << " with instruction:\n ");
714 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
715 DEBUG(dbgs() << "\n");
716
717 // Erase the old instructions.
718 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000719 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000720 return NextI;
721}
722
723MachineBasicBlock::iterator
724AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
725 MachineBasicBlock::iterator Paired,
726 const LdStPairFlags &Flags) {
727 MachineBasicBlock::iterator NextI = I;
728 ++NextI;
729 // If NextI is the second of the two instructions to be merged, we need
730 // to skip one further. Either way we merge will invalidate the iterator,
731 // and we don't need to scan the new instruction, as it's a pairwise
732 // instruction, which we're not considering for further action anyway.
733 if (NextI == Paired)
734 ++NextI;
735
736 int SExtIdx = Flags.getSExtIdx();
737 unsigned Opc =
738 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000739 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000740 int OffsetStride = IsUnscaled ? getMemScale(*I) : 1;
Chad Rosierb5933d72016-02-09 19:02:12 +0000741
742 bool MergeForward = Flags.getMergeForward();
743 // Insert our new paired instruction after whichever of the paired
744 // instructions MergeForward indicates.
745 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
746 // Also based on MergeForward is from where we copy the base register operand
747 // so we get the flags compatible with the input code.
748 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000749 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
Chad Rosierb5933d72016-02-09 19:02:12 +0000750
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000751 int Offset = getLdStOffsetOp(*I).getImm();
752 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000753 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000754 if (IsUnscaled != PairedIsUnscaled) {
755 // We're trying to pair instructions that differ in how they are scaled. If
756 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
757 // the opposite (i.e., make Paired's offset unscaled).
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000758 int MemSize = getMemScale(*Paired);
Chad Rosier00f9d232016-02-11 14:25:08 +0000759 if (PairedIsUnscaled) {
760 // If the unscaled offset isn't a multiple of the MemSize, we can't
761 // pair the operations together.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000762 assert(!(PairedOffset % getMemScale(*Paired)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000763 "Offset should be a multiple of the stride!");
764 PairedOffset /= MemSize;
765 } else {
766 PairedOffset *= MemSize;
767 }
768 }
769
Chad Rosierb5933d72016-02-09 19:02:12 +0000770 // Which register is Rt and which is Rt2 depends on the offset order.
771 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000772 if (Offset == PairedOffset + OffsetStride) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000773 RtMI = &*Paired;
774 Rt2MI = &*I;
Chad Rosierb5933d72016-02-09 19:02:12 +0000775 // Here we swapped the assumption made for SExtIdx.
776 // I.e., we turn ldp I, Paired into ldp Paired, I.
777 // Update the index accordingly.
778 if (SExtIdx != -1)
779 SExtIdx = (SExtIdx + 1) % 2;
780 } else {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000781 RtMI = &*I;
782 Rt2MI = &*Paired;
Chad Rosierb5933d72016-02-09 19:02:12 +0000783 }
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000784 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000785 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000786 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000787 assert(!(OffsetImm % getMemScale(*RtMI)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000788 "Unscaled offset cannot be scaled.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000789 OffsetImm /= getMemScale(*RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000790 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000791
792 // Construct the new instruction.
793 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000794 DebugLoc DL = I->getDebugLoc();
795 MachineBasicBlock *MBB = I->getParent();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000796 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
797 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
798 // Kill flags may become invalid when moving stores for pairing.
799 if (RegOp0.isUse()) {
800 if (!MergeForward) {
801 // Clear kill flags on store if moving upwards. Example:
802 // STRWui %w0, ...
803 // USE %w1
804 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
805 RegOp0.setIsKill(false);
806 RegOp1.setIsKill(false);
807 } else {
808 // Clear kill flags of the first stores register. Example:
809 // STRWui %w1, ...
810 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
811 // STRW %w0
812 unsigned Reg = getLdStRegOp(*I).getReg();
813 for (MachineInstr &MI : make_range(std::next(I), Paired))
814 MI.clearRegisterKills(Reg, TRI);
815 }
816 }
Chad Rosierc46ef882016-02-09 19:33:42 +0000817 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000818 .add(RegOp0)
819 .add(RegOp1)
Diana Picus116bbab2017-01-13 09:58:52 +0000820 .add(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000821 .addImm(OffsetImm)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000822 .setMemRefs(I->mergeMemRefsWith(*Paired))
823 .setMIFlags(I->mergeFlagsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000824
825 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000826
827 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
828 DEBUG(I->print(dbgs()));
829 DEBUG(dbgs() << " ");
830 DEBUG(Paired->print(dbgs()));
831 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000832 if (SExtIdx != -1) {
833 // Generate the sign extension for the proper result of the ldp.
834 // I.e., with X1, that would be:
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000835 // %w1 = KILL %w1, implicit-def %x1
836 // %x1 = SBFMXri killed %x1, 0, 31
Quentin Colombet66b61632015-03-06 22:42:10 +0000837 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
838 // Right now, DstMO has the extended register, since it comes from an
839 // extended opcode.
840 unsigned DstRegX = DstMO.getReg();
841 // Get the W variant of that register.
842 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
843 // Update the result of LDP to use the W instead of the X variant.
844 DstMO.setReg(DstRegW);
845 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
846 DEBUG(dbgs() << "\n");
847 // Make the machine verifier happy by providing a definition for
848 // the X register.
849 // Insert this definition right after the generated LDP, i.e., before
850 // InsertionPoint.
851 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000852 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000853 .addReg(DstRegW)
854 .addReg(DstRegX, RegState::Define);
855 MIBKill->getOperand(2).setImplicit();
856 // Create the sign extension.
857 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000858 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000859 .addReg(DstRegX)
860 .addImm(0)
861 .addImm(31);
862 (void)MIBSXTW;
863 DEBUG(dbgs() << " Extend operand:\n ");
864 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000865 } else {
866 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000867 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000868 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000869
870 // Erase the old instructions.
871 I->eraseFromParent();
872 Paired->eraseFromParent();
873
874 return NextI;
875}
876
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000877MachineBasicBlock::iterator
878AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
879 MachineBasicBlock::iterator StoreI) {
880 MachineBasicBlock::iterator NextI = LoadI;
881 ++NextI;
882
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000883 int LoadSize = getMemScale(*LoadI);
884 int StoreSize = getMemScale(*StoreI);
885 unsigned LdRt = getLdStRegOp(*LoadI).getReg();
Florian Hahn80e48512017-06-21 08:47:23 +0000886 const MachineOperand &StMO = getLdStRegOp(*StoreI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000887 unsigned StRt = getLdStRegOp(*StoreI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000888 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
889
890 assert((IsStoreXReg ||
891 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
892 "Unexpected RegClass");
893
894 MachineInstr *BitExtMI;
895 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
896 // Remove the load, if the destination register of the loads is the same
897 // register for stored value.
898 if (StRt == LdRt && LoadSize == 8) {
Tim Northover9ac3e422017-06-26 18:49:25 +0000899 for (MachineInstr &MI : make_range(StoreI->getIterator(),
900 LoadI->getIterator())) {
901 if (MI.killsRegister(StRt, TRI)) {
902 MI.clearRegisterKills(StRt, TRI);
903 break;
904 }
905 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000906 DEBUG(dbgs() << "Remove load instruction:\n ");
907 DEBUG(LoadI->print(dbgs()));
908 DEBUG(dbgs() << "\n");
909 LoadI->eraseFromParent();
910 return NextI;
911 }
912 // Replace the load with a mov if the load and store are in the same size.
913 BitExtMI =
914 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
915 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
916 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
Florian Hahn80e48512017-06-21 08:47:23 +0000917 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000918 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
919 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000920 } else {
921 // FIXME: Currently we disable this transformation in big-endian targets as
922 // performance and correctness are verified only in little-endian.
923 if (!Subtarget->isLittleEndian())
924 return NextI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000925 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
926 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000927 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000928 assert(LoadSize <= StoreSize && "Invalid load size");
929 int UnscaledLdOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000930 ? getLdStOffsetOp(*LoadI).getImm()
931 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000932 int UnscaledStOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000933 ? getLdStOffsetOp(*StoreI).getImm()
934 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000935 int Width = LoadSize * 8;
936 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
937 int Imms = Immr + Width - 1;
938 unsigned DestReg = IsStoreXReg
939 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
940 &AArch64::GPR64RegClass)
941 : LdRt;
942
943 assert((UnscaledLdOffset >= UnscaledStOffset &&
944 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
945 "Invalid offset");
946
947 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
948 Imms = Immr + Width - 1;
949 if (UnscaledLdOffset == UnscaledStOffset) {
950 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
951 | ((Immr) << 6) // immr
952 | ((Imms) << 0) // imms
953 ;
954
955 BitExtMI =
956 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
957 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
958 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +0000959 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000960 .addImm(AndMaskEncoded)
961 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000962 } else {
963 BitExtMI =
964 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
965 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
966 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +0000967 .add(StMO)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000968 .addImm(Immr)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000969 .addImm(Imms)
970 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000971 }
972 }
Matthias Braun76bb4132016-12-16 23:55:43 +0000973
Matthias Braund9a59a82017-02-17 23:15:03 +0000974 // Clear kill flags between store and load.
975 for (MachineInstr &MI : make_range(StoreI->getIterator(),
976 BitExtMI->getIterator()))
Florian Hahn8552e592017-06-21 09:51:52 +0000977 if (MI.killsRegister(StRt, TRI)) {
978 MI.clearRegisterKills(StRt, TRI);
979 break;
980 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000981
982 DEBUG(dbgs() << "Promoting load by replacing :\n ");
983 DEBUG(StoreI->print(dbgs()));
984 DEBUG(dbgs() << " ");
985 DEBUG(LoadI->print(dbgs()));
986 DEBUG(dbgs() << " with instructions:\n ");
987 DEBUG(StoreI->print(dbgs()));
988 DEBUG(dbgs() << " ");
989 DEBUG((BitExtMI)->print(dbgs()));
990 DEBUG(dbgs() << "\n");
991
992 // Erase the old instructions.
993 LoadI->eraseFromParent();
994 return NextI;
995}
996
Tim Northover3b0846e2014-05-24 12:50:23 +0000997static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +0000998 // Convert the byte-offset used by unscaled into an "element" offset used
999 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001000 if (IsUnscaled) {
1001 // If the byte-offset isn't a multiple of the stride, there's no point
1002 // trying to match it.
1003 if (Offset % OffsetStride)
1004 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001005 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001006 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001007 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001008}
1009
1010// Do alignment, specialized to power of 2 and for signed ints,
1011// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001012// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001013// FIXME: Move this function to include/MathExtras.h?
1014static int alignTo(int Num, int PowOf2) {
1015 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1016}
1017
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001018static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001019 AliasAnalysis *AA) {
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001020 // One of the instructions must modify memory.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001021 if (!MIa.mayStore() && !MIb.mayStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001022 return false;
1023
1024 // Both instructions must be memory operations.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001025 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001026 return false;
1027
Chad Rosiera69dcb62017-03-17 14:19:55 +00001028 return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001029}
1030
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001031static bool mayAlias(MachineInstr &MIa,
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001032 SmallVectorImpl<MachineInstr *> &MemInsns,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001033 AliasAnalysis *AA) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001034 for (MachineInstr *MIb : MemInsns)
Chad Rosiera69dcb62017-03-17 14:19:55 +00001035 if (mayAlias(MIa, *MIb, AA))
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001036 return true;
1037
1038 return false;
1039}
1040
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001041bool AArch64LoadStoreOpt::findMatchingStore(
1042 MachineBasicBlock::iterator I, unsigned Limit,
1043 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001044 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001045 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001046 MachineInstr &LoadMI = *I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001047 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001048
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001049 // If the load is the first instruction in the block, there's obviously
1050 // not any matching store.
1051 if (MBBI == B)
1052 return false;
1053
Jun Bum Lim47aece12018-04-27 18:44:37 +00001054 // Track which register units have been modified and used between the first
1055 // insn and the second insn.
1056 ModifiedRegUnits.clear();
1057 UsedRegUnits.clear();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001058
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001059 unsigned Count = 0;
1060 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001061 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001062 MachineInstr &MI = *MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001063
Geoff Berry4ff2e362016-07-21 15:20:25 +00001064 // Don't count transient instructions towards the search limit since there
1065 // may be different numbers of them if e.g. debug information is present.
1066 if (!MI.isTransient())
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001067 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001068
1069 // If the load instruction reads directly from the address to which the
1070 // store instruction writes and the stored value is not modified, we can
1071 // promote the load. Since we do not handle stores with pre-/post-index,
1072 // it's unnecessary to check if BaseReg is modified by the store itself.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001073 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001074 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001075 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001076 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001077 StoreI = MBBI;
1078 return true;
1079 }
1080
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001081 if (MI.isCall())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001082 return false;
1083
Jun Bum Lim47aece12018-04-27 18:44:37 +00001084 // Update modified / uses register units.
1085 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001086
1087 // Otherwise, if the base register is modified, we have no match, so
1088 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001089 if (!ModifiedRegUnits.available(BaseReg))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001090 return false;
1091
1092 // If we encounter a store aliased with the load, return early.
Chad Rosiera69dcb62017-03-17 14:19:55 +00001093 if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001094 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001095 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001096 return false;
1097}
1098
Chad Rosierc5083c22016-06-10 20:47:14 +00001099// Returns true if FirstMI and MI are candidates for merging or pairing.
1100// Otherwise, returns false.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001101static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
Chad Rosierc5083c22016-06-10 20:47:14 +00001102 LdStPairFlags &Flags,
1103 const AArch64InstrInfo *TII) {
1104 // If this is volatile or if pairing is suppressed, not a candidate.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001105 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
Chad Rosierc5083c22016-06-10 20:47:14 +00001106 return false;
1107
1108 // We should have already checked FirstMI for pair suppression and volatility.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001109 assert(!FirstMI.hasOrderedMemoryRef() &&
1110 !TII->isLdStPairSuppressed(FirstMI) &&
Chad Rosierc5083c22016-06-10 20:47:14 +00001111 "FirstMI shouldn't get here if either of these checks are true.");
1112
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001113 unsigned OpcA = FirstMI.getOpcode();
1114 unsigned OpcB = MI.getOpcode();
Chad Rosierc5083c22016-06-10 20:47:14 +00001115
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001116 // Opcodes match: nothing more to check.
1117 if (OpcA == OpcB)
1118 return true;
1119
1120 // Try to match a sign-extended load/store with a zero-extended load/store.
1121 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1122 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1123 assert(IsValidLdStrOpc &&
1124 "Given Opc should be a Load or Store with an immediate");
1125 // OpcA will be the first instruction in the pair.
1126 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1127 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1128 return true;
1129 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001130
Chad Rosierd6daac42016-11-07 15:27:22 +00001131 // If the second instruction isn't even a mergable/pairable load/store, bail
1132 // out.
Chad Rosier00f9d232016-02-11 14:25:08 +00001133 if (!PairIsValidLdStrOpc)
1134 return false;
1135
Chad Rosierd6daac42016-11-07 15:27:22 +00001136 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1137 // offsets.
1138 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
Chad Rosier00f9d232016-02-11 14:25:08 +00001139 return false;
1140
1141 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001142 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001143 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1144
1145 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001146}
1147
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001148/// Scan the instructions looking for a load/store that can be combined with the
1149/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001150MachineBasicBlock::iterator
1151AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001152 LdStPairFlags &Flags, unsigned Limit,
1153 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001154 MachineBasicBlock::iterator E = I->getParent()->end();
1155 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001156 MachineInstr &FirstMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001157 ++MBBI;
1158
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001159 bool MayLoad = FirstMI.mayLoad();
1160 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001161 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1162 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1163 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001164 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001165 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001166
Jun Bum Lim47aece12018-04-27 18:44:37 +00001167 // Track which register units have been modified and used between the first
1168 // insn (inclusive) and the second insn.
1169 ModifiedRegUnits.clear();
1170 UsedRegUnits.clear();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001171
1172 // Remember any instructions that read/write memory between FirstMI and MI.
1173 SmallVector<MachineInstr *, 4> MemInsns;
1174
Tim Northover3b0846e2014-05-24 12:50:23 +00001175 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001176 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001177
Geoff Berry4ff2e362016-07-21 15:20:25 +00001178 // Don't count transient instructions towards the search limit since there
1179 // may be different numbers of them if e.g. debug information is present.
1180 if (!MI.isTransient())
1181 ++Count;
Tim Northover3b0846e2014-05-24 12:50:23 +00001182
Chad Rosier18896c02016-02-04 16:01:40 +00001183 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001184 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001185 getLdStOffsetOp(MI).isImm()) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001186 assert(MI.mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001187 // If we've found another instruction with the same opcode, check to see
1188 // if the base and offset are compatible with our starting instruction.
1189 // These instructions all have scaled immediate operands, so we just
1190 // check for +1/-1. Make sure to check the new instruction offset is
1191 // actually an immediate and not a symbolic reference destined for
1192 // a relocation.
Chad Rosierf77e9092015-08-06 15:50:12 +00001193 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1194 int MIOffset = getLdStOffsetOp(MI).getImm();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001195 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001196 if (IsUnscaled != MIIsUnscaled) {
1197 // We're trying to pair instructions that differ in how they are scaled.
1198 // If FirstMI is scaled then scale the offset of MI accordingly.
1199 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1200 int MemSize = getMemScale(MI);
1201 if (MIIsUnscaled) {
1202 // If the unscaled offset isn't a multiple of the MemSize, we can't
1203 // pair the operations together: bail and keep looking.
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001204 if (MIOffset % MemSize) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001205 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1206 UsedRegUnits, TRI);
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001207 MemInsns.push_back(&MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001208 continue;
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001209 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001210 MIOffset /= MemSize;
1211 } else {
1212 MIOffset *= MemSize;
1213 }
1214 }
1215
Tim Northover3b0846e2014-05-24 12:50:23 +00001216 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1217 (Offset + OffsetStride == MIOffset))) {
1218 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001219 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001220 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001221 // instruction can't express the offset of the scaled narrow input,
1222 // bail and keep looking. For promotable zero stores, allow only when
1223 // the stored value is the same (i.e., WZR).
1224 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1225 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001226 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1227 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001228 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001229 continue;
1230 }
1231 } else {
Chad Rosierd1f6c842016-06-10 20:49:18 +00001232 // Pairwise instructions have a 7-bit signed offset field. Single
1233 // insns have a 12-bit unsigned offset field. If the resultant
1234 // immediate offset of merging these instructions is out of range for
1235 // a pairwise instruction, bail and keep looking.
Jun Bum Limcf974432016-03-31 14:47:24 +00001236 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001237 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1238 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001239 MemInsns.push_back(&MI);
Jun Bum Limcf974432016-03-31 14:47:24 +00001240 continue;
1241 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001242 // If the alignment requirements of the paired (scaled) instruction
1243 // can't express the offset of the unscaled input, bail and keep
1244 // looking.
1245 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001246 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1247 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001248 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001249 continue;
1250 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001251 }
1252 // If the destination register of the loads is the same register, bail
1253 // and keep looking. A load-pair instruction with both destination
1254 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001255 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001256 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1257 TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001258 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001259 continue;
1260 }
1261
1262 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001263 // the two instructions and none of the instructions between the second
1264 // and first alias with the second, we can combine the second into the
1265 // first.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001266 if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1267 !(MI.mayLoad() &&
1268 !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001269 !mayAlias(MI, MemInsns, AA)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001270 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001271 return MBBI;
1272 }
1273
1274 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001275 // between the two instructions and none of the instructions between the
1276 // first and the second alias with the first, we can combine the first
1277 // into the second.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001278 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg()) &&
1279 !(MayLoad &&
1280 !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001281 !mayAlias(FirstMI, MemInsns, AA)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001282 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001283 return MBBI;
1284 }
1285 // Unable to combine these instructions due to interference in between.
1286 // Keep looking.
1287 }
1288 }
1289
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001290 // If the instruction wasn't a matching load or store. Stop searching if we
1291 // encounter a call instruction that might modify memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001292 if (MI.isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001293 return E;
1294
Jun Bum Lim47aece12018-04-27 18:44:37 +00001295 // Update modified / uses register units.
1296 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001297
1298 // Otherwise, if the base register is modified, we have no match, so
1299 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001300 if (!ModifiedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001301 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001302
1303 // Update list of instructions that read/write memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001304 if (MI.mayLoadOrStore())
1305 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001306 }
1307 return E;
1308}
1309
1310MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001311AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1312 MachineBasicBlock::iterator Update,
1313 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001314 assert((Update->getOpcode() == AArch64::ADDXri ||
1315 Update->getOpcode() == AArch64::SUBXri) &&
1316 "Unexpected base register update instruction to merge!");
1317 MachineBasicBlock::iterator NextI = I;
1318 // Return the instruction following the merged instruction, which is
1319 // the instruction following our unmerged load. Unless that's the add/sub
1320 // instruction we're merging, in which case it's the one after that.
1321 if (++NextI == Update)
1322 ++NextI;
1323
1324 int Value = Update->getOperand(2).getImm();
1325 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001326 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001327 if (Update->getOpcode() == AArch64::SUBXri)
1328 Value = -Value;
1329
Chad Rosier2dfd3542015-09-23 13:51:44 +00001330 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1331 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001332 MachineInstrBuilder MIB;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001333 if (!isPairedLdSt(*I)) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001334 // Non-paired instruction.
1335 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001336 .add(getLdStRegOp(*Update))
1337 .add(getLdStRegOp(*I))
1338 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001339 .addImm(Value)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001340 .setMemRefs(I->memoperands_begin(), I->memoperands_end())
1341 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001342 } else {
1343 // Paired instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001344 int Scale = getMemScale(*I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001345 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001346 .add(getLdStRegOp(*Update))
1347 .add(getLdStRegOp(*I, 0))
1348 .add(getLdStRegOp(*I, 1))
1349 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001350 .addImm(Value / Scale)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001351 .setMemRefs(I->memoperands_begin(), I->memoperands_end())
1352 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001353 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001354 (void)MIB;
1355
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001356 if (IsPreIdx) {
1357 ++NumPreFolded;
Chad Rosier2dfd3542015-09-23 13:51:44 +00001358 DEBUG(dbgs() << "Creating pre-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001359 } else {
1360 ++NumPostFolded;
Chad Rosier2dfd3542015-09-23 13:51:44 +00001361 DEBUG(dbgs() << "Creating post-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001362 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001363 DEBUG(dbgs() << " Replacing instructions:\n ");
1364 DEBUG(I->print(dbgs()));
1365 DEBUG(dbgs() << " ");
1366 DEBUG(Update->print(dbgs()));
1367 DEBUG(dbgs() << " with instruction:\n ");
1368 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1369 DEBUG(dbgs() << "\n");
1370
1371 // Erase the old instructions for the block.
1372 I->eraseFromParent();
1373 Update->eraseFromParent();
1374
1375 return NextI;
1376}
1377
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001378bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1379 MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001380 unsigned BaseReg, int Offset) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001381 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001382 default:
1383 break;
1384 case AArch64::SUBXri:
Tim Northover3b0846e2014-05-24 12:50:23 +00001385 case AArch64::ADDXri:
1386 // Make sure it's a vanilla immediate operand, not a relocation or
1387 // anything else we can't handle.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001388 if (!MI.getOperand(2).isImm())
Tim Northover3b0846e2014-05-24 12:50:23 +00001389 break;
1390 // Watch out for 1 << 12 shifted value.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001391 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
Tim Northover3b0846e2014-05-24 12:50:23 +00001392 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393
1394 // The update instruction source and destination register must be the
1395 // same as the load/store base register.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001396 if (MI.getOperand(0).getReg() != BaseReg ||
1397 MI.getOperand(1).getReg() != BaseReg)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001398 break;
1399
1400 bool IsPairedInsn = isPairedLdSt(MemMI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001401 int UpdateOffset = MI.getOperand(2).getImm();
Eli Friedman8585e9d2016-08-12 20:28:02 +00001402 if (MI.getOpcode() == AArch64::SUBXri)
1403 UpdateOffset = -UpdateOffset;
1404
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001405 // For non-paired load/store instructions, the immediate must fit in a
1406 // signed 9-bit integer.
1407 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1408 break;
1409
1410 // For paired load/store instructions, the immediate must be a multiple of
1411 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1412 // integer.
1413 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001414 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001415 if (UpdateOffset % Scale != 0)
1416 break;
1417
1418 int ScaledOffset = UpdateOffset / Scale;
Eli Friedman8585e9d2016-08-12 20:28:02 +00001419 if (ScaledOffset > 63 || ScaledOffset < -64)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001420 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001421 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001422
1423 // If we have a non-zero Offset, we check that it matches the amount
1424 // we're adding to the register.
Eli Friedman8585e9d2016-08-12 20:28:02 +00001425 if (!Offset || Offset == UpdateOffset)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001426 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001427 break;
1428 }
1429 return false;
1430}
1431
1432MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001433 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001434 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001435 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001436 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001437
Chad Rosierf77e9092015-08-06 15:50:12 +00001438 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001439 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001440
Chad Rosierb7c5b912015-10-01 13:43:05 +00001441 // Scan forward looking for post-index opportunities. Updating instructions
1442 // can't be formed if the memory instruction doesn't have the offset we're
1443 // looking for.
1444 if (MIUnscaledOffset != UnscaledOffset)
1445 return E;
1446
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001447 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001448 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001449 bool IsPairedInsn = isPairedLdSt(MemMI);
1450 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1451 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1452 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1453 return E;
1454 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001455
Jun Bum Lim47aece12018-04-27 18:44:37 +00001456 // Track which register units have been modified and used between the first
1457 // insn (inclusive) and the second insn.
1458 ModifiedRegUnits.clear();
1459 UsedRegUnits.clear();
Tim Northover3b0846e2014-05-24 12:50:23 +00001460 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001461 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001462 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001463
Geoff Berry4ff2e362016-07-21 15:20:25 +00001464 // Don't count transient instructions towards the search limit since there
1465 // may be different numbers of them if e.g. debug information is present.
1466 if (!MI.isTransient())
1467 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001468
Tim Northover3b0846e2014-05-24 12:50:23 +00001469 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001470 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001471 return MBBI;
1472
1473 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001474 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001475
1476 // Otherwise, if the base register is used or modified, we have no match, so
1477 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001478 if (!ModifiedRegUnits.available(BaseReg) ||
1479 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001480 return E;
1481 }
1482 return E;
1483}
1484
1485MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001486 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001487 MachineBasicBlock::iterator B = I->getParent()->begin();
1488 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001489 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001491
Chad Rosierf77e9092015-08-06 15:50:12 +00001492 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1493 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001494
1495 // If the load/store is the first instruction in the block, there's obviously
1496 // not any matching update. Ditto if the memory offset isn't zero.
1497 if (MBBI == B || Offset != 0)
1498 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001499 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001500 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001501 bool IsPairedInsn = isPairedLdSt(MemMI);
1502 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1503 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1504 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1505 return E;
1506 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001507
Jun Bum Lim47aece12018-04-27 18:44:37 +00001508 // Track which register units have been modified and used between the first
1509 // insn (inclusive) and the second insn.
1510 ModifiedRegUnits.clear();
1511 UsedRegUnits.clear();
Geoff Berry173b14d2016-02-09 20:47:21 +00001512 unsigned Count = 0;
1513 do {
1514 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001515 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001516
Geoff Berry4ff2e362016-07-21 15:20:25 +00001517 // Don't count transient instructions towards the search limit since there
1518 // may be different numbers of them if e.g. debug information is present.
1519 if (!MI.isTransient())
Geoff Berry173b14d2016-02-09 20:47:21 +00001520 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001521
Tim Northover3b0846e2014-05-24 12:50:23 +00001522 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001523 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001524 return MBBI;
1525
1526 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001527 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001528
1529 // Otherwise, if the base register is used or modified, we have no match, so
1530 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001531 if (!ModifiedRegUnits.available(BaseReg) ||
1532 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001533 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001534 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 return E;
1536}
1537
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001538bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1539 MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001540 MachineInstr &MI = *MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001541 // If this is a volatile load, don't mess with it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001542 if (MI.hasOrderedMemoryRef())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001543 return false;
1544
1545 // Make sure this is a reg+imm.
1546 // FIXME: It is possible to extend it to handle reg+reg cases.
1547 if (!getLdStOffsetOp(MI).isImm())
1548 return false;
1549
Chad Rosier35706ad2016-02-04 21:26:02 +00001550 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001551 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001552 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001553 ++NumLoadsFromStoresPromoted;
1554 // Promote the load. Keeping the iterator straight is a
1555 // pain, so we let the merge routine tell us what the next instruction
1556 // is after it's done mucking about.
1557 MBBI = promoteLoadFromStore(MBBI, StoreI);
1558 return true;
1559 }
1560 return false;
1561}
1562
Chad Rosierd6daac42016-11-07 15:27:22 +00001563// Merge adjacent zero stores into a wider store.
1564bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
Chad Rosier24c46ad2016-02-09 18:10:20 +00001565 MachineBasicBlock::iterator &MBBI) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001566 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001567 MachineInstr &MI = *MBBI;
1568 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001569
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001570 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001571 return false;
1572
1573 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001574 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001575 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001576 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001577 if (MergeMI != E) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001578 ++NumZeroStoresPromoted;
1579
Chad Rosier24c46ad2016-02-09 18:10:20 +00001580 // Keeping the iterator straight is a pain, so we let the merge routine tell
1581 // us what the next instruction is after it's done mucking about.
Chad Rosierd6daac42016-11-07 15:27:22 +00001582 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001583 return true;
1584 }
1585 return false;
1586}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001587
Chad Rosier24c46ad2016-02-09 18:10:20 +00001588// Find loads and stores that can be merged into a single load or store pair
1589// instruction.
1590bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001591 MachineInstr &MI = *MBBI;
1592 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001593
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001594 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001595 return false;
1596
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001597 // Early exit if the offset is not possible to match. (6 bits of positive
1598 // range, plus allow an extra one in case we find a later insn that matches
1599 // with Offset-1)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001600 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001601 int Offset = getLdStOffsetOp(MI).getImm();
1602 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
Nirav Dave0f9d1112017-01-04 21:21:46 +00001603 // Allow one more for offset.
1604 if (Offset > 0)
1605 Offset -= OffsetStride;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001606 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1607 return false;
1608
Chad Rosier24c46ad2016-02-09 18:10:20 +00001609 // Look ahead up to LdStLimit instructions for a pairable instruction.
1610 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001611 MachineBasicBlock::iterator Paired =
1612 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001613 if (Paired != E) {
1614 ++NumPairCreated;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001615 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001616 ++NumUnscaledPairCreated;
1617 // Keeping the iterator straight is a pain, so we let the merge routine tell
1618 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001619 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1620 return true;
1621 }
1622 return false;
1623}
1624
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001625bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1626 (MachineBasicBlock::iterator &MBBI) {
1627 MachineInstr &MI = *MBBI;
1628 MachineBasicBlock::iterator E = MI.getParent()->end();
1629 MachineBasicBlock::iterator Update;
1630
1631 // Look forward to try to form a post-index instruction. For example,
1632 // ldr x0, [x20]
1633 // add x20, x20, #32
1634 // merged into:
1635 // ldr x0, [x20], #32
1636 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1637 if (Update != E) {
1638 // Merge the update into the ld/st.
1639 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1640 return true;
1641 }
1642
1643 // Don't know how to handle unscaled pre/post-index versions below, so bail.
1644 if (TII->isUnscaledLdSt(MI.getOpcode()))
1645 return false;
1646
1647 // Look back to try to find a pre-index instruction. For example,
1648 // add x0, x0, #8
1649 // ldr x1, [x0]
1650 // merged into:
1651 // ldr x1, [x0, #8]!
1652 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1653 if (Update != E) {
1654 // Merge the update into the ld/st.
1655 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1656 return true;
1657 }
1658
1659 // The immediate in the load/store is scaled by the size of the memory
1660 // operation. The immediate in the add we're looking for,
1661 // however, is not, so adjust here.
1662 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
1663
1664 // Look forward to try to find a post-index instruction. For example,
1665 // ldr x1, [x0, #64]
1666 // add x0, x0, #64
1667 // merged into:
1668 // ldr x1, [x0, #64]!
1669 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1670 if (Update != E) {
1671 // Merge the update into the ld/st.
1672 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1673 return true;
1674 }
1675
1676 return false;
1677}
1678
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001679bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
Chad Rosierd6daac42016-11-07 15:27:22 +00001680 bool EnableNarrowZeroStOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001681 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001682 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001683 // 1) Find loads that directly read from stores and promote them by
1684 // replacing with mov instructions. If the store is wider than the load,
1685 // the load will be replaced with a bitfield extract.
1686 // e.g.,
1687 // str w1, [x0, #4]
1688 // ldrh w2, [x0, #6]
1689 // ; becomes
1690 // str w1, [x0, #4]
NAKAMURA Takumife1202c2016-06-20 00:37:41 +00001691 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001692 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001693 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001694 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
1695 Modified = true;
1696 else
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001697 ++MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001698 }
Chad Rosierd6daac42016-11-07 15:27:22 +00001699 // 2) Merge adjacent zero stores into a wider store.
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001700 // e.g.,
1701 // strh wzr, [x0]
1702 // strh wzr, [x0, #2]
1703 // ; becomes
1704 // str wzr, [x0]
Chad Rosierd6daac42016-11-07 15:27:22 +00001705 // e.g.,
1706 // str wzr, [x0]
1707 // str wzr, [x0, #4]
1708 // ; becomes
1709 // str xzr, [x0]
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001710 if (EnableNarrowZeroStOpt)
1711 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1712 MBBI != E;) {
1713 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001714 Modified = true;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001715 else
Jun Bum Lim33be4992016-05-06 15:08:57 +00001716 ++MBBI;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001717 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001718 // 3) Find loads and stores that can be merged into a single load or store
1719 // pair instruction.
1720 // e.g.,
1721 // ldr x0, [x2]
1722 // ldr x1, [x2, #8]
1723 // ; becomes
1724 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001725 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001726 MBBI != E;) {
Geoff Berry22dfbc52016-08-12 15:26:00 +00001727 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
1728 Modified = true;
1729 else
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001731 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001732 // 4) Find base register updates that can be merged into the load or store
1733 // as a base-reg writeback.
1734 // e.g.,
1735 // ldr x0, [x2]
1736 // add x2, x2, #4
1737 // ; becomes
1738 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001739 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1740 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001741 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
1742 Modified = true;
1743 else
Tim Northover3b0846e2014-05-24 12:50:23 +00001744 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001745 }
1746
1747 return Modified;
1748}
1749
1750bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001751 if (skipFunction(Fn.getFunction()))
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00001752 return false;
1753
Oliver Stannardd414c992015-11-10 11:04:18 +00001754 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1755 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1756 TRI = Subtarget->getRegisterInfo();
Chad Rosiera69dcb62017-03-17 14:19:55 +00001757 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tim Northover3b0846e2014-05-24 12:50:23 +00001758
Jun Bum Lim47aece12018-04-27 18:44:37 +00001759 // Resize the modified and used register unit trackers. We do this once
1760 // per function and then clear the register units each time we optimize a load
1761 // or store.
1762 ModifiedRegUnits.init(*TRI);
1763 UsedRegUnits.init(*TRI);
Chad Rosierbba881e2016-02-02 15:02:30 +00001764
Tim Northover3b0846e2014-05-24 12:50:23 +00001765 bool Modified = false;
Chad Rosier10c7aaa2016-11-11 14:10:12 +00001766 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
Tim Northover3b0846e2014-05-24 12:50:23 +00001767 for (auto &MBB : Fn)
Chad Rosierd6daac42016-11-07 15:27:22 +00001768 Modified |= optimizeBlock(MBB, enableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001769
1770 return Modified;
1771}
1772
Chad Rosier8ade0342016-11-11 19:52:45 +00001773// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
1774// stores near one another? Note: The pre-RA instruction scheduler already has
1775// hooks to try and schedule pairable loads/stores together to improve pairing
1776// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
Tim Northover3b0846e2014-05-24 12:50:23 +00001777
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001778// FIXME: When pairing store instructions it's very possible for this pass to
1779// hoist a store with a KILL marker above another use (without a KILL marker).
1780// The resulting IR is invalid, but nothing uses the KILL markers after this
1781// pass, so it's never caused a problem in practice.
1782
Chad Rosier43f5c842015-08-05 12:40:13 +00001783/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1784/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001785FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1786 return new AArch64LoadStoreOpt();
1787}