blob: 178390e7a3170083569d0f4bef251b04eaea128b [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that performs load / store related peephole
11// optimizations. This pass should be run after register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000016#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "MCTargetDesc/AArch64AddressingModes.h"
18#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000019#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000020#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000021#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032using namespace llvm;
33
34#define DEBUG_TYPE "aarch64-ldst-opt"
35
Tim Northover3b0846e2014-05-24 12:50:23 +000036STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37STATISTIC(NumPostFolded, "Number of post-index updates folded");
38STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
Jun Bum Limc12c2792015-11-19 18:41:27 +000041STATISTIC(NumNarrowLoadsPromoted, "Number of narrow loads promoted");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000042STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000043STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000044
Chad Rosier35706ad2016-02-04 21:26:02 +000045// The LdStLimit limits how far we search for load/store pairs.
46static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000047 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000048
Chad Rosier35706ad2016-02-04 21:26:02 +000049// The UpdateLimit limits how far we search for update instructions when we form
50// pre-/post-index instructions.
51static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
52 cl::Hidden);
53
Chad Rosier96530b32015-08-05 13:44:51 +000054namespace llvm {
55void initializeAArch64LoadStoreOptPass(PassRegistry &);
56}
57
58#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
59
Tim Northover3b0846e2014-05-24 12:50:23 +000060namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000061
62typedef struct LdStPairFlags {
63 // If a matching instruction is found, MergeForward is set to true if the
64 // merge is to remove the first instruction and replace the second with
65 // a pair-wise insn, and false if the reverse is true.
66 bool MergeForward;
67
68 // SExtIdx gives the index of the result of the load pair that must be
69 // extended. The value of SExtIdx assumes that the paired load produces the
70 // value in this order: (I, returned iterator), i.e., -1 means no value has
71 // to be extended, 0 means I, and 1 means the returned iterator.
72 int SExtIdx;
73
74 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75
76 void setMergeForward(bool V = true) { MergeForward = V; }
77 bool getMergeForward() const { return MergeForward; }
78
79 void setSExtIdx(int V) { SExtIdx = V; }
80 int getSExtIdx() const { return SExtIdx; }
81
82} LdStPairFlags;
83
Tim Northover3b0846e2014-05-24 12:50:23 +000084struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000086 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000087 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
88 }
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 const AArch64InstrInfo *TII;
91 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000092 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
Chad Rosierbba881e2016-02-02 15:02:30 +000094 // Track which registers have been modified and used.
95 BitVector ModifiedRegs, UsedRegs;
96
Tim Northover3b0846e2014-05-24 12:50:23 +000097 // Scan the instructions looking for a load/store that can be combined
98 // with the current instruction into a load/store pair.
99 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000101 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +0000102 unsigned Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000103
104 // Scan the instructions looking for a store that writes to the address from
105 // which the current load instruction reads. Return true if one is found.
106 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
107 MachineBasicBlock::iterator &StoreI);
108
Chad Rosierb5933d72016-02-09 19:02:12 +0000109 // Merge the two instructions indicated into a wider instruction.
110 MachineBasicBlock::iterator
111 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000112 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000113 const LdStPairFlags &Flags);
114
Tim Northover3b0846e2014-05-24 12:50:23 +0000115 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000116 MachineBasicBlock::iterator
117 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000118 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000119 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000120
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000121 // Promote the load that reads directly from the address stored to.
122 MachineBasicBlock::iterator
123 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
124 MachineBasicBlock::iterator StoreI);
125
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 // Scan the instruction list to find a base register update that can
127 // be combined with the current instruction (a load or store) using
128 // pre or post indexed addressing with writeback. Scan forwards.
129 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000130 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000131 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000132
133 // Scan the instruction list to find a base register update that can
134 // be combined with the current instruction (a load or store) using
135 // pre or post indexed addressing with writeback. Scan backwards.
136 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000137 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000138
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000139 // Find an instruction that updates the base register of the ld/st
140 // instruction.
141 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
142 unsigned BaseReg, int Offset);
143
Chad Rosier2dfd3542015-09-23 13:51:44 +0000144 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000146 mergeUpdateInsn(MachineBasicBlock::iterator I,
147 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000148
Chad Rosier24c46ad2016-02-09 18:10:20 +0000149 // Is this a candidate for ld/st merging or pairing? For example, we don't
150 // touch volatiles or load/stores that have a hint to avoid pair formation.
151 bool isCandidateToMergeOrPair(MachineInstr *MI);
152
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000153 // Find and merge foldable ldr/str instructions.
154 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
155
Chad Rosier24c46ad2016-02-09 18:10:20 +0000156 // Find and pair ldr/str instructions.
157 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
158
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000159 // Find and promote load instructions which read directly from store.
160 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
161
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000162 // Check if converting two narrow loads into a single wider load with
163 // bitfield extracts could be enabled.
164 bool enableNarrowLdMerge(MachineFunction &Fn);
165
166 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000167
168 bool runOnMachineFunction(MachineFunction &Fn) override;
169
170 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000171 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000173};
174char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000175} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000176
Chad Rosier96530b32015-08-05 13:44:51 +0000177INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
178 AARCH64_LOAD_STORE_OPT_NAME, false, false)
179
Chad Rosier22eb7102015-08-06 17:37:18 +0000180static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 switch (Opc) {
182 default:
183 return false;
184 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000187 case AArch64::STURBBi:
188 case AArch64::STURHHi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000196 case AArch64::LDURSWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000197 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000198 case AArch64::LDURBBi:
199 case AArch64::LDURSBWi:
200 case AArch64::LDURSHWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000201 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000202 }
203}
204
Chad Rosier22eb7102015-08-06 17:37:18 +0000205static bool isUnscaledLdSt(MachineInstr *MI) {
206 return isUnscaledLdSt(MI->getOpcode());
207}
208
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000209static unsigned getBitExtrOpcode(MachineInstr *MI) {
210 switch (MI->getOpcode()) {
211 default:
212 llvm_unreachable("Unexpected opcode.");
213 case AArch64::LDRBBui:
214 case AArch64::LDURBBi:
215 case AArch64::LDRHHui:
216 case AArch64::LDURHHi:
217 return AArch64::UBFMWri;
218 case AArch64::LDRSBWui:
219 case AArch64::LDURSBWi:
220 case AArch64::LDRSHWui:
221 case AArch64::LDURSHWi:
222 return AArch64::SBFMWri;
223 }
224}
225
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000226static bool isNarrowStore(unsigned Opc) {
227 switch (Opc) {
228 default:
229 return false;
230 case AArch64::STRBBui:
231 case AArch64::STURBBi:
232 case AArch64::STRHHui:
233 case AArch64::STURHHi:
234 return true;
235 }
236}
237
Jun Bum Limc12c2792015-11-19 18:41:27 +0000238static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000239 switch (Opc) {
240 default:
241 return false;
242 case AArch64::LDRHHui:
243 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000244 case AArch64::LDRBBui:
245 case AArch64::LDURBBi:
246 case AArch64::LDRSHWui:
247 case AArch64::LDURSHWi:
248 case AArch64::LDRSBWui:
249 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000250 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000251 }
252}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000253
Jun Bum Limc12c2792015-11-19 18:41:27 +0000254static bool isNarrowLoad(MachineInstr *MI) {
255 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000256}
257
Chad Rosier00f9d232016-02-11 14:25:08 +0000258static bool isNarrowLoadOrStore(unsigned Opc) {
259 return isNarrowLoad(Opc) || isNarrowStore(Opc);
260}
261
Chad Rosier32d4d372015-09-29 16:07:32 +0000262// Scaling factor for unscaled load or store.
263static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000264 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000265 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000266 llvm_unreachable("Opcode has unknown scale!");
267 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000268 case AArch64::LDURBBi:
269 case AArch64::LDRSBWui:
270 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000271 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000272 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000273 return 1;
274 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000275 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000276 case AArch64::LDRSHWui:
277 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000278 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000279 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000280 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000281 case AArch64::LDRSui:
282 case AArch64::LDURSi:
283 case AArch64::LDRSWui:
284 case AArch64::LDURSWi:
285 case AArch64::LDRWui:
286 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000287 case AArch64::STRSui:
288 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000289 case AArch64::STRWui:
290 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000291 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000292 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000293 case AArch64::LDPWi:
294 case AArch64::STPSi:
295 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000296 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000297 case AArch64::LDRDui:
298 case AArch64::LDURDi:
299 case AArch64::LDRXui:
300 case AArch64::LDURXi:
301 case AArch64::STRDui:
302 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000303 case AArch64::STRXui:
304 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000305 case AArch64::LDPDi:
306 case AArch64::LDPXi:
307 case AArch64::STPDi:
308 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000309 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000310 case AArch64::LDRQui:
311 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000312 case AArch64::STRQui:
313 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000314 case AArch64::LDPQi:
315 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000316 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000317 }
318}
319
Quentin Colombet66b61632015-03-06 22:42:10 +0000320static unsigned getMatchingNonSExtOpcode(unsigned Opc,
321 bool *IsValidLdStrOpc = nullptr) {
322 if (IsValidLdStrOpc)
323 *IsValidLdStrOpc = true;
324 switch (Opc) {
325 default:
326 if (IsValidLdStrOpc)
327 *IsValidLdStrOpc = false;
328 return UINT_MAX;
329 case AArch64::STRDui:
330 case AArch64::STURDi:
331 case AArch64::STRQui:
332 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000333 case AArch64::STRBBui:
334 case AArch64::STURBBi:
335 case AArch64::STRHHui:
336 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000337 case AArch64::STRWui:
338 case AArch64::STURWi:
339 case AArch64::STRXui:
340 case AArch64::STURXi:
341 case AArch64::LDRDui:
342 case AArch64::LDURDi:
343 case AArch64::LDRQui:
344 case AArch64::LDURQi:
345 case AArch64::LDRWui:
346 case AArch64::LDURWi:
347 case AArch64::LDRXui:
348 case AArch64::LDURXi:
349 case AArch64::STRSui:
350 case AArch64::STURSi:
351 case AArch64::LDRSui:
352 case AArch64::LDURSi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000353 case AArch64::LDRHHui:
354 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000355 case AArch64::LDRBBui:
356 case AArch64::LDURBBi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000357 return Opc;
358 case AArch64::LDRSWui:
359 return AArch64::LDRWui;
360 case AArch64::LDURSWi:
361 return AArch64::LDURWi;
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000362 case AArch64::LDRSBWui:
363 return AArch64::LDRBBui;
364 case AArch64::LDRSHWui:
365 return AArch64::LDRHHui;
366 case AArch64::LDURSBWi:
367 return AArch64::LDURBBi;
368 case AArch64::LDURSHWi:
369 return AArch64::LDURHHi;
Quentin Colombet66b61632015-03-06 22:42:10 +0000370 }
371}
372
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000373static unsigned getMatchingWideOpcode(unsigned Opc) {
374 switch (Opc) {
375 default:
376 llvm_unreachable("Opcode has no wide equivalent!");
377 case AArch64::STRBBui:
378 return AArch64::STRHHui;
379 case AArch64::STRHHui:
380 return AArch64::STRWui;
381 case AArch64::STURBBi:
382 return AArch64::STURHHi;
383 case AArch64::STURHHi:
384 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000385 case AArch64::STURWi:
386 return AArch64::STURXi;
387 case AArch64::STRWui:
388 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000389 case AArch64::LDRHHui:
390 case AArch64::LDRSHWui:
391 return AArch64::LDRWui;
392 case AArch64::LDURHHi:
393 case AArch64::LDURSHWi:
394 return AArch64::LDURWi;
395 case AArch64::LDRBBui:
396 case AArch64::LDRSBWui:
397 return AArch64::LDRHHui;
398 case AArch64::LDURBBi:
399 case AArch64::LDURSBWi:
400 return AArch64::LDURHHi;
401 }
402}
403
Tim Northover3b0846e2014-05-24 12:50:23 +0000404static unsigned getMatchingPairOpcode(unsigned Opc) {
405 switch (Opc) {
406 default:
407 llvm_unreachable("Opcode has no pairwise equivalent!");
408 case AArch64::STRSui:
409 case AArch64::STURSi:
410 return AArch64::STPSi;
411 case AArch64::STRDui:
412 case AArch64::STURDi:
413 return AArch64::STPDi;
414 case AArch64::STRQui:
415 case AArch64::STURQi:
416 return AArch64::STPQi;
417 case AArch64::STRWui:
418 case AArch64::STURWi:
419 return AArch64::STPWi;
420 case AArch64::STRXui:
421 case AArch64::STURXi:
422 return AArch64::STPXi;
423 case AArch64::LDRSui:
424 case AArch64::LDURSi:
425 return AArch64::LDPSi;
426 case AArch64::LDRDui:
427 case AArch64::LDURDi:
428 return AArch64::LDPDi;
429 case AArch64::LDRQui:
430 case AArch64::LDURQi:
431 return AArch64::LDPQi;
432 case AArch64::LDRWui:
433 case AArch64::LDURWi:
434 return AArch64::LDPWi;
435 case AArch64::LDRXui:
436 case AArch64::LDURXi:
437 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000438 case AArch64::LDRSWui:
439 case AArch64::LDURSWi:
440 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000441 }
442}
443
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000444static unsigned isMatchingStore(MachineInstr *LoadInst,
445 MachineInstr *StoreInst) {
446 unsigned LdOpc = LoadInst->getOpcode();
447 unsigned StOpc = StoreInst->getOpcode();
448 switch (LdOpc) {
449 default:
450 llvm_unreachable("Unsupported load instruction!");
451 case AArch64::LDRBBui:
452 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
453 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
454 case AArch64::LDURBBi:
455 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
456 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
457 case AArch64::LDRHHui:
458 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
459 StOpc == AArch64::STRXui;
460 case AArch64::LDURHHi:
461 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
462 StOpc == AArch64::STURXi;
463 case AArch64::LDRWui:
464 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
465 case AArch64::LDURWi:
466 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
467 case AArch64::LDRXui:
468 return StOpc == AArch64::STRXui;
469 case AArch64::LDURXi:
470 return StOpc == AArch64::STURXi;
471 }
472}
473
Tim Northover3b0846e2014-05-24 12:50:23 +0000474static unsigned getPreIndexedOpcode(unsigned Opc) {
475 switch (Opc) {
476 default:
477 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000478 case AArch64::STRSui:
479 return AArch64::STRSpre;
480 case AArch64::STRDui:
481 return AArch64::STRDpre;
482 case AArch64::STRQui:
483 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000484 case AArch64::STRBBui:
485 return AArch64::STRBBpre;
486 case AArch64::STRHHui:
487 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000488 case AArch64::STRWui:
489 return AArch64::STRWpre;
490 case AArch64::STRXui:
491 return AArch64::STRXpre;
492 case AArch64::LDRSui:
493 return AArch64::LDRSpre;
494 case AArch64::LDRDui:
495 return AArch64::LDRDpre;
496 case AArch64::LDRQui:
497 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000498 case AArch64::LDRBBui:
499 return AArch64::LDRBBpre;
500 case AArch64::LDRHHui:
501 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000502 case AArch64::LDRWui:
503 return AArch64::LDRWpre;
504 case AArch64::LDRXui:
505 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000506 case AArch64::LDRSWui:
507 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000508 case AArch64::LDPSi:
509 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000510 case AArch64::LDPSWi:
511 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000512 case AArch64::LDPDi:
513 return AArch64::LDPDpre;
514 case AArch64::LDPQi:
515 return AArch64::LDPQpre;
516 case AArch64::LDPWi:
517 return AArch64::LDPWpre;
518 case AArch64::LDPXi:
519 return AArch64::LDPXpre;
520 case AArch64::STPSi:
521 return AArch64::STPSpre;
522 case AArch64::STPDi:
523 return AArch64::STPDpre;
524 case AArch64::STPQi:
525 return AArch64::STPQpre;
526 case AArch64::STPWi:
527 return AArch64::STPWpre;
528 case AArch64::STPXi:
529 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 }
531}
532
533static unsigned getPostIndexedOpcode(unsigned Opc) {
534 switch (Opc) {
535 default:
536 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
537 case AArch64::STRSui:
538 return AArch64::STRSpost;
539 case AArch64::STRDui:
540 return AArch64::STRDpost;
541 case AArch64::STRQui:
542 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000543 case AArch64::STRBBui:
544 return AArch64::STRBBpost;
545 case AArch64::STRHHui:
546 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000547 case AArch64::STRWui:
548 return AArch64::STRWpost;
549 case AArch64::STRXui:
550 return AArch64::STRXpost;
551 case AArch64::LDRSui:
552 return AArch64::LDRSpost;
553 case AArch64::LDRDui:
554 return AArch64::LDRDpost;
555 case AArch64::LDRQui:
556 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000557 case AArch64::LDRBBui:
558 return AArch64::LDRBBpost;
559 case AArch64::LDRHHui:
560 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000561 case AArch64::LDRWui:
562 return AArch64::LDRWpost;
563 case AArch64::LDRXui:
564 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000565 case AArch64::LDRSWui:
566 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 case AArch64::LDPSi:
568 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000569 case AArch64::LDPSWi:
570 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000571 case AArch64::LDPDi:
572 return AArch64::LDPDpost;
573 case AArch64::LDPQi:
574 return AArch64::LDPQpost;
575 case AArch64::LDPWi:
576 return AArch64::LDPWpost;
577 case AArch64::LDPXi:
578 return AArch64::LDPXpost;
579 case AArch64::STPSi:
580 return AArch64::STPSpost;
581 case AArch64::STPDi:
582 return AArch64::STPDpost;
583 case AArch64::STPQi:
584 return AArch64::STPQpost;
585 case AArch64::STPWi:
586 return AArch64::STPWpost;
587 case AArch64::STPXi:
588 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 }
590}
591
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000592static bool isPairedLdSt(const MachineInstr *MI) {
593 switch (MI->getOpcode()) {
594 default:
595 return false;
596 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000597 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000598 case AArch64::LDPDi:
599 case AArch64::LDPQi:
600 case AArch64::LDPWi:
601 case AArch64::LDPXi:
602 case AArch64::STPSi:
603 case AArch64::STPDi:
604 case AArch64::STPQi:
605 case AArch64::STPWi:
606 case AArch64::STPXi:
607 return true;
608 }
609}
610
611static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
612 unsigned PairedRegOp = 0) {
613 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
614 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
615 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000616}
617
618static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000619 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
620 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000621}
622
623static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000624 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
625 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000626}
627
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000628static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
629 MachineInstr *StoreInst) {
630 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
631 int LoadSize = getMemScale(LoadInst);
632 int StoreSize = getMemScale(StoreInst);
633 int UnscaledStOffset = isUnscaledLdSt(StoreInst)
634 ? getLdStOffsetOp(StoreInst).getImm()
635 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
636 int UnscaledLdOffset = isUnscaledLdSt(LoadInst)
637 ? getLdStOffsetOp(LoadInst).getImm()
638 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
639 return (UnscaledStOffset <= UnscaledLdOffset) &&
640 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
641}
642
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000643static bool isPromotableZeroStoreOpcode(MachineInstr *MI) {
644 unsigned Opc = MI->getOpcode();
645 return isNarrowStore(Opc) || Opc == AArch64::STRWui || Opc == AArch64::STURWi;
646}
647
648static bool isPromotableZeroStoreInst(MachineInstr *MI) {
649 return (isPromotableZeroStoreOpcode(MI)) &&
650 getLdStRegOp(MI).getReg() == AArch64::WZR;
651}
652
Tim Northover3b0846e2014-05-24 12:50:23 +0000653MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000654AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000655 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000656 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 MachineBasicBlock::iterator NextI = I;
658 ++NextI;
659 // If NextI is the second of the two instructions to be merged, we need
660 // to skip one further. Either way we merge will invalidate the iterator,
661 // and we don't need to scan the new instruction, as it's a pairwise
662 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000663 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000664 ++NextI;
665
Chad Rosierb5933d72016-02-09 19:02:12 +0000666 unsigned Opc = I->getOpcode();
Chad Rosier11eedc92016-02-09 19:17:18 +0000667 bool IsScaled = !isUnscaledLdSt(Opc);
668 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000669
Chad Rosier96a18a92015-07-21 17:42:04 +0000670 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000671 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000672 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000673 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000674 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000676 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000677 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000678
679 // Which register is Rt and which is Rt2 depends on the offset order.
680 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000681 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000682 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
683 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000684 Rt2MI = I;
685 } else {
686 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000687 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000688 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000689
James Molloy5b18b4c2015-10-23 10:41:38 +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 Rosierc46ef882016-02-09 19:33:42 +0000697 DebugLoc DL = I->getDebugLoc();
698 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000699 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000700 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000701 // When merging small (< 32 bit) loads for big-endian targets, the order of
702 // the component parts gets swapped.
703 if (!Subtarget->isLittleEndian())
704 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000705 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000706 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000707 NewMemMI =
708 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
709 .addOperand(getLdStRegOp(RtNewDest))
710 .addOperand(BaseRegOp)
711 .addImm(OffsetImm)
712 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000713
714 DEBUG(
715 dbgs()
716 << "Creating the new load and extract. Replacing instructions:\n ");
717 DEBUG(I->print(dbgs()));
718 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000719 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000720 DEBUG(dbgs() << " with instructions:\n ");
721 DEBUG((NewMemMI)->print(dbgs()));
722
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000723 int Width = getMemScale(I) == 1 ? 8 : 16;
724 int LSBLow = 0;
725 int LSBHigh = Width;
726 int ImmsLow = LSBLow + Width - 1;
727 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000728 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000729 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000730 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000731 BitExtMI1 =
732 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
733 .addOperand(getLdStRegOp(Rt2MI))
734 .addReg(getLdStRegOp(RtNewDest).getReg())
735 .addImm(LSBHigh)
736 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000737 // Create the bitfield extract for low bits.
738 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
739 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000740 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000741 .addOperand(getLdStRegOp(RtMI))
742 .addReg(getLdStRegOp(RtNewDest).getReg())
743 .addImm(ImmsLow);
744 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000745 BitExtMI2 =
746 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
747 .addOperand(getLdStRegOp(RtMI))
748 .addReg(getLdStRegOp(RtNewDest).getReg())
749 .addImm(LSBLow)
750 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000751 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000752 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000753 // Create the bitfield extract for low bits.
754 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
755 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000756 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000757 .addOperand(getLdStRegOp(RtMI))
758 .addReg(getLdStRegOp(RtNewDest).getReg())
759 .addImm(ImmsLow);
760 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000761 BitExtMI1 =
762 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
763 .addOperand(getLdStRegOp(RtMI))
764 .addReg(getLdStRegOp(RtNewDest).getReg())
765 .addImm(LSBLow)
766 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000767 }
768
769 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000770 BitExtMI2 =
771 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
772 .addOperand(getLdStRegOp(Rt2MI))
773 .addReg(getLdStRegOp(RtNewDest).getReg())
774 .addImm(LSBHigh)
775 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000776 }
777 DEBUG(dbgs() << " ");
778 DEBUG((BitExtMI1)->print(dbgs()));
779 DEBUG(dbgs() << " ");
780 DEBUG((BitExtMI2)->print(dbgs()));
781 DEBUG(dbgs() << "\n");
782
783 // Erase the old instructions.
784 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000785 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000786 return NextI;
787 }
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000788 assert(isPromotableZeroStoreInst(I) && "Expected promotable zero store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000789
Tim Northover3b0846e2014-05-24 12:50:23 +0000790 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000791 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000792 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000793 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Chad Rosierb5933d72016-02-09 19:02:12 +0000794 .addOperand(BaseRegOp)
795 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000796 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000797
Tim Northover3b0846e2014-05-24 12:50:23 +0000798 (void)MIB;
799
Chad Rosierb5933d72016-02-09 19:02:12 +0000800 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
801 DEBUG(I->print(dbgs()));
802 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000803 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000804 DEBUG(dbgs() << " with instruction:\n ");
805 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
806 DEBUG(dbgs() << "\n");
807
808 // Erase the old instructions.
809 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000810 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000811 return NextI;
812}
813
814MachineBasicBlock::iterator
815AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
816 MachineBasicBlock::iterator Paired,
817 const LdStPairFlags &Flags) {
818 MachineBasicBlock::iterator NextI = I;
819 ++NextI;
820 // If NextI is the second of the two instructions to be merged, we need
821 // to skip one further. Either way we merge will invalidate the iterator,
822 // and we don't need to scan the new instruction, as it's a pairwise
823 // instruction, which we're not considering for further action anyway.
824 if (NextI == Paired)
825 ++NextI;
826
827 int SExtIdx = Flags.getSExtIdx();
828 unsigned Opc =
829 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
830 bool IsUnscaled = isUnscaledLdSt(Opc);
831 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
832
833 bool MergeForward = Flags.getMergeForward();
834 // Insert our new paired instruction after whichever of the paired
835 // instructions MergeForward indicates.
836 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
837 // Also based on MergeForward is from where we copy the base register operand
838 // so we get the flags compatible with the input code.
839 const MachineOperand &BaseRegOp =
840 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
841
Chad Rosier00f9d232016-02-11 14:25:08 +0000842 int Offset = getLdStOffsetOp(I).getImm();
843 int PairedOffset = getLdStOffsetOp(Paired).getImm();
844 bool PairedIsUnscaled = isUnscaledLdSt(Paired->getOpcode());
845 if (IsUnscaled != PairedIsUnscaled) {
846 // We're trying to pair instructions that differ in how they are scaled. If
847 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
848 // the opposite (i.e., make Paired's offset unscaled).
849 int MemSize = getMemScale(Paired);
850 if (PairedIsUnscaled) {
851 // If the unscaled offset isn't a multiple of the MemSize, we can't
852 // pair the operations together.
853 assert(!(PairedOffset % getMemScale(Paired)) &&
854 "Offset should be a multiple of the stride!");
855 PairedOffset /= MemSize;
856 } else {
857 PairedOffset *= MemSize;
858 }
859 }
860
Chad Rosierb5933d72016-02-09 19:02:12 +0000861 // Which register is Rt and which is Rt2 depends on the offset order.
862 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000863 if (Offset == PairedOffset + OffsetStride) {
Chad Rosierb5933d72016-02-09 19:02:12 +0000864 RtMI = Paired;
865 Rt2MI = I;
866 // Here we swapped the assumption made for SExtIdx.
867 // I.e., we turn ldp I, Paired into ldp Paired, I.
868 // Update the index accordingly.
869 if (SExtIdx != -1)
870 SExtIdx = (SExtIdx + 1) % 2;
871 } else {
872 RtMI = I;
873 Rt2MI = Paired;
874 }
875 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000876 // Scale the immediate offset, if necessary.
877 if (isUnscaledLdSt(RtMI->getOpcode())) {
878 assert(!(OffsetImm % getMemScale(RtMI)) &&
879 "Unscaled offset cannot be scaled.");
880 OffsetImm /= getMemScale(RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000881 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000882
883 // Construct the new instruction.
884 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000885 DebugLoc DL = I->getDebugLoc();
886 MachineBasicBlock *MBB = I->getParent();
887 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000888 .addOperand(getLdStRegOp(RtMI))
889 .addOperand(getLdStRegOp(Rt2MI))
890 .addOperand(BaseRegOp)
891 .addImm(OffsetImm);
892 // FIXME: Copy the mem operands from the source instructions. The MI scheduler
893 // needs these to reason about loads/stores.
894
895 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000896
897 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
898 DEBUG(I->print(dbgs()));
899 DEBUG(dbgs() << " ");
900 DEBUG(Paired->print(dbgs()));
901 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000902 if (SExtIdx != -1) {
903 // Generate the sign extension for the proper result of the ldp.
904 // I.e., with X1, that would be:
905 // %W1<def> = KILL %W1, %X1<imp-def>
906 // %X1<def> = SBFMXri %X1<kill>, 0, 31
907 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
908 // Right now, DstMO has the extended register, since it comes from an
909 // extended opcode.
910 unsigned DstRegX = DstMO.getReg();
911 // Get the W variant of that register.
912 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
913 // Update the result of LDP to use the W instead of the X variant.
914 DstMO.setReg(DstRegW);
915 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
916 DEBUG(dbgs() << "\n");
917 // Make the machine verifier happy by providing a definition for
918 // the X register.
919 // Insert this definition right after the generated LDP, i.e., before
920 // InsertionPoint.
921 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000922 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000923 .addReg(DstRegW)
924 .addReg(DstRegX, RegState::Define);
925 MIBKill->getOperand(2).setImplicit();
926 // Create the sign extension.
927 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000928 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000929 .addReg(DstRegX)
930 .addImm(0)
931 .addImm(31);
932 (void)MIBSXTW;
933 DEBUG(dbgs() << " Extend operand:\n ");
934 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000935 } else {
936 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000937 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000938 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000939
940 // Erase the old instructions.
941 I->eraseFromParent();
942 Paired->eraseFromParent();
943
944 return NextI;
945}
946
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000947MachineBasicBlock::iterator
948AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
949 MachineBasicBlock::iterator StoreI) {
950 MachineBasicBlock::iterator NextI = LoadI;
951 ++NextI;
952
953 int LoadSize = getMemScale(LoadI);
954 int StoreSize = getMemScale(StoreI);
955 unsigned LdRt = getLdStRegOp(LoadI).getReg();
956 unsigned StRt = getLdStRegOp(StoreI).getReg();
957 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
958
959 assert((IsStoreXReg ||
960 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
961 "Unexpected RegClass");
962
963 MachineInstr *BitExtMI;
964 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
965 // Remove the load, if the destination register of the loads is the same
966 // register for stored value.
967 if (StRt == LdRt && LoadSize == 8) {
968 DEBUG(dbgs() << "Remove load instruction:\n ");
969 DEBUG(LoadI->print(dbgs()));
970 DEBUG(dbgs() << "\n");
971 LoadI->eraseFromParent();
972 return NextI;
973 }
974 // Replace the load with a mov if the load and store are in the same size.
975 BitExtMI =
976 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
977 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
978 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
979 .addReg(StRt)
980 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
981 } else {
982 // FIXME: Currently we disable this transformation in big-endian targets as
983 // performance and correctness are verified only in little-endian.
984 if (!Subtarget->isLittleEndian())
985 return NextI;
986 bool IsUnscaled = isUnscaledLdSt(LoadI);
987 assert(IsUnscaled == isUnscaledLdSt(StoreI) && "Unsupported ld/st match");
988 assert(LoadSize <= StoreSize && "Invalid load size");
989 int UnscaledLdOffset = IsUnscaled
990 ? getLdStOffsetOp(LoadI).getImm()
991 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
992 int UnscaledStOffset = IsUnscaled
993 ? getLdStOffsetOp(StoreI).getImm()
994 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
995 int Width = LoadSize * 8;
996 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
997 int Imms = Immr + Width - 1;
998 unsigned DestReg = IsStoreXReg
999 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
1000 &AArch64::GPR64RegClass)
1001 : LdRt;
1002
1003 assert((UnscaledLdOffset >= UnscaledStOffset &&
1004 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1005 "Invalid offset");
1006
1007 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1008 Imms = Immr + Width - 1;
1009 if (UnscaledLdOffset == UnscaledStOffset) {
1010 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1011 | ((Immr) << 6) // immr
1012 | ((Imms) << 0) // imms
1013 ;
1014
1015 BitExtMI =
1016 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1017 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1018 DestReg)
1019 .addReg(StRt)
1020 .addImm(AndMaskEncoded);
1021 } else {
1022 BitExtMI =
1023 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1024 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1025 DestReg)
1026 .addReg(StRt)
1027 .addImm(Immr)
1028 .addImm(Imms);
1029 }
1030 }
1031
1032 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1033 DEBUG(StoreI->print(dbgs()));
1034 DEBUG(dbgs() << " ");
1035 DEBUG(LoadI->print(dbgs()));
1036 DEBUG(dbgs() << " with instructions:\n ");
1037 DEBUG(StoreI->print(dbgs()));
1038 DEBUG(dbgs() << " ");
1039 DEBUG((BitExtMI)->print(dbgs()));
1040 DEBUG(dbgs() << "\n");
1041
1042 // Erase the old instructions.
1043 LoadI->eraseFromParent();
1044 return NextI;
1045}
1046
Tim Northover3b0846e2014-05-24 12:50:23 +00001047/// trackRegDefsUses - Remember what registers the specified instruction uses
1048/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001049static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001050 BitVector &UsedRegs,
1051 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001052 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001053 if (MO.isRegMask())
1054 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1055
1056 if (!MO.isReg())
1057 continue;
1058 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001059 if (!Reg)
1060 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001061 if (MO.isDef()) {
1062 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1063 ModifiedRegs.set(*AI);
1064 } else {
1065 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1066 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1067 UsedRegs.set(*AI);
1068 }
1069 }
1070}
1071
1072static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001073 // Convert the byte-offset used by unscaled into an "element" offset used
1074 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001075 if (IsUnscaled) {
1076 // If the byte-offset isn't a multiple of the stride, there's no point
1077 // trying to match it.
1078 if (Offset % OffsetStride)
1079 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001080 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001081 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001082 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001083}
1084
1085// Do alignment, specialized to power of 2 and for signed ints,
1086// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001087// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001088// FIXME: Move this function to include/MathExtras.h?
1089static int alignTo(int Num, int PowOf2) {
1090 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1091}
1092
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001093static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1094 const AArch64InstrInfo *TII) {
1095 // One of the instructions must modify memory.
1096 if (!MIa->mayStore() && !MIb->mayStore())
1097 return false;
1098
1099 // Both instructions must be memory operations.
1100 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1101 return false;
1102
1103 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1104}
1105
1106static bool mayAlias(MachineInstr *MIa,
1107 SmallVectorImpl<MachineInstr *> &MemInsns,
1108 const AArch64InstrInfo *TII) {
1109 for (auto &MIb : MemInsns)
1110 if (mayAlias(MIa, MIb, TII))
1111 return true;
1112
1113 return false;
1114}
1115
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001116bool AArch64LoadStoreOpt::findMatchingStore(
1117 MachineBasicBlock::iterator I, unsigned Limit,
1118 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001119 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001120 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001121 MachineInstr *LoadMI = I;
1122 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001123
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001124 // If the load is the first instruction in the block, there's obviously
1125 // not any matching store.
1126 if (MBBI == B)
1127 return false;
1128
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001129 // Track which registers have been modified and used between the first insn
1130 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001131 ModifiedRegs.reset();
1132 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001133
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001134 unsigned Count = 0;
1135 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001136 --MBBI;
1137 MachineInstr *MI = MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001138
1139 // Don't count DBG_VALUE instructions towards the search limit.
1140 if (!MI->isDebugValue())
1141 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001142
1143 // If the load instruction reads directly from the address to which the
1144 // store instruction writes and the stored value is not modified, we can
1145 // promote the load. Since we do not handle stores with pre-/post-index,
1146 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001147 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001148 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001149 isLdOffsetInRangeOfSt(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001150 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1151 StoreI = MBBI;
1152 return true;
1153 }
1154
1155 if (MI->isCall())
1156 return false;
1157
1158 // Update modified / uses register lists.
1159 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1160
1161 // Otherwise, if the base register is modified, we have no match, so
1162 // return early.
1163 if (ModifiedRegs[BaseReg])
1164 return false;
1165
1166 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001167 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001168 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001169 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001170 return false;
1171}
1172
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001173// Returns true if these two opcodes can be merged or paired. Otherwise,
1174// returns false.
1175static bool canMergeOpc(unsigned OpcA, unsigned OpcB, LdStPairFlags &Flags) {
1176 // Opcodes match: nothing more to check.
1177 if (OpcA == OpcB)
1178 return true;
1179
1180 // Try to match a sign-extended load/store with a zero-extended load/store.
1181 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1182 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1183 assert(IsValidLdStrOpc &&
1184 "Given Opc should be a Load or Store with an immediate");
1185 // OpcA will be the first instruction in the pair.
1186 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1187 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1188 return true;
1189 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001190
1191 // If the second instruction isn't even a load/store, bail out.
1192 if (!PairIsValidLdStrOpc)
1193 return false;
1194
1195 // FIXME: We don't support merging narrow loads/stores with mixed
1196 // scaled/unscaled offsets.
1197 if (isNarrowLoadOrStore(OpcA) || isNarrowLoadOrStore(OpcB))
1198 return false;
1199
1200 // Try to match an unscaled load/store with a scaled load/store.
1201 return isUnscaledLdSt(OpcA) != isUnscaledLdSt(OpcB) &&
1202 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1203
1204 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001205}
1206
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001207/// Scan the instructions looking for a load/store that can be combined with the
1208/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001209MachineBasicBlock::iterator
1210AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001211 LdStPairFlags &Flags, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 MachineBasicBlock::iterator E = I->getParent()->end();
1213 MachineBasicBlock::iterator MBBI = I;
1214 MachineInstr *FirstMI = I;
1215 ++MBBI;
1216
Matthias Braunfa3872e2015-05-18 20:27:55 +00001217 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001218 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +00001219 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001220 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1221 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1222 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001223 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001224 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001225
1226 // Track which registers have been modified and used between the first insn
1227 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001228 ModifiedRegs.reset();
1229 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001230
1231 // Remember any instructions that read/write memory between FirstMI and MI.
1232 SmallVector<MachineInstr *, 4> MemInsns;
1233
Tim Northover3b0846e2014-05-24 12:50:23 +00001234 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1235 MachineInstr *MI = MBBI;
1236 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1237 // optimization by changing how far we scan.
1238 if (MI->isDebugValue())
1239 continue;
1240
1241 // Now that we know this is a real instruction, count it.
1242 ++Count;
1243
Chad Rosier18896c02016-02-04 16:01:40 +00001244 Flags.setSExtIdx(-1);
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001245 if (canMergeOpc(Opc, MI->getOpcode(), Flags) &&
1246 getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001247 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001248 // If we've found another instruction with the same opcode, check to see
1249 // if the base and offset are compatible with our starting instruction.
1250 // These instructions all have scaled immediate operands, so we just
1251 // check for +1/-1. Make sure to check the new instruction offset is
1252 // actually an immediate and not a symbolic reference destined for
1253 // a relocation.
1254 //
1255 // Pairwise instructions have a 7-bit signed offset field. Single insns
1256 // have a 12-bit unsigned offset field. To be a valid combine, the
1257 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001258 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1259 int MIOffset = getLdStOffsetOp(MI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +00001260 bool MIIsUnscaled = isUnscaledLdSt(MI);
1261 if (IsUnscaled != MIIsUnscaled) {
1262 // We're trying to pair instructions that differ in how they are scaled.
1263 // If FirstMI is scaled then scale the offset of MI accordingly.
1264 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1265 int MemSize = getMemScale(MI);
1266 if (MIIsUnscaled) {
1267 // If the unscaled offset isn't a multiple of the MemSize, we can't
1268 // pair the operations together: bail and keep looking.
1269 if (MIOffset % MemSize)
1270 continue;
1271 MIOffset /= MemSize;
1272 } else {
1273 MIOffset *= MemSize;
1274 }
1275 }
1276
Tim Northover3b0846e2014-05-24 12:50:23 +00001277 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1278 (Offset + OffsetStride == MIOffset))) {
1279 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1280 // If this is a volatile load/store that otherwise matched, stop looking
1281 // as something is going on that we don't have enough information to
1282 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1283 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1284 return E;
1285 // If the resultant immediate offset of merging these instructions
1286 // is out of range for a pairwise instruction, bail and keep looking.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001287 bool IsNarrowLoad = isNarrowLoad(MI->getOpcode());
1288 if (!IsNarrowLoad &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001289 !inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001290 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001291 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001292 continue;
1293 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001294
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001295 if (IsNarrowLoad || IsPromotableZeroStore) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001296 // If the alignment requirements of the scaled wide load/store
1297 // instruction can't express the offset of the scaled narrow
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001298 // input, bail and keep looking.
1299 if (!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) {
1300 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1301 MemInsns.push_back(MI);
1302 continue;
1303 }
1304 } else {
1305 // If the alignment requirements of the paired (scaled) instruction
1306 // can't express the offset of the unscaled input, bail and keep
1307 // looking.
1308 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1309 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1310 MemInsns.push_back(MI);
1311 continue;
1312 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001313 }
1314 // If the destination register of the loads is the same register, bail
1315 // and keep looking. A load-pair instruction with both destination
1316 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001317 // For narrow stores, allow only when the stored value is the same
1318 // (i.e., WZR).
1319 if ((MayLoad && Reg == getLdStRegOp(MI).getReg()) ||
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001320 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001321 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001322 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001323 continue;
1324 }
1325
1326 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001327 // the two instructions and none of the instructions between the second
1328 // and first alias with the second, we can combine the second into the
1329 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001330 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1331 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001332 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001333 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001334 return MBBI;
1335 }
1336
1337 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001338 // between the two instructions and none of the instructions between the
1339 // first and the second alias with the first, we can combine the first
1340 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001341 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001342 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001343 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001344 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001345 return MBBI;
1346 }
1347 // Unable to combine these instructions due to interference in between.
1348 // Keep looking.
1349 }
1350 }
1351
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001352 // If the instruction wasn't a matching load or store. Stop searching if we
1353 // encounter a call instruction that might modify memory.
1354 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001355 return E;
1356
1357 // Update modified / uses register lists.
1358 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1359
1360 // Otherwise, if the base register is modified, we have no match, so
1361 // return early.
1362 if (ModifiedRegs[BaseReg])
1363 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001364
1365 // Update list of instructions that read/write memory.
1366 if (MI->mayLoadOrStore())
1367 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001368 }
1369 return E;
1370}
1371
1372MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001373AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1374 MachineBasicBlock::iterator Update,
1375 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001376 assert((Update->getOpcode() == AArch64::ADDXri ||
1377 Update->getOpcode() == AArch64::SUBXri) &&
1378 "Unexpected base register update instruction to merge!");
1379 MachineBasicBlock::iterator NextI = I;
1380 // Return the instruction following the merged instruction, which is
1381 // the instruction following our unmerged load. Unless that's the add/sub
1382 // instruction we're merging, in which case it's the one after that.
1383 if (++NextI == Update)
1384 ++NextI;
1385
1386 int Value = Update->getOperand(2).getImm();
1387 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001388 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001389 if (Update->getOpcode() == AArch64::SUBXri)
1390 Value = -Value;
1391
Chad Rosier2dfd3542015-09-23 13:51:44 +00001392 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1393 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001394 MachineInstrBuilder MIB;
1395 if (!isPairedLdSt(I)) {
1396 // Non-paired instruction.
1397 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1398 .addOperand(getLdStRegOp(Update))
1399 .addOperand(getLdStRegOp(I))
1400 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001401 .addImm(Value)
1402 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001403 } else {
1404 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001405 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001406 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1407 .addOperand(getLdStRegOp(Update))
1408 .addOperand(getLdStRegOp(I, 0))
1409 .addOperand(getLdStRegOp(I, 1))
1410 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001411 .addImm(Value / Scale)
1412 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001413 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001414 (void)MIB;
1415
Chad Rosier2dfd3542015-09-23 13:51:44 +00001416 if (IsPreIdx)
1417 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1418 else
1419 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001420 DEBUG(dbgs() << " Replacing instructions:\n ");
1421 DEBUG(I->print(dbgs()));
1422 DEBUG(dbgs() << " ");
1423 DEBUG(Update->print(dbgs()));
1424 DEBUG(dbgs() << " with instruction:\n ");
1425 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1426 DEBUG(dbgs() << "\n");
1427
1428 // Erase the old instructions for the block.
1429 I->eraseFromParent();
1430 Update->eraseFromParent();
1431
1432 return NextI;
1433}
1434
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001435bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1436 MachineInstr *MI,
1437 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001438 switch (MI->getOpcode()) {
1439 default:
1440 break;
1441 case AArch64::SUBXri:
1442 // Negate the offset for a SUB instruction.
1443 Offset *= -1;
1444 // FALLTHROUGH
1445 case AArch64::ADDXri:
1446 // Make sure it's a vanilla immediate operand, not a relocation or
1447 // anything else we can't handle.
1448 if (!MI->getOperand(2).isImm())
1449 break;
1450 // Watch out for 1 << 12 shifted value.
1451 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1452 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001453
1454 // The update instruction source and destination register must be the
1455 // same as the load/store base register.
1456 if (MI->getOperand(0).getReg() != BaseReg ||
1457 MI->getOperand(1).getReg() != BaseReg)
1458 break;
1459
1460 bool IsPairedInsn = isPairedLdSt(MemMI);
1461 int UpdateOffset = MI->getOperand(2).getImm();
1462 // For non-paired load/store instructions, the immediate must fit in a
1463 // signed 9-bit integer.
1464 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1465 break;
1466
1467 // For paired load/store instructions, the immediate must be a multiple of
1468 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1469 // integer.
1470 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001471 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001472 if (UpdateOffset % Scale != 0)
1473 break;
1474
1475 int ScaledOffset = UpdateOffset / Scale;
1476 if (ScaledOffset > 64 || ScaledOffset < -64)
1477 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001479
1480 // If we have a non-zero Offset, we check that it matches the amount
1481 // we're adding to the register.
1482 if (!Offset || Offset == MI->getOperand(2).getImm())
1483 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001484 break;
1485 }
1486 return false;
1487}
1488
1489MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001490 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001491 MachineBasicBlock::iterator E = I->getParent()->end();
1492 MachineInstr *MemMI = I;
1493 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001494
Chad Rosierf77e9092015-08-06 15:50:12 +00001495 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001496 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001497
Chad Rosierb7c5b912015-10-01 13:43:05 +00001498 // Scan forward looking for post-index opportunities. Updating instructions
1499 // can't be formed if the memory instruction doesn't have the offset we're
1500 // looking for.
1501 if (MIUnscaledOffset != UnscaledOffset)
1502 return E;
1503
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001504 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001505 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001506 bool IsPairedInsn = isPairedLdSt(MemMI);
1507 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1508 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1509 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1510 return E;
1511 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001512
Tim Northover3b0846e2014-05-24 12:50:23 +00001513 // Track which registers have been modified and used between the first insn
1514 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001515 ModifiedRegs.reset();
1516 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001517 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001518 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001519 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001520 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001521 if (MI->isDebugValue())
1522 continue;
1523
Chad Rosier35706ad2016-02-04 21:26:02 +00001524 // Now that we know this is a real instruction, count it.
1525 ++Count;
1526
Tim Northover3b0846e2014-05-24 12:50:23 +00001527 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001528 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001529 return MBBI;
1530
1531 // Update the status of what the instruction clobbered and used.
1532 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1533
1534 // Otherwise, if the base register is used or modified, we have no match, so
1535 // return early.
1536 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1537 return E;
1538 }
1539 return E;
1540}
1541
1542MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001543 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001544 MachineBasicBlock::iterator B = I->getParent()->begin();
1545 MachineBasicBlock::iterator E = I->getParent()->end();
1546 MachineInstr *MemMI = I;
1547 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001548
Chad Rosierf77e9092015-08-06 15:50:12 +00001549 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1550 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001551
1552 // If the load/store is the first instruction in the block, there's obviously
1553 // not any matching update. Ditto if the memory offset isn't zero.
1554 if (MBBI == B || Offset != 0)
1555 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001556 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001557 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001558 bool IsPairedInsn = isPairedLdSt(MemMI);
1559 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1560 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1561 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1562 return E;
1563 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001564
1565 // Track which registers have been modified and used between the first insn
1566 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001567 ModifiedRegs.reset();
1568 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001569 unsigned Count = 0;
1570 do {
1571 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001572 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001573
Geoff Berry173b14d2016-02-09 20:47:21 +00001574 // Don't count DBG_VALUE instructions towards the search limit.
1575 if (!MI->isDebugValue())
1576 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001577
Tim Northover3b0846e2014-05-24 12:50:23 +00001578 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001579 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001580 return MBBI;
1581
1582 // Update the status of what the instruction clobbered and used.
1583 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1584
1585 // Otherwise, if the base register is used or modified, we have no match, so
1586 // return early.
1587 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1588 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001589 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001590 return E;
1591}
1592
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001593bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1594 MachineBasicBlock::iterator &MBBI) {
1595 MachineInstr *MI = MBBI;
1596 // If this is a volatile load, don't mess with it.
1597 if (MI->hasOrderedMemoryRef())
1598 return false;
1599
1600 // Make sure this is a reg+imm.
1601 // FIXME: It is possible to extend it to handle reg+reg cases.
1602 if (!getLdStOffsetOp(MI).isImm())
1603 return false;
1604
Chad Rosier35706ad2016-02-04 21:26:02 +00001605 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001606 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001607 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001608 ++NumLoadsFromStoresPromoted;
1609 // Promote the load. Keeping the iterator straight is a
1610 // pain, so we let the merge routine tell us what the next instruction
1611 // is after it's done mucking about.
1612 MBBI = promoteLoadFromStore(MBBI, StoreI);
1613 return true;
1614 }
1615 return false;
1616}
1617
Chad Rosier24c46ad2016-02-09 18:10:20 +00001618bool AArch64LoadStoreOpt::isCandidateToMergeOrPair(MachineInstr *MI) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001619 // If this is a volatile load/store, don't mess with it.
1620 if (MI->hasOrderedMemoryRef())
1621 return false;
1622
1623 // Make sure this is a reg+imm (as opposed to an address reloc).
1624 if (!getLdStOffsetOp(MI).isImm())
1625 return false;
1626
Chad Rosiercc5d61f2016-02-09 20:44:41 +00001627 // Can't merge/pair if the instruction modifies the base register.
1628 // e.g., ldr x0, [x0]
1629 unsigned BaseReg = getLdStBaseOp(MI).getReg();
1630 if (MI->modifiesRegister(BaseReg, TRI))
1631 return false;
1632
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001633 // Check if this load/store has a hint to avoid pair formation.
1634 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1635 if (TII->isLdStPairSuppressed(MI))
1636 return false;
1637
Chad Rosier24c46ad2016-02-09 18:10:20 +00001638 return true;
1639}
1640
1641// Find narrow loads that can be converted into a single wider load with
1642// bitfield extract instructions. Also merge adjacent zero stores into a wider
1643// store.
1644bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1645 MachineBasicBlock::iterator &MBBI) {
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001646 assert((isNarrowLoad(MBBI) || isPromotableZeroStoreOpcode(MBBI)) &&
1647 "Expected narrow op.");
Chad Rosier24c46ad2016-02-09 18:10:20 +00001648 MachineInstr *MI = MBBI;
1649 MachineBasicBlock::iterator E = MI->getParent()->end();
1650
1651 if (!isCandidateToMergeOrPair(MI))
1652 return false;
1653
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001654 // For promotable zero stores, the stored value should be WZR.
1655 if (isPromotableZeroStoreOpcode(MI) &&
1656 getLdStRegOp(MI).getReg() != AArch64::WZR)
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001657 return false;
1658
Chad Rosier24c46ad2016-02-09 18:10:20 +00001659 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001660 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001661 MachineBasicBlock::iterator MergeMI =
1662 findMatchingInsn(MBBI, Flags, LdStLimit);
Chad Rosierd7363db2016-02-09 19:09:22 +00001663 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001664 if (isNarrowLoad(MI)) {
1665 ++NumNarrowLoadsPromoted;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001666 } else if (isPromotableZeroStoreInst(MI)) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001667 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001668 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001669 // Keeping the iterator straight is a pain, so we let the merge routine tell
1670 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001671 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001672 return true;
1673 }
1674 return false;
1675}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001676
Chad Rosier24c46ad2016-02-09 18:10:20 +00001677// Find loads and stores that can be merged into a single load or store pair
1678// instruction.
1679bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1680 MachineInstr *MI = MBBI;
1681 MachineBasicBlock::iterator E = MI->getParent()->end();
1682
1683 if (!isCandidateToMergeOrPair(MI))
1684 return false;
1685
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001686 // Early exit if the offset is not possible to match. (6 bits of positive
1687 // range, plus allow an extra one in case we find a later insn that matches
1688 // with Offset-1)
1689 bool IsUnscaled = isUnscaledLdSt(MI);
1690 int Offset = getLdStOffsetOp(MI).getImm();
1691 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1692 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1693 return false;
1694
Chad Rosier24c46ad2016-02-09 18:10:20 +00001695 // Look ahead up to LdStLimit instructions for a pairable instruction.
1696 LdStPairFlags Flags;
1697 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, Flags, LdStLimit);
1698 if (Paired != E) {
1699 ++NumPairCreated;
1700 if (isUnscaledLdSt(MI))
1701 ++NumUnscaledPairCreated;
1702 // Keeping the iterator straight is a pain, so we let the merge routine tell
1703 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001704 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1705 return true;
1706 }
1707 return false;
1708}
1709
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001710bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1711 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001712 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001713 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001714 // 1) Find loads that directly read from stores and promote them by
1715 // replacing with mov instructions. If the store is wider than the load,
1716 // the load will be replaced with a bitfield extract.
1717 // e.g.,
1718 // str w1, [x0, #4]
1719 // ldrh w2, [x0, #6]
1720 // ; becomes
1721 // str w1, [x0, #4]
1722 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001723 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001724 MBBI != E;) {
1725 MachineInstr *MI = MBBI;
1726 switch (MI->getOpcode()) {
1727 default:
1728 // Just move on to the next instruction.
1729 ++MBBI;
1730 break;
1731 // Scaled instructions.
1732 case AArch64::LDRBBui:
1733 case AArch64::LDRHHui:
1734 case AArch64::LDRWui:
1735 case AArch64::LDRXui:
1736 // Unscaled instructions.
1737 case AArch64::LDURBBi:
1738 case AArch64::LDURHHi:
1739 case AArch64::LDURWi:
1740 case AArch64::LDURXi: {
1741 if (tryToPromoteLoadFromStore(MBBI)) {
1742 Modified = true;
1743 break;
1744 }
1745 ++MBBI;
1746 break;
1747 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001748 }
1749 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001750 // 2) Find narrow loads that can be converted into a single wider load
1751 // with bitfield extract instructions.
1752 // e.g.,
1753 // ldrh w0, [x2]
1754 // ldrh w1, [x2, #2]
1755 // ; becomes
1756 // ldr w0, [x2]
1757 // ubfx w1, w0, #16, #16
1758 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001759 //
1760 // Also merge adjacent zero stores into a wider store.
1761 // e.g.,
1762 // strh wzr, [x0]
1763 // strh wzr, [x0, #2]
1764 // ; becomes
1765 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001766 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001767 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001768 MachineInstr *MI = MBBI;
1769 switch (MI->getOpcode()) {
1770 default:
1771 // Just move on to the next instruction.
1772 ++MBBI;
1773 break;
1774 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001775 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001776 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001777 case AArch64::LDRSBWui:
1778 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001779 case AArch64::STRBBui:
1780 case AArch64::STRHHui:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001781 case AArch64::STRWui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001782 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001783 case AArch64::LDURBBi:
1784 case AArch64::LDURHHi:
1785 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001786 case AArch64::LDURSHWi:
1787 case AArch64::STURBBi:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001788 case AArch64::STURHHi:
1789 case AArch64::STURWi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001790 if (tryToMergeLdStInst(MBBI)) {
1791 Modified = true;
1792 break;
1793 }
1794 ++MBBI;
1795 break;
1796 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001797 }
1798 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001799 // 3) Find loads and stores that can be merged into a single load or store
1800 // pair instruction.
1801 // e.g.,
1802 // ldr x0, [x2]
1803 // ldr x1, [x2, #8]
1804 // ; becomes
1805 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001806 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001807 MBBI != E;) {
1808 MachineInstr *MI = MBBI;
1809 switch (MI->getOpcode()) {
1810 default:
1811 // Just move on to the next instruction.
1812 ++MBBI;
1813 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001814 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001815 case AArch64::STRSui:
1816 case AArch64::STRDui:
1817 case AArch64::STRQui:
1818 case AArch64::STRXui:
1819 case AArch64::STRWui:
1820 case AArch64::LDRSui:
1821 case AArch64::LDRDui:
1822 case AArch64::LDRQui:
1823 case AArch64::LDRXui:
1824 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001825 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001826 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001827 case AArch64::STURSi:
1828 case AArch64::STURDi:
1829 case AArch64::STURQi:
1830 case AArch64::STURWi:
1831 case AArch64::STURXi:
1832 case AArch64::LDURSi:
1833 case AArch64::LDURDi:
1834 case AArch64::LDURQi:
1835 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001836 case AArch64::LDURXi:
1837 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001838 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001840 break;
1841 }
1842 ++MBBI;
1843 break;
1844 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001845 }
1846 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001847 // 4) Find base register updates that can be merged into the load or store
1848 // as a base-reg writeback.
1849 // e.g.,
1850 // ldr x0, [x2]
1851 // add x2, x2, #4
1852 // ; becomes
1853 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001854 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1855 MBBI != E;) {
1856 MachineInstr *MI = MBBI;
1857 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001858 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001859 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001860 switch (Opc) {
1861 default:
1862 // Just move on to the next instruction.
1863 ++MBBI;
1864 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001865 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001866 case AArch64::STRSui:
1867 case AArch64::STRDui:
1868 case AArch64::STRQui:
1869 case AArch64::STRXui:
1870 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001871 case AArch64::STRHHui:
1872 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001873 case AArch64::LDRSui:
1874 case AArch64::LDRDui:
1875 case AArch64::LDRQui:
1876 case AArch64::LDRXui:
1877 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001878 case AArch64::LDRHHui:
1879 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001880 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001881 case AArch64::STURSi:
1882 case AArch64::STURDi:
1883 case AArch64::STURQi:
1884 case AArch64::STURWi:
1885 case AArch64::STURXi:
1886 case AArch64::LDURSi:
1887 case AArch64::LDURDi:
1888 case AArch64::LDURQi:
1889 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001890 case AArch64::LDURXi:
1891 // Paired instructions.
1892 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001893 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001894 case AArch64::LDPDi:
1895 case AArch64::LDPQi:
1896 case AArch64::LDPWi:
1897 case AArch64::LDPXi:
1898 case AArch64::STPSi:
1899 case AArch64::STPDi:
1900 case AArch64::STPQi:
1901 case AArch64::STPWi:
1902 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001903 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001904 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001905 ++MBBI;
1906 break;
1907 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001908 // Look forward to try to form a post-index instruction. For example,
1909 // ldr x0, [x20]
1910 // add x20, x20, #32
1911 // merged into:
1912 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001913 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001914 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001915 if (Update != E) {
1916 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001917 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001918 Modified = true;
1919 ++NumPostFolded;
1920 break;
1921 }
1922 // Don't know how to handle pre/post-index versions, so move to the next
1923 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001924 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001925 ++MBBI;
1926 break;
1927 }
1928
1929 // Look back to try to find a pre-index instruction. For example,
1930 // add x0, x0, #8
1931 // ldr x1, [x0]
1932 // merged into:
1933 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001934 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001935 if (Update != E) {
1936 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001937 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001938 Modified = true;
1939 ++NumPreFolded;
1940 break;
1941 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001942 // The immediate in the load/store is scaled by the size of the memory
1943 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001944 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001945 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001946
Tim Northover3b0846e2014-05-24 12:50:23 +00001947 // Look forward to try to find a post-index instruction. For example,
1948 // ldr x1, [x0, #64]
1949 // add x0, x0, #64
1950 // merged into:
1951 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001952 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001953 if (Update != E) {
1954 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001955 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001956 Modified = true;
1957 ++NumPreFolded;
1958 break;
1959 }
1960
1961 // Nothing found. Just move to the next instruction.
1962 ++MBBI;
1963 break;
1964 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001965 }
1966 }
1967
1968 return Modified;
1969}
1970
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001971bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Chad Rosiercd2be7f2016-02-12 15:51:51 +00001972 bool ProfitableArch = Subtarget->isCortexA57() || Subtarget->isKryo();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001973 // FIXME: The benefit from converting narrow loads into a wider load could be
1974 // microarchitectural as it assumes that a single load with two bitfield
1975 // extracts is cheaper than two narrow loads. Currently, this conversion is
1976 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001977 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001978}
1979
Tim Northover3b0846e2014-05-24 12:50:23 +00001980bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001981 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1982 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1983 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001984
Chad Rosierbba881e2016-02-02 15:02:30 +00001985 // Resize the modified and used register bitfield trackers. We do this once
1986 // per function and then clear the bitfield each time we optimize a load or
1987 // store.
1988 ModifiedRegs.resize(TRI->getNumRegs());
1989 UsedRegs.resize(TRI->getNumRegs());
1990
Tim Northover3b0846e2014-05-24 12:50:23 +00001991 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001992 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001993 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001994 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001995
1996 return Modified;
1997}
1998
1999// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
2000// loads and stores near one another?
2001
Chad Rosier3f8b09d2016-02-09 19:42:19 +00002002// FIXME: When pairing store instructions it's very possible for this pass to
2003// hoist a store with a KILL marker above another use (without a KILL marker).
2004// The resulting IR is invalid, but nothing uses the KILL markers after this
2005// pass, so it's never caused a problem in practice.
2006
Chad Rosier43f5c842015-08-05 12:40:13 +00002007/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2008/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00002009FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2010 return new AArch64LoadStoreOpt();
2011}