blob: d07ef3cecccd367cb7cb59bbe68332a83925a870 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that performs load / store related peephole
11// optimizations. This pass should be run after register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000016#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "MCTargetDesc/AArch64AddressingModes.h"
18#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000019#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000020#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000021#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032using namespace llvm;
33
34#define DEBUG_TYPE "aarch64-ldst-opt"
35
Tim Northover3b0846e2014-05-24 12:50:23 +000036STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37STATISTIC(NumPostFolded, "Number of post-index updates folded");
38STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
Jun Bum Limc12c2792015-11-19 18:41:27 +000041STATISTIC(NumNarrowLoadsPromoted, "Number of narrow loads promoted");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000042STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000043STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000044
Chad Rosier35706ad2016-02-04 21:26:02 +000045// The LdStLimit limits how far we search for load/store pairs.
46static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000047 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000048
Chad Rosier35706ad2016-02-04 21:26:02 +000049// The UpdateLimit limits how far we search for update instructions when we form
50// pre-/post-index instructions.
51static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
52 cl::Hidden);
53
Chad Rosier96530b32015-08-05 13:44:51 +000054namespace llvm {
55void initializeAArch64LoadStoreOptPass(PassRegistry &);
56}
57
58#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
59
Tim Northover3b0846e2014-05-24 12:50:23 +000060namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000061
62typedef struct LdStPairFlags {
63 // If a matching instruction is found, MergeForward is set to true if the
64 // merge is to remove the first instruction and replace the second with
65 // a pair-wise insn, and false if the reverse is true.
66 bool MergeForward;
67
68 // SExtIdx gives the index of the result of the load pair that must be
69 // extended. The value of SExtIdx assumes that the paired load produces the
70 // value in this order: (I, returned iterator), i.e., -1 means no value has
71 // to be extended, 0 means I, and 1 means the returned iterator.
72 int SExtIdx;
73
74 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75
76 void setMergeForward(bool V = true) { MergeForward = V; }
77 bool getMergeForward() const { return MergeForward; }
78
79 void setSExtIdx(int V) { SExtIdx = V; }
80 int getSExtIdx() const { return SExtIdx; }
81
82} LdStPairFlags;
83
Tim Northover3b0846e2014-05-24 12:50:23 +000084struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000086 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000087 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
88 }
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 const AArch64InstrInfo *TII;
91 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000092 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
Chad Rosierbba881e2016-02-02 15:02:30 +000094 // Track which registers have been modified and used.
95 BitVector ModifiedRegs, UsedRegs;
96
Tim Northover3b0846e2014-05-24 12:50:23 +000097 // Scan the instructions looking for a load/store that can be combined
98 // with the current instruction into a load/store pair.
99 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000101 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +0000102 unsigned Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000103
104 // Scan the instructions looking for a store that writes to the address from
105 // which the current load instruction reads. Return true if one is found.
106 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
107 MachineBasicBlock::iterator &StoreI);
108
Chad Rosierb5933d72016-02-09 19:02:12 +0000109 // Merge the two instructions indicated into a wider instruction.
110 MachineBasicBlock::iterator
111 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000112 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000113 const LdStPairFlags &Flags);
114
Tim Northover3b0846e2014-05-24 12:50:23 +0000115 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000116 MachineBasicBlock::iterator
117 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000118 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000119 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000120
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000121 // Promote the load that reads directly from the address stored to.
122 MachineBasicBlock::iterator
123 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
124 MachineBasicBlock::iterator StoreI);
125
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 // Scan the instruction list to find a base register update that can
127 // be combined with the current instruction (a load or store) using
128 // pre or post indexed addressing with writeback. Scan forwards.
129 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000130 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000131 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000132
133 // Scan the instruction list to find a base register update that can
134 // be combined with the current instruction (a load or store) using
135 // pre or post indexed addressing with writeback. Scan backwards.
136 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000137 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000138
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000139 // Find an instruction that updates the base register of the ld/st
140 // instruction.
141 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
142 unsigned BaseReg, int Offset);
143
Chad Rosier2dfd3542015-09-23 13:51:44 +0000144 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000146 mergeUpdateInsn(MachineBasicBlock::iterator I,
147 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000148
Chad Rosier24c46ad2016-02-09 18:10:20 +0000149 // Is this a candidate for ld/st merging or pairing? For example, we don't
150 // touch volatiles or load/stores that have a hint to avoid pair formation.
151 bool isCandidateToMergeOrPair(MachineInstr *MI);
152
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000153 // Find and merge foldable ldr/str instructions.
154 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
155
Chad Rosier24c46ad2016-02-09 18:10:20 +0000156 // Find and pair ldr/str instructions.
157 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
158
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000159 // Find and promote load instructions which read directly from store.
160 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
161
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000162 // Check if converting two narrow loads into a single wider load with
163 // bitfield extracts could be enabled.
164 bool enableNarrowLdMerge(MachineFunction &Fn);
165
166 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000167
168 bool runOnMachineFunction(MachineFunction &Fn) override;
169
170 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000171 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000173};
174char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000175} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000176
Chad Rosier96530b32015-08-05 13:44:51 +0000177INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
178 AARCH64_LOAD_STORE_OPT_NAME, false, false)
179
Chad Rosier22eb7102015-08-06 17:37:18 +0000180static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 switch (Opc) {
182 default:
183 return false;
184 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000187 case AArch64::STURBBi:
188 case AArch64::STURHHi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000196 case AArch64::LDURSWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000197 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000198 case AArch64::LDURBBi:
199 case AArch64::LDURSBWi:
200 case AArch64::LDURSHWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000201 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000202 }
203}
204
Chad Rosier22eb7102015-08-06 17:37:18 +0000205static bool isUnscaledLdSt(MachineInstr *MI) {
206 return isUnscaledLdSt(MI->getOpcode());
207}
208
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000209static unsigned getBitExtrOpcode(MachineInstr *MI) {
210 switch (MI->getOpcode()) {
211 default:
212 llvm_unreachable("Unexpected opcode.");
213 case AArch64::LDRBBui:
214 case AArch64::LDURBBi:
215 case AArch64::LDRHHui:
216 case AArch64::LDURHHi:
217 return AArch64::UBFMWri;
218 case AArch64::LDRSBWui:
219 case AArch64::LDURSBWi:
220 case AArch64::LDRSHWui:
221 case AArch64::LDURSHWi:
222 return AArch64::SBFMWri;
223 }
224}
225
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000226static bool isNarrowStore(unsigned Opc) {
227 switch (Opc) {
228 default:
229 return false;
230 case AArch64::STRBBui:
231 case AArch64::STURBBi:
232 case AArch64::STRHHui:
233 case AArch64::STURHHi:
234 return true;
235 }
236}
237
238static bool isNarrowStore(MachineInstr *MI) {
239 return isNarrowStore(MI->getOpcode());
240}
241
Jun Bum Limc12c2792015-11-19 18:41:27 +0000242static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000243 switch (Opc) {
244 default:
245 return false;
246 case AArch64::LDRHHui:
247 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000248 case AArch64::LDRBBui:
249 case AArch64::LDURBBi:
250 case AArch64::LDRSHWui:
251 case AArch64::LDURSHWi:
252 case AArch64::LDRSBWui:
253 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000254 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000255 }
256}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000257
Jun Bum Limc12c2792015-11-19 18:41:27 +0000258static bool isNarrowLoad(MachineInstr *MI) {
259 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000260}
261
Chad 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;
385 case AArch64::LDRHHui:
386 case AArch64::LDRSHWui:
387 return AArch64::LDRWui;
388 case AArch64::LDURHHi:
389 case AArch64::LDURSHWi:
390 return AArch64::LDURWi;
391 case AArch64::LDRBBui:
392 case AArch64::LDRSBWui:
393 return AArch64::LDRHHui;
394 case AArch64::LDURBBi:
395 case AArch64::LDURSBWi:
396 return AArch64::LDURHHi;
397 }
398}
399
Tim Northover3b0846e2014-05-24 12:50:23 +0000400static unsigned getMatchingPairOpcode(unsigned Opc) {
401 switch (Opc) {
402 default:
403 llvm_unreachable("Opcode has no pairwise equivalent!");
404 case AArch64::STRSui:
405 case AArch64::STURSi:
406 return AArch64::STPSi;
407 case AArch64::STRDui:
408 case AArch64::STURDi:
409 return AArch64::STPDi;
410 case AArch64::STRQui:
411 case AArch64::STURQi:
412 return AArch64::STPQi;
413 case AArch64::STRWui:
414 case AArch64::STURWi:
415 return AArch64::STPWi;
416 case AArch64::STRXui:
417 case AArch64::STURXi:
418 return AArch64::STPXi;
419 case AArch64::LDRSui:
420 case AArch64::LDURSi:
421 return AArch64::LDPSi;
422 case AArch64::LDRDui:
423 case AArch64::LDURDi:
424 return AArch64::LDPDi;
425 case AArch64::LDRQui:
426 case AArch64::LDURQi:
427 return AArch64::LDPQi;
428 case AArch64::LDRWui:
429 case AArch64::LDURWi:
430 return AArch64::LDPWi;
431 case AArch64::LDRXui:
432 case AArch64::LDURXi:
433 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000434 case AArch64::LDRSWui:
435 case AArch64::LDURSWi:
436 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000437 }
438}
439
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000440static unsigned isMatchingStore(MachineInstr *LoadInst,
441 MachineInstr *StoreInst) {
442 unsigned LdOpc = LoadInst->getOpcode();
443 unsigned StOpc = StoreInst->getOpcode();
444 switch (LdOpc) {
445 default:
446 llvm_unreachable("Unsupported load instruction!");
447 case AArch64::LDRBBui:
448 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
449 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
450 case AArch64::LDURBBi:
451 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
452 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
453 case AArch64::LDRHHui:
454 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
455 StOpc == AArch64::STRXui;
456 case AArch64::LDURHHi:
457 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
458 StOpc == AArch64::STURXi;
459 case AArch64::LDRWui:
460 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
461 case AArch64::LDURWi:
462 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
463 case AArch64::LDRXui:
464 return StOpc == AArch64::STRXui;
465 case AArch64::LDURXi:
466 return StOpc == AArch64::STURXi;
467 }
468}
469
Tim Northover3b0846e2014-05-24 12:50:23 +0000470static unsigned getPreIndexedOpcode(unsigned Opc) {
471 switch (Opc) {
472 default:
473 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000474 case AArch64::STRSui:
475 return AArch64::STRSpre;
476 case AArch64::STRDui:
477 return AArch64::STRDpre;
478 case AArch64::STRQui:
479 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000480 case AArch64::STRBBui:
481 return AArch64::STRBBpre;
482 case AArch64::STRHHui:
483 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000484 case AArch64::STRWui:
485 return AArch64::STRWpre;
486 case AArch64::STRXui:
487 return AArch64::STRXpre;
488 case AArch64::LDRSui:
489 return AArch64::LDRSpre;
490 case AArch64::LDRDui:
491 return AArch64::LDRDpre;
492 case AArch64::LDRQui:
493 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000494 case AArch64::LDRBBui:
495 return AArch64::LDRBBpre;
496 case AArch64::LDRHHui:
497 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000498 case AArch64::LDRWui:
499 return AArch64::LDRWpre;
500 case AArch64::LDRXui:
501 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000502 case AArch64::LDRSWui:
503 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000504 case AArch64::LDPSi:
505 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000506 case AArch64::LDPSWi:
507 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000508 case AArch64::LDPDi:
509 return AArch64::LDPDpre;
510 case AArch64::LDPQi:
511 return AArch64::LDPQpre;
512 case AArch64::LDPWi:
513 return AArch64::LDPWpre;
514 case AArch64::LDPXi:
515 return AArch64::LDPXpre;
516 case AArch64::STPSi:
517 return AArch64::STPSpre;
518 case AArch64::STPDi:
519 return AArch64::STPDpre;
520 case AArch64::STPQi:
521 return AArch64::STPQpre;
522 case AArch64::STPWi:
523 return AArch64::STPWpre;
524 case AArch64::STPXi:
525 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 }
527}
528
529static unsigned getPostIndexedOpcode(unsigned Opc) {
530 switch (Opc) {
531 default:
532 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
533 case AArch64::STRSui:
534 return AArch64::STRSpost;
535 case AArch64::STRDui:
536 return AArch64::STRDpost;
537 case AArch64::STRQui:
538 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000539 case AArch64::STRBBui:
540 return AArch64::STRBBpost;
541 case AArch64::STRHHui:
542 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 case AArch64::STRWui:
544 return AArch64::STRWpost;
545 case AArch64::STRXui:
546 return AArch64::STRXpost;
547 case AArch64::LDRSui:
548 return AArch64::LDRSpost;
549 case AArch64::LDRDui:
550 return AArch64::LDRDpost;
551 case AArch64::LDRQui:
552 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000553 case AArch64::LDRBBui:
554 return AArch64::LDRBBpost;
555 case AArch64::LDRHHui:
556 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000557 case AArch64::LDRWui:
558 return AArch64::LDRWpost;
559 case AArch64::LDRXui:
560 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000561 case AArch64::LDRSWui:
562 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000563 case AArch64::LDPSi:
564 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000565 case AArch64::LDPSWi:
566 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 case AArch64::LDPDi:
568 return AArch64::LDPDpost;
569 case AArch64::LDPQi:
570 return AArch64::LDPQpost;
571 case AArch64::LDPWi:
572 return AArch64::LDPWpost;
573 case AArch64::LDPXi:
574 return AArch64::LDPXpost;
575 case AArch64::STPSi:
576 return AArch64::STPSpost;
577 case AArch64::STPDi:
578 return AArch64::STPDpost;
579 case AArch64::STPQi:
580 return AArch64::STPQpost;
581 case AArch64::STPWi:
582 return AArch64::STPWpost;
583 case AArch64::STPXi:
584 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000585 }
586}
587
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000588static bool isPairedLdSt(const MachineInstr *MI) {
589 switch (MI->getOpcode()) {
590 default:
591 return false;
592 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000593 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000594 case AArch64::LDPDi:
595 case AArch64::LDPQi:
596 case AArch64::LDPWi:
597 case AArch64::LDPXi:
598 case AArch64::STPSi:
599 case AArch64::STPDi:
600 case AArch64::STPQi:
601 case AArch64::STPWi:
602 case AArch64::STPXi:
603 return true;
604 }
605}
606
607static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
608 unsigned PairedRegOp = 0) {
609 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
610 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
611 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000612}
613
614static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000615 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
616 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000617}
618
619static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000620 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
621 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000622}
623
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000624static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
625 MachineInstr *StoreInst) {
626 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
627 int LoadSize = getMemScale(LoadInst);
628 int StoreSize = getMemScale(StoreInst);
629 int UnscaledStOffset = isUnscaledLdSt(StoreInst)
630 ? getLdStOffsetOp(StoreInst).getImm()
631 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
632 int UnscaledLdOffset = isUnscaledLdSt(LoadInst)
633 ? getLdStOffsetOp(LoadInst).getImm()
634 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
635 return (UnscaledStOffset <= UnscaledLdOffset) &&
636 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
637}
638
Tim Northover3b0846e2014-05-24 12:50:23 +0000639MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000640AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000641 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000642 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 MachineBasicBlock::iterator NextI = I;
644 ++NextI;
645 // If NextI is the second of the two instructions to be merged, we need
646 // to skip one further. Either way we merge will invalidate the iterator,
647 // and we don't need to scan the new instruction, as it's a pairwise
648 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000649 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000650 ++NextI;
651
Chad Rosierb5933d72016-02-09 19:02:12 +0000652 unsigned Opc = I->getOpcode();
Chad Rosier11eedc92016-02-09 19:17:18 +0000653 bool IsScaled = !isUnscaledLdSt(Opc);
654 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000655
Chad Rosier96a18a92015-07-21 17:42:04 +0000656 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000658 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000659 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000660 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000661 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000662 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000663 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000664
665 // Which register is Rt and which is Rt2 depends on the offset order.
666 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000667 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000668 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
669 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 Rt2MI = I;
671 } else {
672 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000673 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000675
James Molloy5b18b4c2015-10-23 10:41:38 +0000676 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000677 // Change the scaled offset from small to large type.
678 if (IsScaled) {
679 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
680 OffsetImm /= 2;
681 }
682
Chad Rosierc46ef882016-02-09 19:33:42 +0000683 DebugLoc DL = I->getDebugLoc();
684 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000685 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000686 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000687 // When merging small (< 32 bit) loads for big-endian targets, the order of
688 // the component parts gets swapped.
689 if (!Subtarget->isLittleEndian())
690 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000691 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000692 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000693 NewMemMI =
694 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
695 .addOperand(getLdStRegOp(RtNewDest))
696 .addOperand(BaseRegOp)
697 .addImm(OffsetImm)
698 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000699
700 DEBUG(
701 dbgs()
702 << "Creating the new load and extract. Replacing instructions:\n ");
703 DEBUG(I->print(dbgs()));
704 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000705 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000706 DEBUG(dbgs() << " with instructions:\n ");
707 DEBUG((NewMemMI)->print(dbgs()));
708
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000709 int Width = getMemScale(I) == 1 ? 8 : 16;
710 int LSBLow = 0;
711 int LSBHigh = Width;
712 int ImmsLow = LSBLow + Width - 1;
713 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000714 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000715 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000716 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000717 BitExtMI1 =
718 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
719 .addOperand(getLdStRegOp(Rt2MI))
720 .addReg(getLdStRegOp(RtNewDest).getReg())
721 .addImm(LSBHigh)
722 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000723 // Create the bitfield extract for low bits.
724 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
725 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000726 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000727 .addOperand(getLdStRegOp(RtMI))
728 .addReg(getLdStRegOp(RtNewDest).getReg())
729 .addImm(ImmsLow);
730 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000731 BitExtMI2 =
732 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
733 .addOperand(getLdStRegOp(RtMI))
734 .addReg(getLdStRegOp(RtNewDest).getReg())
735 .addImm(LSBLow)
736 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000737 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000738 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000739 // Create the bitfield extract for low bits.
740 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
741 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000742 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000743 .addOperand(getLdStRegOp(RtMI))
744 .addReg(getLdStRegOp(RtNewDest).getReg())
745 .addImm(ImmsLow);
746 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000747 BitExtMI1 =
748 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
749 .addOperand(getLdStRegOp(RtMI))
750 .addReg(getLdStRegOp(RtNewDest).getReg())
751 .addImm(LSBLow)
752 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000753 }
754
755 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000756 BitExtMI2 =
757 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
758 .addOperand(getLdStRegOp(Rt2MI))
759 .addReg(getLdStRegOp(RtNewDest).getReg())
760 .addImm(LSBHigh)
761 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000762 }
763 DEBUG(dbgs() << " ");
764 DEBUG((BitExtMI1)->print(dbgs()));
765 DEBUG(dbgs() << " ");
766 DEBUG((BitExtMI2)->print(dbgs()));
767 DEBUG(dbgs() << "\n");
768
769 // Erase the old instructions.
770 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000771 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000772 return NextI;
773 }
Chad Rosier11eedc92016-02-09 19:17:18 +0000774 assert(isNarrowStore(Opc) && "Expected narrow store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000775
Tim Northover3b0846e2014-05-24 12:50:23 +0000776 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000777 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000778 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000779 .addOperand(getLdStRegOp(I))
780 .addOperand(BaseRegOp)
781 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000782 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000783
Tim Northover3b0846e2014-05-24 12:50:23 +0000784 (void)MIB;
785
Chad Rosierb5933d72016-02-09 19:02:12 +0000786 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
787 DEBUG(I->print(dbgs()));
788 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000789 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000790 DEBUG(dbgs() << " with instruction:\n ");
791 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
792 DEBUG(dbgs() << "\n");
793
794 // Erase the old instructions.
795 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000796 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000797 return NextI;
798}
799
800MachineBasicBlock::iterator
801AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
802 MachineBasicBlock::iterator Paired,
803 const LdStPairFlags &Flags) {
804 MachineBasicBlock::iterator NextI = I;
805 ++NextI;
806 // If NextI is the second of the two instructions to be merged, we need
807 // to skip one further. Either way we merge will invalidate the iterator,
808 // and we don't need to scan the new instruction, as it's a pairwise
809 // instruction, which we're not considering for further action anyway.
810 if (NextI == Paired)
811 ++NextI;
812
813 int SExtIdx = Flags.getSExtIdx();
814 unsigned Opc =
815 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
816 bool IsUnscaled = isUnscaledLdSt(Opc);
817 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
818
819 bool MergeForward = Flags.getMergeForward();
820 // Insert our new paired instruction after whichever of the paired
821 // instructions MergeForward indicates.
822 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
823 // Also based on MergeForward is from where we copy the base register operand
824 // so we get the flags compatible with the input code.
825 const MachineOperand &BaseRegOp =
826 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
827
828 // Which register is Rt and which is Rt2 depends on the offset order.
829 MachineInstr *RtMI, *Rt2MI;
830 if (getLdStOffsetOp(I).getImm() ==
831 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
832 RtMI = Paired;
833 Rt2MI = I;
834 // Here we swapped the assumption made for SExtIdx.
835 // I.e., we turn ldp I, Paired into ldp Paired, I.
836 // Update the index accordingly.
837 if (SExtIdx != -1)
838 SExtIdx = (SExtIdx + 1) % 2;
839 } else {
840 RtMI = I;
841 Rt2MI = Paired;
842 }
843 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
844 // Handle Unscaled.
Chad Rosier87e33412016-02-09 20:18:07 +0000845 if (IsUnscaled) {
846 assert (!(OffsetImm % OffsetStride) && "Unscaled offset cannot be scaled.");
Chad Rosierb5933d72016-02-09 19:02:12 +0000847 OffsetImm /= OffsetStride;
Chad Rosier87e33412016-02-09 20:18:07 +0000848 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000849
850 // Construct the new instruction.
851 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000852 DebugLoc DL = I->getDebugLoc();
853 MachineBasicBlock *MBB = I->getParent();
854 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000855 .addOperand(getLdStRegOp(RtMI))
856 .addOperand(getLdStRegOp(Rt2MI))
857 .addOperand(BaseRegOp)
858 .addImm(OffsetImm);
859 // FIXME: Copy the mem operands from the source instructions. The MI scheduler
860 // needs these to reason about loads/stores.
861
862 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000863
864 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
865 DEBUG(I->print(dbgs()));
866 DEBUG(dbgs() << " ");
867 DEBUG(Paired->print(dbgs()));
868 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000869
870 if (SExtIdx != -1) {
871 // Generate the sign extension for the proper result of the ldp.
872 // I.e., with X1, that would be:
873 // %W1<def> = KILL %W1, %X1<imp-def>
874 // %X1<def> = SBFMXri %X1<kill>, 0, 31
875 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
876 // Right now, DstMO has the extended register, since it comes from an
877 // extended opcode.
878 unsigned DstRegX = DstMO.getReg();
879 // Get the W variant of that register.
880 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
881 // Update the result of LDP to use the W instead of the X variant.
882 DstMO.setReg(DstRegW);
883 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
884 DEBUG(dbgs() << "\n");
885 // Make the machine verifier happy by providing a definition for
886 // the X register.
887 // Insert this definition right after the generated LDP, i.e., before
888 // InsertionPoint.
889 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000890 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000891 .addReg(DstRegW)
892 .addReg(DstRegX, RegState::Define);
893 MIBKill->getOperand(2).setImplicit();
894 // Create the sign extension.
895 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000896 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000897 .addReg(DstRegX)
898 .addImm(0)
899 .addImm(31);
900 (void)MIBSXTW;
901 DEBUG(dbgs() << " Extend operand:\n ");
902 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
903 DEBUG(dbgs() << "\n");
904 } else {
905 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
906 DEBUG(dbgs() << "\n");
907 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000908
909 // Erase the old instructions.
910 I->eraseFromParent();
911 Paired->eraseFromParent();
912
913 return NextI;
914}
915
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000916MachineBasicBlock::iterator
917AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
918 MachineBasicBlock::iterator StoreI) {
919 MachineBasicBlock::iterator NextI = LoadI;
920 ++NextI;
921
922 int LoadSize = getMemScale(LoadI);
923 int StoreSize = getMemScale(StoreI);
924 unsigned LdRt = getLdStRegOp(LoadI).getReg();
925 unsigned StRt = getLdStRegOp(StoreI).getReg();
926 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
927
928 assert((IsStoreXReg ||
929 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
930 "Unexpected RegClass");
931
932 MachineInstr *BitExtMI;
933 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
934 // Remove the load, if the destination register of the loads is the same
935 // register for stored value.
936 if (StRt == LdRt && LoadSize == 8) {
937 DEBUG(dbgs() << "Remove load instruction:\n ");
938 DEBUG(LoadI->print(dbgs()));
939 DEBUG(dbgs() << "\n");
940 LoadI->eraseFromParent();
941 return NextI;
942 }
943 // Replace the load with a mov if the load and store are in the same size.
944 BitExtMI =
945 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
946 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
947 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
948 .addReg(StRt)
949 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
950 } else {
951 // FIXME: Currently we disable this transformation in big-endian targets as
952 // performance and correctness are verified only in little-endian.
953 if (!Subtarget->isLittleEndian())
954 return NextI;
955 bool IsUnscaled = isUnscaledLdSt(LoadI);
956 assert(IsUnscaled == isUnscaledLdSt(StoreI) && "Unsupported ld/st match");
957 assert(LoadSize <= StoreSize && "Invalid load size");
958 int UnscaledLdOffset = IsUnscaled
959 ? getLdStOffsetOp(LoadI).getImm()
960 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
961 int UnscaledStOffset = IsUnscaled
962 ? getLdStOffsetOp(StoreI).getImm()
963 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
964 int Width = LoadSize * 8;
965 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
966 int Imms = Immr + Width - 1;
967 unsigned DestReg = IsStoreXReg
968 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
969 &AArch64::GPR64RegClass)
970 : LdRt;
971
972 assert((UnscaledLdOffset >= UnscaledStOffset &&
973 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
974 "Invalid offset");
975
976 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
977 Imms = Immr + Width - 1;
978 if (UnscaledLdOffset == UnscaledStOffset) {
979 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
980 | ((Immr) << 6) // immr
981 | ((Imms) << 0) // imms
982 ;
983
984 BitExtMI =
985 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
986 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
987 DestReg)
988 .addReg(StRt)
989 .addImm(AndMaskEncoded);
990 } else {
991 BitExtMI =
992 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
993 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
994 DestReg)
995 .addReg(StRt)
996 .addImm(Immr)
997 .addImm(Imms);
998 }
999 }
1000
1001 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1002 DEBUG(StoreI->print(dbgs()));
1003 DEBUG(dbgs() << " ");
1004 DEBUG(LoadI->print(dbgs()));
1005 DEBUG(dbgs() << " with instructions:\n ");
1006 DEBUG(StoreI->print(dbgs()));
1007 DEBUG(dbgs() << " ");
1008 DEBUG((BitExtMI)->print(dbgs()));
1009 DEBUG(dbgs() << "\n");
1010
1011 // Erase the old instructions.
1012 LoadI->eraseFromParent();
1013 return NextI;
1014}
1015
Tim Northover3b0846e2014-05-24 12:50:23 +00001016/// trackRegDefsUses - Remember what registers the specified instruction uses
1017/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001018static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001019 BitVector &UsedRegs,
1020 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001021 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001022 if (MO.isRegMask())
1023 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1024
1025 if (!MO.isReg())
1026 continue;
1027 unsigned Reg = MO.getReg();
1028 if (MO.isDef()) {
1029 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1030 ModifiedRegs.set(*AI);
1031 } else {
1032 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1033 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1034 UsedRegs.set(*AI);
1035 }
1036 }
1037}
1038
1039static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001040 // Convert the byte-offset used by unscaled into an "element" offset used
1041 // by the scaled pair load/store instructions.
Renato Golin6274e522016-02-05 12:14:30 +00001042 if (IsUnscaled)
Chad Rosier3dd0e942015-08-18 16:20:03 +00001043 Offset /= OffsetStride;
Renato Golin6274e522016-02-05 12:14:30 +00001044
Chad Rosier3dd0e942015-08-18 16:20:03 +00001045 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001046}
1047
1048// Do alignment, specialized to power of 2 and for signed ints,
1049// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001050// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001051// FIXME: Move this function to include/MathExtras.h?
1052static int alignTo(int Num, int PowOf2) {
1053 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1054}
1055
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001056static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1057 const AArch64InstrInfo *TII) {
1058 // One of the instructions must modify memory.
1059 if (!MIa->mayStore() && !MIb->mayStore())
1060 return false;
1061
1062 // Both instructions must be memory operations.
1063 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1064 return false;
1065
1066 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1067}
1068
1069static bool mayAlias(MachineInstr *MIa,
1070 SmallVectorImpl<MachineInstr *> &MemInsns,
1071 const AArch64InstrInfo *TII) {
1072 for (auto &MIb : MemInsns)
1073 if (mayAlias(MIa, MIb, TII))
1074 return true;
1075
1076 return false;
1077}
1078
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001079bool AArch64LoadStoreOpt::findMatchingStore(
1080 MachineBasicBlock::iterator I, unsigned Limit,
1081 MachineBasicBlock::iterator &StoreI) {
1082 MachineBasicBlock::iterator E = I->getParent()->begin();
1083 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001084 MachineInstr *LoadMI = I;
1085 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001086
1087 // Track which registers have been modified and used between the first insn
1088 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001089 ModifiedRegs.reset();
1090 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001091
Chad Rosier1142f3c2016-02-02 15:22:55 +00001092 // FIXME: We miss the case where the matching store is the first instruction
1093 // in the basic block.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001094 for (unsigned Count = 0; MBBI != E && Count < Limit;) {
1095 --MBBI;
1096 MachineInstr *MI = MBBI;
1097 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1098 // optimization by changing how far we scan.
1099 if (MI->isDebugValue())
1100 continue;
1101 // Now that we know this is a real instruction, count it.
1102 ++Count;
1103
1104 // If the load instruction reads directly from the address to which the
1105 // store instruction writes and the stored value is not modified, we can
1106 // promote the load. Since we do not handle stores with pre-/post-index,
1107 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001108 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001109 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001110 isLdOffsetInRangeOfSt(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001111 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1112 StoreI = MBBI;
1113 return true;
1114 }
1115
1116 if (MI->isCall())
1117 return false;
1118
1119 // Update modified / uses register lists.
1120 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1121
1122 // Otherwise, if the base register is modified, we have no match, so
1123 // return early.
1124 if (ModifiedRegs[BaseReg])
1125 return false;
1126
1127 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001128 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001129 return false;
1130 }
1131 return false;
1132}
1133
Tim Northover3b0846e2014-05-24 12:50:23 +00001134/// findMatchingInsn - Scan the instructions looking for a load/store that can
1135/// be combined with the current instruction into a load/store pair.
1136MachineBasicBlock::iterator
1137AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001138 LdStPairFlags &Flags, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001139 MachineBasicBlock::iterator E = I->getParent()->end();
1140 MachineBasicBlock::iterator MBBI = I;
1141 MachineInstr *FirstMI = I;
1142 ++MBBI;
1143
Matthias Braunfa3872e2015-05-18 20:27:55 +00001144 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001145 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +00001146 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001147 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1148 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1149 int Offset = getLdStOffsetOp(FirstMI).getImm();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001150 bool IsNarrowStore = isNarrowStore(Opc);
1151
1152 // For narrow stores, find only the case where the stored value is WZR.
1153 if (IsNarrowStore && Reg != AArch64::WZR)
1154 return E;
Tim Northover3b0846e2014-05-24 12:50:23 +00001155
1156 // Early exit if the first instruction modifies the base register.
1157 // e.g., ldr x0, [x0]
Tim Northover3b0846e2014-05-24 12:50:23 +00001158 if (FirstMI->modifiesRegister(BaseReg, TRI))
1159 return E;
Chad Rosiercaed6db2015-08-10 17:17:19 +00001160
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001161 // Early exit if the offset is not possible to match. (6 bits of positive
Chad Rosiercaed6db2015-08-10 17:17:19 +00001162 // range, plus allow an extra one in case we find a later insn that matches
1163 // with Offset-1)
Chad Rosierf11d0402015-10-01 18:17:12 +00001164 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001165 if (!(isNarrowLoad(Opc) || IsNarrowStore) &&
1166 !inBoundsForPair(IsUnscaled, Offset, OffsetStride))
Tim Northover3b0846e2014-05-24 12:50:23 +00001167 return E;
1168
1169 // Track which registers have been modified and used between the first insn
1170 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001171 ModifiedRegs.reset();
1172 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001173
1174 // Remember any instructions that read/write memory between FirstMI and MI.
1175 SmallVector<MachineInstr *, 4> MemInsns;
1176
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1178 MachineInstr *MI = MBBI;
1179 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1180 // optimization by changing how far we scan.
1181 if (MI->isDebugValue())
1182 continue;
1183
1184 // Now that we know this is a real instruction, count it.
1185 ++Count;
1186
Renato Golin6274e522016-02-05 12:14:30 +00001187 bool CanMergeOpc = Opc == MI->getOpcode();
Chad Rosier18896c02016-02-04 16:01:40 +00001188 Flags.setSExtIdx(-1);
Renato Golin6274e522016-02-05 12:14:30 +00001189 if (!CanMergeOpc) {
1190 bool IsValidLdStrOpc;
1191 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
1192 assert(IsValidLdStrOpc &&
1193 "Given Opc should be a Load or Store with an immediate");
1194 // Opc will be the first instruction in the pair.
1195 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
1196 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
1197 }
1198
1199 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001200 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001201 // If we've found another instruction with the same opcode, check to see
1202 // if the base and offset are compatible with our starting instruction.
1203 // These instructions all have scaled immediate operands, so we just
1204 // check for +1/-1. Make sure to check the new instruction offset is
1205 // actually an immediate and not a symbolic reference destined for
1206 // a relocation.
1207 //
1208 // Pairwise instructions have a 7-bit signed offset field. Single insns
1209 // have a 12-bit unsigned offset field. To be a valid combine, the
1210 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001211 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1212 int MIOffset = getLdStOffsetOp(MI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001213 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1214 (Offset + OffsetStride == MIOffset))) {
1215 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1216 // If this is a volatile load/store that otherwise matched, stop looking
1217 // as something is going on that we don't have enough information to
1218 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1219 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1220 return E;
1221 // If the resultant immediate offset of merging these instructions
1222 // is out of range for a pairwise instruction, bail and keep looking.
Renato Golin6274e522016-02-05 12:14:30 +00001223 bool MIIsUnscaled = isUnscaledLdSt(MI);
Jun Bum Limc12c2792015-11-19 18:41:27 +00001224 bool IsNarrowLoad = isNarrowLoad(MI->getOpcode());
1225 if (!IsNarrowLoad &&
Renato Golin6274e522016-02-05 12:14:30 +00001226 !inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001227 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001228 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001229 continue;
1230 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001231
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001232 if (IsNarrowLoad || IsNarrowStore) {
1233 // If the alignment requirements of the scaled wide load/store
1234 // instruction can't express the offset of the scaled narrow
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001235 // input, bail and keep looking.
1236 if (!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) {
1237 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1238 MemInsns.push_back(MI);
1239 continue;
1240 }
1241 } else {
1242 // If the alignment requirements of the paired (scaled) instruction
1243 // can't express the offset of the unscaled input, bail and keep
1244 // looking.
1245 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1246 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1247 MemInsns.push_back(MI);
1248 continue;
1249 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001250 }
1251 // If the destination register of the loads is the same register, bail
1252 // and keep looking. A load-pair instruction with both destination
1253 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001254 // For narrow stores, allow only when the stored value is the same
1255 // (i.e., WZR).
1256 if ((MayLoad && Reg == getLdStRegOp(MI).getReg()) ||
1257 (IsNarrowStore && Reg != getLdStRegOp(MI).getReg())) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001258 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001259 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001260 continue;
1261 }
1262
1263 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001264 // the two instructions and none of the instructions between the second
1265 // and first alias with the second, we can combine the second into the
1266 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001267 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1268 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001269 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001270 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001271 return MBBI;
1272 }
1273
1274 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001275 // between the two instructions and none of the instructions between the
1276 // first and the second alias with the first, we can combine the first
1277 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001278 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001279 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001280 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001281 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001282 return MBBI;
1283 }
1284 // Unable to combine these instructions due to interference in between.
1285 // Keep looking.
1286 }
1287 }
1288
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001289 // If the instruction wasn't a matching load or store. Stop searching if we
1290 // encounter a call instruction that might modify memory.
1291 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001292 return E;
1293
1294 // Update modified / uses register lists.
1295 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1296
1297 // Otherwise, if the base register is modified, we have no match, so
1298 // return early.
1299 if (ModifiedRegs[BaseReg])
1300 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001301
1302 // Update list of instructions that read/write memory.
1303 if (MI->mayLoadOrStore())
1304 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001305 }
1306 return E;
1307}
1308
1309MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001310AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1311 MachineBasicBlock::iterator Update,
1312 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001313 assert((Update->getOpcode() == AArch64::ADDXri ||
1314 Update->getOpcode() == AArch64::SUBXri) &&
1315 "Unexpected base register update instruction to merge!");
1316 MachineBasicBlock::iterator NextI = I;
1317 // Return the instruction following the merged instruction, which is
1318 // the instruction following our unmerged load. Unless that's the add/sub
1319 // instruction we're merging, in which case it's the one after that.
1320 if (++NextI == Update)
1321 ++NextI;
1322
1323 int Value = Update->getOperand(2).getImm();
1324 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001325 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001326 if (Update->getOpcode() == AArch64::SUBXri)
1327 Value = -Value;
1328
Chad Rosier2dfd3542015-09-23 13:51:44 +00001329 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1330 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001331 MachineInstrBuilder MIB;
1332 if (!isPairedLdSt(I)) {
1333 // Non-paired instruction.
1334 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1335 .addOperand(getLdStRegOp(Update))
1336 .addOperand(getLdStRegOp(I))
1337 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001338 .addImm(Value)
1339 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001340 } else {
1341 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001342 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001343 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1344 .addOperand(getLdStRegOp(Update))
1345 .addOperand(getLdStRegOp(I, 0))
1346 .addOperand(getLdStRegOp(I, 1))
1347 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001348 .addImm(Value / Scale)
1349 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001350 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001351 (void)MIB;
1352
Chad Rosier2dfd3542015-09-23 13:51:44 +00001353 if (IsPreIdx)
1354 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1355 else
1356 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001357 DEBUG(dbgs() << " Replacing instructions:\n ");
1358 DEBUG(I->print(dbgs()));
1359 DEBUG(dbgs() << " ");
1360 DEBUG(Update->print(dbgs()));
1361 DEBUG(dbgs() << " with instruction:\n ");
1362 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1363 DEBUG(dbgs() << "\n");
1364
1365 // Erase the old instructions for the block.
1366 I->eraseFromParent();
1367 Update->eraseFromParent();
1368
1369 return NextI;
1370}
1371
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001372bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1373 MachineInstr *MI,
1374 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001375 switch (MI->getOpcode()) {
1376 default:
1377 break;
1378 case AArch64::SUBXri:
1379 // Negate the offset for a SUB instruction.
1380 Offset *= -1;
1381 // FALLTHROUGH
1382 case AArch64::ADDXri:
1383 // Make sure it's a vanilla immediate operand, not a relocation or
1384 // anything else we can't handle.
1385 if (!MI->getOperand(2).isImm())
1386 break;
1387 // Watch out for 1 << 12 shifted value.
1388 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1389 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001390
1391 // The update instruction source and destination register must be the
1392 // same as the load/store base register.
1393 if (MI->getOperand(0).getReg() != BaseReg ||
1394 MI->getOperand(1).getReg() != BaseReg)
1395 break;
1396
1397 bool IsPairedInsn = isPairedLdSt(MemMI);
1398 int UpdateOffset = MI->getOperand(2).getImm();
1399 // For non-paired load/store instructions, the immediate must fit in a
1400 // signed 9-bit integer.
1401 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1402 break;
1403
1404 // For paired load/store instructions, the immediate must be a multiple of
1405 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1406 // integer.
1407 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001408 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001409 if (UpdateOffset % Scale != 0)
1410 break;
1411
1412 int ScaledOffset = UpdateOffset / Scale;
1413 if (ScaledOffset > 64 || ScaledOffset < -64)
1414 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001415 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001416
1417 // If we have a non-zero Offset, we check that it matches the amount
1418 // we're adding to the register.
1419 if (!Offset || Offset == MI->getOperand(2).getImm())
1420 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001421 break;
1422 }
1423 return false;
1424}
1425
1426MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001427 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001428 MachineBasicBlock::iterator E = I->getParent()->end();
1429 MachineInstr *MemMI = I;
1430 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001431
Chad Rosierf77e9092015-08-06 15:50:12 +00001432 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001433 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001434
Chad Rosierb7c5b912015-10-01 13:43:05 +00001435 // Scan forward looking for post-index opportunities. Updating instructions
1436 // can't be formed if the memory instruction doesn't have the offset we're
1437 // looking for.
1438 if (MIUnscaledOffset != UnscaledOffset)
1439 return E;
1440
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001441 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001442 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001443 bool IsPairedInsn = isPairedLdSt(MemMI);
1444 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1445 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1446 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1447 return E;
1448 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001449
Tim Northover3b0846e2014-05-24 12:50:23 +00001450 // Track which registers have been modified and used between the first insn
1451 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001452 ModifiedRegs.reset();
1453 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001454 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001455 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001456 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001457 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001458 if (MI->isDebugValue())
1459 continue;
1460
Chad Rosier35706ad2016-02-04 21:26:02 +00001461 // Now that we know this is a real instruction, count it.
1462 ++Count;
1463
Tim Northover3b0846e2014-05-24 12:50:23 +00001464 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001465 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001466 return MBBI;
1467
1468 // Update the status of what the instruction clobbered and used.
1469 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1470
1471 // Otherwise, if the base register is used or modified, we have no match, so
1472 // return early.
1473 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1474 return E;
1475 }
1476 return E;
1477}
1478
1479MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001480 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001481 MachineBasicBlock::iterator B = I->getParent()->begin();
1482 MachineBasicBlock::iterator E = I->getParent()->end();
1483 MachineInstr *MemMI = I;
1484 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001485
Chad Rosierf77e9092015-08-06 15:50:12 +00001486 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1487 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001488
1489 // If the load/store is the first instruction in the block, there's obviously
1490 // not any matching update. Ditto if the memory offset isn't zero.
1491 if (MBBI == B || Offset != 0)
1492 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001493 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001494 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001495 bool IsPairedInsn = isPairedLdSt(MemMI);
1496 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1497 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1498 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1499 return E;
1500 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001501
1502 // Track which registers have been modified and used between the first insn
1503 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001504 ModifiedRegs.reset();
1505 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001506 --MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001507 for (unsigned Count = 0; MBBI != B && Count < Limit; --MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001508 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001509 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001510 if (MI->isDebugValue())
1511 continue;
1512
Chad Rosier35706ad2016-02-04 21:26:02 +00001513 // Now that we know this is a real instruction, count it.
1514 ++Count;
1515
Tim Northover3b0846e2014-05-24 12:50:23 +00001516 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001517 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001518 return MBBI;
1519
1520 // Update the status of what the instruction clobbered and used.
1521 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1522
1523 // Otherwise, if the base register is used or modified, we have no match, so
1524 // return early.
1525 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1526 return E;
1527 }
1528 return E;
1529}
1530
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001531bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1532 MachineBasicBlock::iterator &MBBI) {
1533 MachineInstr *MI = MBBI;
1534 // If this is a volatile load, don't mess with it.
1535 if (MI->hasOrderedMemoryRef())
1536 return false;
1537
1538 // Make sure this is a reg+imm.
1539 // FIXME: It is possible to extend it to handle reg+reg cases.
1540 if (!getLdStOffsetOp(MI).isImm())
1541 return false;
1542
Chad Rosier35706ad2016-02-04 21:26:02 +00001543 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001544 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001545 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001546 ++NumLoadsFromStoresPromoted;
1547 // Promote the load. Keeping the iterator straight is a
1548 // pain, so we let the merge routine tell us what the next instruction
1549 // is after it's done mucking about.
1550 MBBI = promoteLoadFromStore(MBBI, StoreI);
1551 return true;
1552 }
1553 return false;
1554}
1555
Chad Rosier24c46ad2016-02-09 18:10:20 +00001556bool AArch64LoadStoreOpt::isCandidateToMergeOrPair(MachineInstr *MI) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001557 // If this is a volatile load/store, don't mess with it.
1558 if (MI->hasOrderedMemoryRef())
1559 return false;
1560
1561 // Make sure this is a reg+imm (as opposed to an address reloc).
1562 if (!getLdStOffsetOp(MI).isImm())
1563 return false;
1564
1565 // Check if this load/store has a hint to avoid pair formation.
1566 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1567 if (TII->isLdStPairSuppressed(MI))
1568 return false;
1569
Chad Rosier24c46ad2016-02-09 18:10:20 +00001570 return true;
1571}
1572
1573// Find narrow loads that can be converted into a single wider load with
1574// bitfield extract instructions. Also merge adjacent zero stores into a wider
1575// store.
1576bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1577 MachineBasicBlock::iterator &MBBI) {
1578 assert((isNarrowLoad(MBBI) || isNarrowStore(MBBI)) && "Expected narrow op.");
1579 MachineInstr *MI = MBBI;
1580 MachineBasicBlock::iterator E = MI->getParent()->end();
1581
1582 if (!isCandidateToMergeOrPair(MI))
1583 return false;
1584
1585 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001586 LdStPairFlags Flags;
Chad Rosierd7363db2016-02-09 19:09:22 +00001587 MachineBasicBlock::iterator MergeMI = findMatchingInsn(MBBI, Flags, LdStLimit);
1588 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001589 if (isNarrowLoad(MI)) {
1590 ++NumNarrowLoadsPromoted;
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001591 } else if (isNarrowStore(MI)) {
1592 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001593 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001594 // Keeping the iterator straight is a pain, so we let the merge routine tell
1595 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001596 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001597 return true;
1598 }
1599 return false;
1600}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001601
Chad Rosier24c46ad2016-02-09 18:10:20 +00001602// Find loads and stores that can be merged into a single load or store pair
1603// instruction.
1604bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1605 MachineInstr *MI = MBBI;
1606 MachineBasicBlock::iterator E = MI->getParent()->end();
1607
1608 if (!isCandidateToMergeOrPair(MI))
1609 return false;
1610
1611 // Look ahead up to LdStLimit instructions for a pairable instruction.
1612 LdStPairFlags Flags;
1613 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, Flags, LdStLimit);
1614 if (Paired != E) {
1615 ++NumPairCreated;
1616 if (isUnscaledLdSt(MI))
1617 ++NumUnscaledPairCreated;
1618 // Keeping the iterator straight is a pain, so we let the merge routine tell
1619 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001620 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1621 return true;
1622 }
1623 return false;
1624}
1625
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001626bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1627 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001628 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001629 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001630 // 1) Find loads that directly read from stores and promote them by
1631 // replacing with mov instructions. If the store is wider than the load,
1632 // the load will be replaced with a bitfield extract.
1633 // e.g.,
1634 // str w1, [x0, #4]
1635 // ldrh w2, [x0, #6]
1636 // ; becomes
1637 // str w1, [x0, #4]
1638 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001639 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001640 MBBI != E;) {
1641 MachineInstr *MI = MBBI;
1642 switch (MI->getOpcode()) {
1643 default:
1644 // Just move on to the next instruction.
1645 ++MBBI;
1646 break;
1647 // Scaled instructions.
1648 case AArch64::LDRBBui:
1649 case AArch64::LDRHHui:
1650 case AArch64::LDRWui:
1651 case AArch64::LDRXui:
1652 // Unscaled instructions.
1653 case AArch64::LDURBBi:
1654 case AArch64::LDURHHi:
1655 case AArch64::LDURWi:
1656 case AArch64::LDURXi: {
1657 if (tryToPromoteLoadFromStore(MBBI)) {
1658 Modified = true;
1659 break;
1660 }
1661 ++MBBI;
1662 break;
1663 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001664 }
1665 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001666 // 2) Find narrow loads that can be converted into a single wider load
1667 // with bitfield extract instructions.
1668 // e.g.,
1669 // ldrh w0, [x2]
1670 // ldrh w1, [x2, #2]
1671 // ; becomes
1672 // ldr w0, [x2]
1673 // ubfx w1, w0, #16, #16
1674 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001675 //
1676 // Also merge adjacent zero stores into a wider store.
1677 // e.g.,
1678 // strh wzr, [x0]
1679 // strh wzr, [x0, #2]
1680 // ; becomes
1681 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001682 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001683 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001684 MachineInstr *MI = MBBI;
1685 switch (MI->getOpcode()) {
1686 default:
1687 // Just move on to the next instruction.
1688 ++MBBI;
1689 break;
1690 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001691 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001692 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001693 case AArch64::LDRSBWui:
1694 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001695 case AArch64::STRBBui:
1696 case AArch64::STRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001697 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001698 case AArch64::LDURBBi:
1699 case AArch64::LDURHHi:
1700 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001701 case AArch64::LDURSHWi:
1702 case AArch64::STURBBi:
1703 case AArch64::STURHHi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001704 if (tryToMergeLdStInst(MBBI)) {
1705 Modified = true;
1706 break;
1707 }
1708 ++MBBI;
1709 break;
1710 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001711 }
1712 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001713 // 3) Find loads and stores that can be merged into a single load or store
1714 // pair instruction.
1715 // e.g.,
1716 // ldr x0, [x2]
1717 // ldr x1, [x2, #8]
1718 // ; becomes
1719 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001720 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001721 MBBI != E;) {
1722 MachineInstr *MI = MBBI;
1723 switch (MI->getOpcode()) {
1724 default:
1725 // Just move on to the next instruction.
1726 ++MBBI;
1727 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001728 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001729 case AArch64::STRSui:
1730 case AArch64::STRDui:
1731 case AArch64::STRQui:
1732 case AArch64::STRXui:
1733 case AArch64::STRWui:
1734 case AArch64::LDRSui:
1735 case AArch64::LDRDui:
1736 case AArch64::LDRQui:
1737 case AArch64::LDRXui:
1738 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001739 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001740 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001741 case AArch64::STURSi:
1742 case AArch64::STURDi:
1743 case AArch64::STURQi:
1744 case AArch64::STURWi:
1745 case AArch64::STURXi:
1746 case AArch64::LDURSi:
1747 case AArch64::LDURDi:
1748 case AArch64::LDURQi:
1749 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001750 case AArch64::LDURXi:
1751 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001752 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001753 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001754 break;
1755 }
1756 ++MBBI;
1757 break;
1758 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001759 }
1760 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001761 // 4) Find base register updates that can be merged into the load or store
1762 // as a base-reg writeback.
1763 // e.g.,
1764 // ldr x0, [x2]
1765 // add x2, x2, #4
1766 // ; becomes
1767 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001768 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1769 MBBI != E;) {
1770 MachineInstr *MI = MBBI;
1771 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001772 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001773 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001774 switch (Opc) {
1775 default:
1776 // Just move on to the next instruction.
1777 ++MBBI;
1778 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001779 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001780 case AArch64::STRSui:
1781 case AArch64::STRDui:
1782 case AArch64::STRQui:
1783 case AArch64::STRXui:
1784 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001785 case AArch64::STRHHui:
1786 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001787 case AArch64::LDRSui:
1788 case AArch64::LDRDui:
1789 case AArch64::LDRQui:
1790 case AArch64::LDRXui:
1791 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001792 case AArch64::LDRHHui:
1793 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001794 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001795 case AArch64::STURSi:
1796 case AArch64::STURDi:
1797 case AArch64::STURQi:
1798 case AArch64::STURWi:
1799 case AArch64::STURXi:
1800 case AArch64::LDURSi:
1801 case AArch64::LDURDi:
1802 case AArch64::LDURQi:
1803 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001804 case AArch64::LDURXi:
1805 // Paired instructions.
1806 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001807 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001808 case AArch64::LDPDi:
1809 case AArch64::LDPQi:
1810 case AArch64::LDPWi:
1811 case AArch64::LDPXi:
1812 case AArch64::STPSi:
1813 case AArch64::STPDi:
1814 case AArch64::STPQi:
1815 case AArch64::STPWi:
1816 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001817 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001818 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001819 ++MBBI;
1820 break;
1821 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001822 // Look forward to try to form a post-index instruction. For example,
1823 // ldr x0, [x20]
1824 // add x20, x20, #32
1825 // merged into:
1826 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001827 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001828 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001829 if (Update != E) {
1830 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001831 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001832 Modified = true;
1833 ++NumPostFolded;
1834 break;
1835 }
1836 // Don't know how to handle pre/post-index versions, so move to the next
1837 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001838 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 ++MBBI;
1840 break;
1841 }
1842
1843 // Look back to try to find a pre-index instruction. For example,
1844 // add x0, x0, #8
1845 // ldr x1, [x0]
1846 // merged into:
1847 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001848 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001849 if (Update != E) {
1850 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001851 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001852 Modified = true;
1853 ++NumPreFolded;
1854 break;
1855 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001856 // The immediate in the load/store is scaled by the size of the memory
1857 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001858 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001859 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001860
Tim Northover3b0846e2014-05-24 12:50:23 +00001861 // Look forward to try to find a post-index instruction. For example,
1862 // ldr x1, [x0, #64]
1863 // add x0, x0, #64
1864 // merged into:
1865 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001866 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001867 if (Update != E) {
1868 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001869 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001870 Modified = true;
1871 ++NumPreFolded;
1872 break;
1873 }
1874
1875 // Nothing found. Just move to the next instruction.
1876 ++MBBI;
1877 break;
1878 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001879 }
1880 }
1881
1882 return Modified;
1883}
1884
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001885bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001886 bool ProfitableArch = Subtarget->isCortexA57();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001887 // FIXME: The benefit from converting narrow loads into a wider load could be
1888 // microarchitectural as it assumes that a single load with two bitfield
1889 // extracts is cheaper than two narrow loads. Currently, this conversion is
1890 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001891 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001892}
1893
Tim Northover3b0846e2014-05-24 12:50:23 +00001894bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001895 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1896 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1897 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001898
Chad Rosierbba881e2016-02-02 15:02:30 +00001899 // Resize the modified and used register bitfield trackers. We do this once
1900 // per function and then clear the bitfield each time we optimize a load or
1901 // store.
1902 ModifiedRegs.resize(TRI->getNumRegs());
1903 UsedRegs.resize(TRI->getNumRegs());
1904
Tim Northover3b0846e2014-05-24 12:50:23 +00001905 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001906 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001908 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001909
1910 return Modified;
1911}
1912
1913// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1914// loads and stores near one another?
1915
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001916// FIXME: When pairing store instructions it's very possible for this pass to
1917// hoist a store with a KILL marker above another use (without a KILL marker).
1918// The resulting IR is invalid, but nothing uses the KILL markers after this
1919// pass, so it's never caused a problem in practice.
1920
Chad Rosier43f5c842015-08-05 12:40:13 +00001921/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1922/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001923FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1924 return new AArch64LoadStoreOpt();
1925}