blob: 3156bb4469638a6a5416bad39c0b48f414d688ab [file] [log] [blame]
Eugene Zelenko96d933d2017-07-25 23:51:02 +00001//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that performs load / store related peephole
10// optimizations. This pass should be run after register allocation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000015#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "MCTargetDesc/AArch64AddressingModes.h"
17#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000018#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000020#include "llvm/ADT/StringRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/iterator_range.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000022#include "llvm/Analysis/AliasAnalysis.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000024#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstr.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000028#include "llvm/CodeGen/MachineOperand.h"
Florian Hahnd2692552019-12-21 14:47:08 +010029#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000030#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000031#include "llvm/IR/DebugLoc.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/Pass.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Florian Hahn17554b82019-12-11 09:59:18 +000036#include "llvm/Support/DebugCounter.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000037#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000039#include <cassert>
40#include <cstdint>
Florian Hahn17554b82019-12-11 09:59:18 +000041#include <functional>
Eugene Zelenko11f69072017-01-25 00:29:26 +000042#include <iterator>
43#include <limits>
44
Tim Northover3b0846e2014-05-24 12:50:23 +000045using namespace llvm;
46
47#define DEBUG_TYPE "aarch64-ldst-opt"
48
Tim Northover3b0846e2014-05-24 12:50:23 +000049STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
50STATISTIC(NumPostFolded, "Number of post-index updates folded");
51STATISTIC(NumPreFolded, "Number of pre-index updates folded");
52STATISTIC(NumUnscaledPairCreated,
53 "Number of load/store from unscaled generated");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000054STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000055STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000056
Florian Hahn17554b82019-12-11 09:59:18 +000057DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
58 "Controls which pairs are considered for renaming");
59
Chad Rosier35706ad2016-02-04 21:26:02 +000060// The LdStLimit limits how far we search for load/store pairs.
61static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000062 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000063
Chad Rosier35706ad2016-02-04 21:26:02 +000064// The UpdateLimit limits how far we search for update instructions when we form
65// pre-/post-index instructions.
66static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
67 cl::Hidden);
68
Chad Rosier96530b32015-08-05 13:44:51 +000069#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
70
Tim Northover3b0846e2014-05-24 12:50:23 +000071namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000072
Eugene Zelenko96d933d2017-07-25 23:51:02 +000073using LdStPairFlags = struct LdStPairFlags {
Chad Rosier96a18a92015-07-21 17:42:04 +000074 // If a matching instruction is found, MergeForward is set to true if the
75 // merge is to remove the first instruction and replace the second with
76 // a pair-wise insn, and false if the reverse is true.
Eugene Zelenko11f69072017-01-25 00:29:26 +000077 bool MergeForward = false;
Chad Rosier96a18a92015-07-21 17:42:04 +000078
79 // SExtIdx gives the index of the result of the load pair that must be
80 // extended. The value of SExtIdx assumes that the paired load produces the
81 // value in this order: (I, returned iterator), i.e., -1 means no value has
82 // to be extended, 0 means I, and 1 means the returned iterator.
Eugene Zelenko11f69072017-01-25 00:29:26 +000083 int SExtIdx = -1;
Chad Rosier96a18a92015-07-21 17:42:04 +000084
Florian Hahn17554b82019-12-11 09:59:18 +000085 // If not none, RenameReg can be used to rename the result register of the
86 // first store in a pair. Currently this only works when merging stores
87 // forward.
88 Optional<MCPhysReg> RenameReg = None;
89
Eugene Zelenko11f69072017-01-25 00:29:26 +000090 LdStPairFlags() = default;
Chad Rosier96a18a92015-07-21 17:42:04 +000091
92 void setMergeForward(bool V = true) { MergeForward = V; }
93 bool getMergeForward() const { return MergeForward; }
94
95 void setSExtIdx(int V) { SExtIdx = V; }
96 int getSExtIdx() const { return SExtIdx; }
Florian Hahn17554b82019-12-11 09:59:18 +000097
98 void setRenameReg(MCPhysReg R) { RenameReg = R; }
99 void clearRenameReg() { RenameReg = None; }
100 Optional<MCPhysReg> getRenameReg() const { return RenameReg; }
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000101};
Chad Rosier96a18a92015-07-21 17:42:04 +0000102
Tim Northover3b0846e2014-05-24 12:50:23 +0000103struct AArch64LoadStoreOpt : public MachineFunctionPass {
104 static char ID;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000105
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000106 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +0000107 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
108 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000109
Chad Rosiera69dcb62017-03-17 14:19:55 +0000110 AliasAnalysis *AA;
Tim Northover3b0846e2014-05-24 12:50:23 +0000111 const AArch64InstrInfo *TII;
112 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000113 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +0000114
Jun Bum Lim47aece12018-04-27 18:44:37 +0000115 // Track which register units have been modified and used.
116 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
Florian Hahn17554b82019-12-11 09:59:18 +0000117 LiveRegUnits DefinedInBB;
Chad Rosierbba881e2016-02-02 15:02:30 +0000118
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000119 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiera69dcb62017-03-17 14:19:55 +0000120 AU.addRequired<AAResultsWrapperPass>();
121 MachineFunctionPass::getAnalysisUsage(AU);
122 }
123
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 // Scan the instructions looking for a load/store that can be combined
125 // with the current instruction into a load/store pair.
126 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000127 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000128 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +0000129 unsigned Limit,
130 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000131
132 // Scan the instructions looking for a store that writes to the address from
133 // which the current load instruction reads. Return true if one is found.
134 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
135 MachineBasicBlock::iterator &StoreI);
136
Chad Rosierd6daac42016-11-07 15:27:22 +0000137 // Merge the two instructions indicated into a wider narrow store instruction.
Chad Rosierb5933d72016-02-09 19:02:12 +0000138 MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000139 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
140 MachineBasicBlock::iterator MergeMI,
141 const LdStPairFlags &Flags);
Chad Rosierb5933d72016-02-09 19:02:12 +0000142
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000144 MachineBasicBlock::iterator
145 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000146 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000147 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000148
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000149 // Promote the load that reads directly from the address stored to.
150 MachineBasicBlock::iterator
151 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
152 MachineBasicBlock::iterator StoreI);
153
Tim Northover3b0846e2014-05-24 12:50:23 +0000154 // Scan the instruction list to find a base register update that can
155 // be combined with the current instruction (a load or store) using
156 // pre or post indexed addressing with writeback. Scan forwards.
157 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000158 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000159 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000160
161 // Scan the instruction list to find a base register update that can
162 // be combined with the current instruction (a load or store) using
163 // pre or post indexed addressing with writeback. Scan backwards.
164 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000165 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000166
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000167 // Find an instruction that updates the base register of the ld/st
168 // instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000169 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000170 unsigned BaseReg, int Offset);
171
Chad Rosier2dfd3542015-09-23 13:51:44 +0000172 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000174 mergeUpdateInsn(MachineBasicBlock::iterator I,
175 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000176
Chad Rosierd6daac42016-11-07 15:27:22 +0000177 // Find and merge zero store instructions.
178 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000179
Chad Rosier24c46ad2016-02-09 18:10:20 +0000180 // Find and pair ldr/str instructions.
181 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
182
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000183 // Find and promote load instructions which read directly from store.
184 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
185
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000186 // Find and merge a base register updates before or after a ld/st instruction.
187 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
188
Chad Rosierd6daac42016-11-07 15:27:22 +0000189 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000190
191 bool runOnMachineFunction(MachineFunction &Fn) override;
192
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000193 MachineFunctionProperties getRequiredProperties() const override {
194 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000195 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000196 }
197
Mehdi Amini117296c2016-10-01 02:56:57 +0000198 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000199};
Eugene Zelenko11f69072017-01-25 00:29:26 +0000200
Tim Northover3b0846e2014-05-24 12:50:23 +0000201char AArch64LoadStoreOpt::ID = 0;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000202
203} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000204
Chad Rosier96530b32015-08-05 13:44:51 +0000205INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
206 AARCH64_LOAD_STORE_OPT_NAME, false, false)
207
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000208static bool isNarrowStore(unsigned Opc) {
209 switch (Opc) {
210 default:
211 return false;
212 case AArch64::STRBBui:
213 case AArch64::STURBBi:
214 case AArch64::STRHHui:
215 case AArch64::STURHHi:
216 return true;
217 }
218}
219
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000220// These instruction set memory tag and either keep memory contents unchanged or
221// set it to zero, ignoring the address part of the source register.
222static bool isTagStore(const MachineInstr &MI) {
223 switch (MI.getOpcode()) {
224 default:
225 return false;
226 case AArch64::STGOffset:
227 case AArch64::STZGOffset:
228 case AArch64::ST2GOffset:
229 case AArch64::STZ2GOffset:
230 return true;
231 }
232}
233
Quentin Colombet66b61632015-03-06 22:42:10 +0000234static unsigned getMatchingNonSExtOpcode(unsigned Opc,
235 bool *IsValidLdStrOpc = nullptr) {
236 if (IsValidLdStrOpc)
237 *IsValidLdStrOpc = true;
238 switch (Opc) {
239 default:
240 if (IsValidLdStrOpc)
241 *IsValidLdStrOpc = false;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000242 return std::numeric_limits<unsigned>::max();
Quentin Colombet66b61632015-03-06 22:42:10 +0000243 case AArch64::STRDui:
244 case AArch64::STURDi:
245 case AArch64::STRQui:
246 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000247 case AArch64::STRBBui:
248 case AArch64::STURBBi:
249 case AArch64::STRHHui:
250 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000251 case AArch64::STRWui:
252 case AArch64::STURWi:
253 case AArch64::STRXui:
254 case AArch64::STURXi:
255 case AArch64::LDRDui:
256 case AArch64::LDURDi:
257 case AArch64::LDRQui:
258 case AArch64::LDURQi:
259 case AArch64::LDRWui:
260 case AArch64::LDURWi:
261 case AArch64::LDRXui:
262 case AArch64::LDURXi:
263 case AArch64::STRSui:
264 case AArch64::STURSi:
265 case AArch64::LDRSui:
266 case AArch64::LDURSi:
267 return Opc;
268 case AArch64::LDRSWui:
269 return AArch64::LDRWui;
270 case AArch64::LDURSWi:
271 return AArch64::LDURWi;
272 }
273}
274
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000275static unsigned getMatchingWideOpcode(unsigned Opc) {
276 switch (Opc) {
277 default:
278 llvm_unreachable("Opcode has no wide equivalent!");
279 case AArch64::STRBBui:
280 return AArch64::STRHHui;
281 case AArch64::STRHHui:
282 return AArch64::STRWui;
283 case AArch64::STURBBi:
284 return AArch64::STURHHi;
285 case AArch64::STURHHi:
286 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000287 case AArch64::STURWi:
288 return AArch64::STURXi;
289 case AArch64::STRWui:
290 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000291 }
292}
293
Tim Northover3b0846e2014-05-24 12:50:23 +0000294static unsigned getMatchingPairOpcode(unsigned Opc) {
295 switch (Opc) {
296 default:
297 llvm_unreachable("Opcode has no pairwise equivalent!");
298 case AArch64::STRSui:
299 case AArch64::STURSi:
300 return AArch64::STPSi;
301 case AArch64::STRDui:
302 case AArch64::STURDi:
303 return AArch64::STPDi;
304 case AArch64::STRQui:
305 case AArch64::STURQi:
306 return AArch64::STPQi;
307 case AArch64::STRWui:
308 case AArch64::STURWi:
309 return AArch64::STPWi;
310 case AArch64::STRXui:
311 case AArch64::STURXi:
312 return AArch64::STPXi;
313 case AArch64::LDRSui:
314 case AArch64::LDURSi:
315 return AArch64::LDPSi;
316 case AArch64::LDRDui:
317 case AArch64::LDURDi:
318 return AArch64::LDPDi;
319 case AArch64::LDRQui:
320 case AArch64::LDURQi:
321 return AArch64::LDPQi;
322 case AArch64::LDRWui:
323 case AArch64::LDURWi:
324 return AArch64::LDPWi;
325 case AArch64::LDRXui:
326 case AArch64::LDURXi:
327 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000328 case AArch64::LDRSWui:
329 case AArch64::LDURSWi:
330 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000331 }
332}
333
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000334static unsigned isMatchingStore(MachineInstr &LoadInst,
335 MachineInstr &StoreInst) {
336 unsigned LdOpc = LoadInst.getOpcode();
337 unsigned StOpc = StoreInst.getOpcode();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000338 switch (LdOpc) {
339 default:
340 llvm_unreachable("Unsupported load instruction!");
341 case AArch64::LDRBBui:
342 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
343 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
344 case AArch64::LDURBBi:
345 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
346 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
347 case AArch64::LDRHHui:
348 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
349 StOpc == AArch64::STRXui;
350 case AArch64::LDURHHi:
351 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
352 StOpc == AArch64::STURXi;
353 case AArch64::LDRWui:
354 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
355 case AArch64::LDURWi:
356 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
357 case AArch64::LDRXui:
358 return StOpc == AArch64::STRXui;
359 case AArch64::LDURXi:
360 return StOpc == AArch64::STURXi;
361 }
362}
363
Tim Northover3b0846e2014-05-24 12:50:23 +0000364static unsigned getPreIndexedOpcode(unsigned Opc) {
Chad Rosier14fc82a2017-08-04 16:44:06 +0000365 // FIXME: We don't currently support creating pre-indexed loads/stores when
366 // the load or store is the unscaled version. If we decide to perform such an
367 // optimization in the future the cases for the unscaled loads/stores will
368 // need to be added here.
Tim Northover3b0846e2014-05-24 12:50:23 +0000369 switch (Opc) {
370 default:
371 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000372 case AArch64::STRSui:
373 return AArch64::STRSpre;
374 case AArch64::STRDui:
375 return AArch64::STRDpre;
376 case AArch64::STRQui:
377 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000378 case AArch64::STRBBui:
379 return AArch64::STRBBpre;
380 case AArch64::STRHHui:
381 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000382 case AArch64::STRWui:
383 return AArch64::STRWpre;
384 case AArch64::STRXui:
385 return AArch64::STRXpre;
386 case AArch64::LDRSui:
387 return AArch64::LDRSpre;
388 case AArch64::LDRDui:
389 return AArch64::LDRDpre;
390 case AArch64::LDRQui:
391 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000392 case AArch64::LDRBBui:
393 return AArch64::LDRBBpre;
394 case AArch64::LDRHHui:
395 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000396 case AArch64::LDRWui:
397 return AArch64::LDRWpre;
398 case AArch64::LDRXui:
399 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000400 case AArch64::LDRSWui:
401 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000402 case AArch64::LDPSi:
403 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000404 case AArch64::LDPSWi:
405 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000406 case AArch64::LDPDi:
407 return AArch64::LDPDpre;
408 case AArch64::LDPQi:
409 return AArch64::LDPQpre;
410 case AArch64::LDPWi:
411 return AArch64::LDPWpre;
412 case AArch64::LDPXi:
413 return AArch64::LDPXpre;
414 case AArch64::STPSi:
415 return AArch64::STPSpre;
416 case AArch64::STPDi:
417 return AArch64::STPDpre;
418 case AArch64::STPQi:
419 return AArch64::STPQpre;
420 case AArch64::STPWi:
421 return AArch64::STPWpre;
422 case AArch64::STPXi:
423 return AArch64::STPXpre;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000424 case AArch64::STGOffset:
425 return AArch64::STGPreIndex;
426 case AArch64::STZGOffset:
427 return AArch64::STZGPreIndex;
428 case AArch64::ST2GOffset:
429 return AArch64::ST2GPreIndex;
430 case AArch64::STZ2GOffset:
431 return AArch64::STZ2GPreIndex;
432 case AArch64::STGPi:
433 return AArch64::STGPpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000434 }
435}
436
437static unsigned getPostIndexedOpcode(unsigned Opc) {
438 switch (Opc) {
439 default:
440 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
441 case AArch64::STRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000442 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000443 return AArch64::STRSpost;
444 case AArch64::STRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000445 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000446 return AArch64::STRDpost;
447 case AArch64::STRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000448 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000450 case AArch64::STRBBui:
451 return AArch64::STRBBpost;
452 case AArch64::STRHHui:
453 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000454 case AArch64::STRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000455 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 return AArch64::STRWpost;
457 case AArch64::STRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000458 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000459 return AArch64::STRXpost;
460 case AArch64::LDRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000461 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000462 return AArch64::LDRSpost;
463 case AArch64::LDRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000464 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000465 return AArch64::LDRDpost;
466 case AArch64::LDRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000467 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000468 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000469 case AArch64::LDRBBui:
470 return AArch64::LDRBBpost;
471 case AArch64::LDRHHui:
472 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000473 case AArch64::LDRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000474 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000475 return AArch64::LDRWpost;
476 case AArch64::LDRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000477 case AArch64::LDURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000478 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000479 case AArch64::LDRSWui:
480 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000481 case AArch64::LDPSi:
482 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000483 case AArch64::LDPSWi:
484 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000485 case AArch64::LDPDi:
486 return AArch64::LDPDpost;
487 case AArch64::LDPQi:
488 return AArch64::LDPQpost;
489 case AArch64::LDPWi:
490 return AArch64::LDPWpost;
491 case AArch64::LDPXi:
492 return AArch64::LDPXpost;
493 case AArch64::STPSi:
494 return AArch64::STPSpost;
495 case AArch64::STPDi:
496 return AArch64::STPDpost;
497 case AArch64::STPQi:
498 return AArch64::STPQpost;
499 case AArch64::STPWi:
500 return AArch64::STPWpost;
501 case AArch64::STPXi:
502 return AArch64::STPXpost;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000503 case AArch64::STGOffset:
504 return AArch64::STGPostIndex;
505 case AArch64::STZGOffset:
506 return AArch64::STZGPostIndex;
507 case AArch64::ST2GOffset:
508 return AArch64::ST2GPostIndex;
509 case AArch64::STZ2GOffset:
510 return AArch64::STZ2GPostIndex;
511 case AArch64::STGPi:
512 return AArch64::STGPpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000513 }
514}
515
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000516static bool isPairedLdSt(const MachineInstr &MI) {
517 switch (MI.getOpcode()) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000518 default:
519 return false;
520 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000521 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000522 case AArch64::LDPDi:
523 case AArch64::LDPQi:
524 case AArch64::LDPWi:
525 case AArch64::LDPXi:
526 case AArch64::STPSi:
527 case AArch64::STPDi:
528 case AArch64::STPQi:
529 case AArch64::STPWi:
530 case AArch64::STPXi:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000531 case AArch64::STGPi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000532 return true;
533 }
534}
535
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000536// Returns the scale and offset range of pre/post indexed variants of MI.
537static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
538 int &MinOffset, int &MaxOffset) {
539 bool IsPaired = isPairedLdSt(MI);
540 bool IsTagStore = isTagStore(MI);
541 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
542 // as in the "unsigned offset" variant.
543 // All other pre/post indexed ldst instructions are unscaled.
Jay Foad97ca7c22019-12-11 10:29:23 +0000544 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000545
546 if (IsPaired) {
547 MinOffset = -64;
548 MaxOffset = 63;
549 } else {
550 MinOffset = -256;
551 MaxOffset = 255;
552 }
553}
554
Florian Hahn17554b82019-12-11 09:59:18 +0000555static MachineOperand &getLdStRegOp(MachineInstr &MI,
556 unsigned PairedRegOp = 0) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000557 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
558 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000559 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000560}
561
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000562static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000563 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000564 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000565}
566
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000567static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000568 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000569 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000570}
571
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000572static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
573 MachineInstr &StoreInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000574 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000575 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000576 int LoadSize = TII->getMemScale(LoadInst);
577 int StoreSize = TII->getMemScale(StoreInst);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000578 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000579 ? getLdStOffsetOp(StoreInst).getImm()
580 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000581 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000582 ? getLdStOffsetOp(LoadInst).getImm()
583 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
584 return (UnscaledStOffset <= UnscaledLdOffset) &&
585 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
586}
587
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000588static bool isPromotableZeroStoreInst(MachineInstr &MI) {
Chad Rosierd6daac42016-11-07 15:27:22 +0000589 unsigned Opc = MI.getOpcode();
590 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
591 isNarrowStore(Opc)) &&
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000592 getLdStRegOp(MI).getReg() == AArch64::WZR;
593}
594
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000595static bool isPromotableLoadFromStore(MachineInstr &MI) {
596 switch (MI.getOpcode()) {
597 default:
598 return false;
599 // Scaled instructions.
600 case AArch64::LDRBBui:
601 case AArch64::LDRHHui:
602 case AArch64::LDRWui:
603 case AArch64::LDRXui:
604 // Unscaled instructions.
605 case AArch64::LDURBBi:
606 case AArch64::LDURHHi:
607 case AArch64::LDURWi:
608 case AArch64::LDURXi:
609 return true;
610 }
611}
612
613static bool isMergeableLdStUpdate(MachineInstr &MI) {
614 unsigned Opc = MI.getOpcode();
615 switch (Opc) {
616 default:
617 return false;
618 // Scaled instructions.
619 case AArch64::STRSui:
620 case AArch64::STRDui:
621 case AArch64::STRQui:
622 case AArch64::STRXui:
623 case AArch64::STRWui:
624 case AArch64::STRHHui:
625 case AArch64::STRBBui:
626 case AArch64::LDRSui:
627 case AArch64::LDRDui:
628 case AArch64::LDRQui:
629 case AArch64::LDRXui:
630 case AArch64::LDRWui:
631 case AArch64::LDRHHui:
632 case AArch64::LDRBBui:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000633 case AArch64::STGOffset:
634 case AArch64::STZGOffset:
635 case AArch64::ST2GOffset:
636 case AArch64::STZ2GOffset:
637 case AArch64::STGPi:
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000638 // Unscaled instructions.
639 case AArch64::STURSi:
640 case AArch64::STURDi:
641 case AArch64::STURQi:
642 case AArch64::STURWi:
643 case AArch64::STURXi:
644 case AArch64::LDURSi:
645 case AArch64::LDURDi:
646 case AArch64::LDURQi:
647 case AArch64::LDURWi:
648 case AArch64::LDURXi:
649 // Paired instructions.
650 case AArch64::LDPSi:
651 case AArch64::LDPSWi:
652 case AArch64::LDPDi:
653 case AArch64::LDPQi:
654 case AArch64::LDPWi:
655 case AArch64::LDPXi:
656 case AArch64::STPSi:
657 case AArch64::STPDi:
658 case AArch64::STPQi:
659 case AArch64::STPWi:
660 case AArch64::STPXi:
661 // Make sure this is a reg+imm (as opposed to an address reloc).
662 if (!getLdStOffsetOp(MI).isImm())
663 return false;
664
665 return true;
666 }
667}
668
Tim Northover3b0846e2014-05-24 12:50:23 +0000669MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000670AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
671 MachineBasicBlock::iterator MergeMI,
672 const LdStPairFlags &Flags) {
673 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
674 "Expected promotable zero stores.");
675
Tim Northover3b0846e2014-05-24 12:50:23 +0000676 MachineBasicBlock::iterator NextI = I;
677 ++NextI;
678 // If NextI is the second of the two instructions to be merged, we need
679 // to skip one further. Either way we merge will invalidate the iterator,
680 // and we don't need to scan the new instruction, as it's a pairwise
681 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000682 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000683 ++NextI;
684
Chad Rosierb5933d72016-02-09 19:02:12 +0000685 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000686 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000687 int OffsetStride = IsScaled ? 1 : TII->getMemScale(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000688
Chad Rosier96a18a92015-07-21 17:42:04 +0000689 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000690 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000691 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000692 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000693 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000694 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000695 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000696 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000697
698 // Which register is Rt and which is Rt2 depends on the offset order.
Davide Italiano5df60662016-11-07 19:11:25 +0000699 MachineInstr *RtMI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000700 if (getLdStOffsetOp(*I).getImm() ==
Davide Italiano5df60662016-11-07 19:11:25 +0000701 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000702 RtMI = &*MergeMI;
Davide Italiano5df60662016-11-07 19:11:25 +0000703 else
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000704 RtMI = &*I;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000705
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000706 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000707 // Change the scaled offset from small to large type.
708 if (IsScaled) {
709 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
710 OffsetImm /= 2;
711 }
712
Chad Rosierd6daac42016-11-07 15:27:22 +0000713 // Construct the new instruction.
Chad Rosierc46ef882016-02-09 19:33:42 +0000714 DebugLoc DL = I->getDebugLoc();
715 MachineBasicBlock *MBB = I->getParent();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000716 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000717 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000718 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Diana Picus116bbab2017-01-13 09:58:52 +0000719 .add(BaseRegOp)
Chad Rosierb5933d72016-02-09 19:02:12 +0000720 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000721 .cloneMergedMemRefs({&*I, &*MergeMI})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000722 .setMIFlags(I->mergeFlagsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000723 (void)MIB;
724
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000725 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
726 LLVM_DEBUG(I->print(dbgs()));
727 LLVM_DEBUG(dbgs() << " ");
728 LLVM_DEBUG(MergeMI->print(dbgs()));
729 LLVM_DEBUG(dbgs() << " with instruction:\n ");
730 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
731 LLVM_DEBUG(dbgs() << "\n");
Chad Rosierb5933d72016-02-09 19:02:12 +0000732
733 // Erase the old instructions.
734 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000735 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000736 return NextI;
737}
738
Florian Hahn17554b82019-12-11 09:59:18 +0000739// Apply Fn to all instructions between MI and the beginning of the block, until
740// a def for DefReg is reached. Returns true, iff Fn returns true for all
741// visited instructions. Stop after visiting Limit iterations.
742static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg,
743 const TargetRegisterInfo *TRI, unsigned Limit,
744 std::function<bool(MachineInstr &, bool)> &Fn) {
745 auto MBB = MI.getParent();
746 for (MachineBasicBlock::reverse_iterator I = MI.getReverseIterator(),
747 E = MBB->rend();
748 I != E; I++) {
749 if (!Limit)
750 return false;
751 --Limit;
752
753 bool isDef = any_of(I->operands(), [DefReg, TRI](MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000754 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000755 TRI->regsOverlap(MOP.getReg(), DefReg);
756 });
757 if (!Fn(*I, isDef))
758 return false;
759 if (isDef)
760 break;
761 }
762 return true;
763}
764
765static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
766 const TargetRegisterInfo *TRI) {
767
768 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
769 if (MOP.isReg() && MOP.isKill())
770 Units.removeReg(MOP.getReg());
771
772 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
773 if (MOP.isReg() && !MOP.isKill())
774 Units.addReg(MOP.getReg());
775}
776
Chad Rosierb5933d72016-02-09 19:02:12 +0000777MachineBasicBlock::iterator
778AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
779 MachineBasicBlock::iterator Paired,
780 const LdStPairFlags &Flags) {
781 MachineBasicBlock::iterator NextI = I;
782 ++NextI;
783 // If NextI is the second of the two instructions to be merged, we need
784 // to skip one further. Either way we merge will invalidate the iterator,
785 // and we don't need to scan the new instruction, as it's a pairwise
786 // instruction, which we're not considering for further action anyway.
787 if (NextI == Paired)
788 ++NextI;
789
790 int SExtIdx = Flags.getSExtIdx();
791 unsigned Opc =
792 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000793 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000794 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
Chad Rosierb5933d72016-02-09 19:02:12 +0000795
796 bool MergeForward = Flags.getMergeForward();
Florian Hahn17554b82019-12-11 09:59:18 +0000797
798 Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
799 if (MergeForward && RenameReg) {
800 MCRegister RegToRename = getLdStRegOp(*I).getReg();
801 DefinedInBB.addReg(*RenameReg);
802
803 // Return the sub/super register for RenameReg, matching the size of
804 // OriginalReg.
805 auto GetMatchingSubReg = [this,
806 RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
807 for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
808 if (TRI->getMinimalPhysRegClass(OriginalReg) ==
809 TRI->getMinimalPhysRegClass(SubOrSuper))
810 return SubOrSuper;
811 llvm_unreachable("Should have found matching sub or super register!");
812 };
813
814 std::function<bool(MachineInstr &, bool)> UpdateMIs =
815 [this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
816 if (IsDef) {
817 bool SeenDef = false;
818 for (auto &MOP : MI.operands()) {
819 // Rename the first explicit definition and all implicit
820 // definitions matching RegToRename.
Florian Hahn2675a3c2019-12-11 17:17:29 +0000821 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000822 (!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
823 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
824 assert((MOP.isImplicit() ||
825 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
826 "Need renamable operands");
827 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
828 SeenDef = true;
829 }
830 }
831 } else {
832 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000833 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
834 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
Bill Wendlingdc03b962019-12-20 12:47:38 -0800835 assert((MOP.isImplicit() ||
836 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
Florian Hahn17554b82019-12-11 09:59:18 +0000837 "Need renamable operands");
838 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
839 }
840 }
841 }
842 LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
843 return true;
844 };
845 forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
846
Fangrui Song25e21a02019-12-11 10:59:45 -0800847#if !defined(NDEBUG)
Florian Hahn17554b82019-12-11 09:59:18 +0000848 // Make sure the register used for renaming is not used between the paired
849 // instructions. That would trash the content before the new paired
850 // instruction.
851 for (auto &MI :
852 iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
853 std::next(I), std::next(Paired)))
854 assert(all_of(MI.operands(),
855 [this, &RenameReg](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000856 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +0000857 !TRI->regsOverlap(MOP.getReg(), *RenameReg);
858 }) &&
859 "Rename register used between paired instruction, trashing the "
860 "content");
Fangrui Song25e21a02019-12-11 10:59:45 -0800861#endif
Florian Hahn17554b82019-12-11 09:59:18 +0000862 }
863
Chad Rosierb5933d72016-02-09 19:02:12 +0000864 // Insert our new paired instruction after whichever of the paired
865 // instructions MergeForward indicates.
866 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
867 // Also based on MergeForward is from where we copy the base register operand
868 // so we get the flags compatible with the input code.
869 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000870 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
Chad Rosierb5933d72016-02-09 19:02:12 +0000871
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000872 int Offset = getLdStOffsetOp(*I).getImm();
873 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000874 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000875 if (IsUnscaled != PairedIsUnscaled) {
876 // We're trying to pair instructions that differ in how they are scaled. If
877 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
878 // the opposite (i.e., make Paired's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +0000879 int MemSize = TII->getMemScale(*Paired);
Chad Rosier00f9d232016-02-11 14:25:08 +0000880 if (PairedIsUnscaled) {
881 // If the unscaled offset isn't a multiple of the MemSize, we can't
882 // pair the operations together.
Jay Foad97ca7c22019-12-11 10:29:23 +0000883 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000884 "Offset should be a multiple of the stride!");
885 PairedOffset /= MemSize;
886 } else {
887 PairedOffset *= MemSize;
888 }
889 }
890
Chad Rosierb5933d72016-02-09 19:02:12 +0000891 // Which register is Rt and which is Rt2 depends on the offset order.
892 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000893 if (Offset == PairedOffset + OffsetStride) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000894 RtMI = &*Paired;
895 Rt2MI = &*I;
Chad Rosierb5933d72016-02-09 19:02:12 +0000896 // Here we swapped the assumption made for SExtIdx.
897 // I.e., we turn ldp I, Paired into ldp Paired, I.
898 // Update the index accordingly.
899 if (SExtIdx != -1)
900 SExtIdx = (SExtIdx + 1) % 2;
901 } else {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000902 RtMI = &*I;
903 Rt2MI = &*Paired;
Chad Rosierb5933d72016-02-09 19:02:12 +0000904 }
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000905 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000906 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000907 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Jay Foad97ca7c22019-12-11 10:29:23 +0000908 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000909 "Unscaled offset cannot be scaled.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000910 OffsetImm /= TII->getMemScale(*RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000911 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000912
913 // Construct the new instruction.
914 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000915 DebugLoc DL = I->getDebugLoc();
916 MachineBasicBlock *MBB = I->getParent();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000917 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
918 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
919 // Kill flags may become invalid when moving stores for pairing.
920 if (RegOp0.isUse()) {
921 if (!MergeForward) {
922 // Clear kill flags on store if moving upwards. Example:
923 // STRWui %w0, ...
924 // USE %w1
925 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
926 RegOp0.setIsKill(false);
927 RegOp1.setIsKill(false);
928 } else {
929 // Clear kill flags of the first stores register. Example:
930 // STRWui %w1, ...
931 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
932 // STRW %w0
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000933 Register Reg = getLdStRegOp(*I).getReg();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000934 for (MachineInstr &MI : make_range(std::next(I), Paired))
935 MI.clearRegisterKills(Reg, TRI);
936 }
937 }
Chad Rosierc46ef882016-02-09 19:33:42 +0000938 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000939 .add(RegOp0)
940 .add(RegOp1)
Diana Picus116bbab2017-01-13 09:58:52 +0000941 .add(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000942 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000943 .cloneMergedMemRefs({&*I, &*Paired})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000944 .setMIFlags(I->mergeFlagsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000945
946 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000947
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000948 LLVM_DEBUG(
949 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
950 LLVM_DEBUG(I->print(dbgs()));
951 LLVM_DEBUG(dbgs() << " ");
952 LLVM_DEBUG(Paired->print(dbgs()));
953 LLVM_DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000954 if (SExtIdx != -1) {
955 // Generate the sign extension for the proper result of the ldp.
956 // I.e., with X1, that would be:
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000957 // %w1 = KILL %w1, implicit-def %x1
958 // %x1 = SBFMXri killed %x1, 0, 31
Quentin Colombet66b61632015-03-06 22:42:10 +0000959 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
960 // Right now, DstMO has the extended register, since it comes from an
961 // extended opcode.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000962 Register DstRegX = DstMO.getReg();
Quentin Colombet66b61632015-03-06 22:42:10 +0000963 // Get the W variant of that register.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000964 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
Quentin Colombet66b61632015-03-06 22:42:10 +0000965 // Update the result of LDP to use the W instead of the X variant.
966 DstMO.setReg(DstRegW);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000967 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
968 LLVM_DEBUG(dbgs() << "\n");
Quentin Colombet66b61632015-03-06 22:42:10 +0000969 // Make the machine verifier happy by providing a definition for
970 // the X register.
971 // Insert this definition right after the generated LDP, i.e., before
972 // InsertionPoint.
973 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000974 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000975 .addReg(DstRegW)
976 .addReg(DstRegX, RegState::Define);
977 MIBKill->getOperand(2).setImplicit();
978 // Create the sign extension.
979 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000980 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000981 .addReg(DstRegX)
982 .addImm(0)
983 .addImm(31);
984 (void)MIBSXTW;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000985 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
986 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000987 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000988 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000989 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000990 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000991
Florian Hahn17554b82019-12-11 09:59:18 +0000992 if (MergeForward)
993 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
994 if (MOP.isReg() && MOP.isKill())
995 DefinedInBB.addReg(MOP.getReg());
996
Tim Northover3b0846e2014-05-24 12:50:23 +0000997 // Erase the old instructions.
998 I->eraseFromParent();
999 Paired->eraseFromParent();
1000
1001 return NextI;
1002}
1003
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001004MachineBasicBlock::iterator
1005AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1006 MachineBasicBlock::iterator StoreI) {
1007 MachineBasicBlock::iterator NextI = LoadI;
1008 ++NextI;
1009
Jay Foad97ca7c22019-12-11 10:29:23 +00001010 int LoadSize = TII->getMemScale(*LoadI);
1011 int StoreSize = TII->getMemScale(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001012 Register LdRt = getLdStRegOp(*LoadI).getReg();
Florian Hahn80e48512017-06-21 08:47:23 +00001013 const MachineOperand &StMO = getLdStRegOp(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001014 Register StRt = getLdStRegOp(*StoreI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001015 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1016
1017 assert((IsStoreXReg ||
1018 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1019 "Unexpected RegClass");
1020
1021 MachineInstr *BitExtMI;
1022 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1023 // Remove the load, if the destination register of the loads is the same
1024 // register for stored value.
1025 if (StRt == LdRt && LoadSize == 8) {
Tim Northover9ac3e422017-06-26 18:49:25 +00001026 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1027 LoadI->getIterator())) {
1028 if (MI.killsRegister(StRt, TRI)) {
1029 MI.clearRegisterKills(StRt, TRI);
1030 break;
1031 }
1032 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001033 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1034 LLVM_DEBUG(LoadI->print(dbgs()));
1035 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001036 LoadI->eraseFromParent();
1037 return NextI;
1038 }
1039 // Replace the load with a mov if the load and store are in the same size.
1040 BitExtMI =
1041 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1042 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1043 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
Florian Hahn80e48512017-06-21 08:47:23 +00001044 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001045 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1046 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001047 } else {
1048 // FIXME: Currently we disable this transformation in big-endian targets as
1049 // performance and correctness are verified only in little-endian.
1050 if (!Subtarget->isLittleEndian())
1051 return NextI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001052 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
1053 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001054 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001055 assert(LoadSize <= StoreSize && "Invalid load size");
1056 int UnscaledLdOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001057 ? getLdStOffsetOp(*LoadI).getImm()
1058 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001059 int UnscaledStOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001060 ? getLdStOffsetOp(*StoreI).getImm()
1061 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001062 int Width = LoadSize * 8;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001063 unsigned DestReg =
1064 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1065 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1066 : LdRt;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001067
1068 assert((UnscaledLdOffset >= UnscaledStOffset &&
1069 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1070 "Invalid offset");
1071
Simon Pilgrime461e9a2019-05-08 16:29:39 +00001072 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1073 int Imms = Immr + Width - 1;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001074 if (UnscaledLdOffset == UnscaledStOffset) {
1075 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1076 | ((Immr) << 6) // immr
1077 | ((Imms) << 0) // imms
1078 ;
1079
1080 BitExtMI =
1081 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1082 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1083 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001084 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001085 .addImm(AndMaskEncoded)
1086 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001087 } else {
1088 BitExtMI =
1089 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1090 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1091 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001092 .add(StMO)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001093 .addImm(Immr)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001094 .addImm(Imms)
1095 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001096 }
1097 }
Matthias Braun76bb4132016-12-16 23:55:43 +00001098
Matthias Braund9a59a82017-02-17 23:15:03 +00001099 // Clear kill flags between store and load.
1100 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1101 BitExtMI->getIterator()))
Florian Hahn8552e592017-06-21 09:51:52 +00001102 if (MI.killsRegister(StRt, TRI)) {
1103 MI.clearRegisterKills(StRt, TRI);
1104 break;
1105 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001106
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001107 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1108 LLVM_DEBUG(StoreI->print(dbgs()));
1109 LLVM_DEBUG(dbgs() << " ");
1110 LLVM_DEBUG(LoadI->print(dbgs()));
1111 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1112 LLVM_DEBUG(StoreI->print(dbgs()));
1113 LLVM_DEBUG(dbgs() << " ");
1114 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1115 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001116
1117 // Erase the old instructions.
1118 LoadI->eraseFromParent();
1119 return NextI;
1120}
1121
Tim Northover3b0846e2014-05-24 12:50:23 +00001122static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001123 // Convert the byte-offset used by unscaled into an "element" offset used
1124 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001125 if (IsUnscaled) {
1126 // If the byte-offset isn't a multiple of the stride, there's no point
1127 // trying to match it.
1128 if (Offset % OffsetStride)
1129 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001130 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001131 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001132 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001133}
1134
1135// Do alignment, specialized to power of 2 and for signed ints,
1136// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001137// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001138// FIXME: Move this function to include/MathExtras.h?
1139static int alignTo(int Num, int PowOf2) {
1140 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1141}
1142
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001143static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001144 AliasAnalysis *AA) {
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001145 // One of the instructions must modify memory.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001146 if (!MIa.mayStore() && !MIb.mayStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001147 return false;
1148
1149 // Both instructions must be memory operations.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001150 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001151 return false;
1152
Chad Rosiera69dcb62017-03-17 14:19:55 +00001153 return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001154}
1155
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001156static bool mayAlias(MachineInstr &MIa,
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001157 SmallVectorImpl<MachineInstr *> &MemInsns,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001158 AliasAnalysis *AA) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001159 for (MachineInstr *MIb : MemInsns)
Chad Rosiera69dcb62017-03-17 14:19:55 +00001160 if (mayAlias(MIa, *MIb, AA))
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001161 return true;
1162
1163 return false;
1164}
1165
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001166bool AArch64LoadStoreOpt::findMatchingStore(
1167 MachineBasicBlock::iterator I, unsigned Limit,
1168 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001169 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001170 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001171 MachineInstr &LoadMI = *I;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001172 Register BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001173
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001174 // If the load is the first instruction in the block, there's obviously
1175 // not any matching store.
1176 if (MBBI == B)
1177 return false;
1178
Jun Bum Lim47aece12018-04-27 18:44:37 +00001179 // Track which register units have been modified and used between the first
1180 // insn and the second insn.
1181 ModifiedRegUnits.clear();
1182 UsedRegUnits.clear();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001183
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001184 unsigned Count = 0;
1185 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001186 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001187 MachineInstr &MI = *MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001188
Geoff Berry4ff2e362016-07-21 15:20:25 +00001189 // Don't count transient instructions towards the search limit since there
1190 // may be different numbers of them if e.g. debug information is present.
1191 if (!MI.isTransient())
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001192 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001193
1194 // If the load instruction reads directly from the address to which the
1195 // store instruction writes and the stored value is not modified, we can
1196 // promote the load. Since we do not handle stores with pre-/post-index,
1197 // it's unnecessary to check if BaseReg is modified by the store itself.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001198 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001199 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001200 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001201 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001202 StoreI = MBBI;
1203 return true;
1204 }
1205
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001206 if (MI.isCall())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001207 return false;
1208
Jun Bum Lim47aece12018-04-27 18:44:37 +00001209 // Update modified / uses register units.
1210 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001211
1212 // Otherwise, if the base register is modified, we have no match, so
1213 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001214 if (!ModifiedRegUnits.available(BaseReg))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001215 return false;
1216
1217 // If we encounter a store aliased with the load, return early.
Chad Rosiera69dcb62017-03-17 14:19:55 +00001218 if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001219 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001220 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001221 return false;
1222}
1223
Chad Rosierc5083c22016-06-10 20:47:14 +00001224// Returns true if FirstMI and MI are candidates for merging or pairing.
1225// Otherwise, returns false.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001226static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
Chad Rosierc5083c22016-06-10 20:47:14 +00001227 LdStPairFlags &Flags,
1228 const AArch64InstrInfo *TII) {
1229 // If this is volatile or if pairing is suppressed, not a candidate.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001230 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
Chad Rosierc5083c22016-06-10 20:47:14 +00001231 return false;
1232
1233 // We should have already checked FirstMI for pair suppression and volatility.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001234 assert(!FirstMI.hasOrderedMemoryRef() &&
1235 !TII->isLdStPairSuppressed(FirstMI) &&
Chad Rosierc5083c22016-06-10 20:47:14 +00001236 "FirstMI shouldn't get here if either of these checks are true.");
1237
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001238 unsigned OpcA = FirstMI.getOpcode();
1239 unsigned OpcB = MI.getOpcode();
Chad Rosierc5083c22016-06-10 20:47:14 +00001240
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001241 // Opcodes match: nothing more to check.
1242 if (OpcA == OpcB)
1243 return true;
1244
1245 // Try to match a sign-extended load/store with a zero-extended load/store.
1246 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1247 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1248 assert(IsValidLdStrOpc &&
1249 "Given Opc should be a Load or Store with an immediate");
1250 // OpcA will be the first instruction in the pair.
1251 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1252 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1253 return true;
1254 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001255
Chad Rosierd6daac42016-11-07 15:27:22 +00001256 // If the second instruction isn't even a mergable/pairable load/store, bail
1257 // out.
Chad Rosier00f9d232016-02-11 14:25:08 +00001258 if (!PairIsValidLdStrOpc)
1259 return false;
1260
Chad Rosierd6daac42016-11-07 15:27:22 +00001261 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1262 // offsets.
1263 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
Chad Rosier00f9d232016-02-11 14:25:08 +00001264 return false;
1265
1266 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001267 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001268 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1269
1270 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001271}
1272
Florian Hahn17554b82019-12-11 09:59:18 +00001273static bool
1274canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1275 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1276 const TargetRegisterInfo *TRI) {
1277 if (!FirstMI.mayStore())
1278 return false;
1279
1280 // Check if we can find an unused register which we can use to rename
1281 // the register used by the first load/store.
1282 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1283 MachineFunction &MF = *FirstMI.getParent()->getParent();
1284 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1285 return false;
1286
1287 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1288 // For now, we only rename if the store operand gets killed at the store.
1289 if (!getLdStRegOp(FirstMI).isKill() &&
1290 !any_of(FirstMI.operands(),
1291 [TRI, RegToRename](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001292 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1293 MOP.isImplicit() && MOP.isKill() &&
Florian Hahn17554b82019-12-11 09:59:18 +00001294 TRI->regsOverlap(RegToRename, MOP.getReg());
1295 })) {
1296 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI << "\n");
1297 return false;
1298 }
1299 auto canRenameMOP = [](const MachineOperand &MOP) {
1300 return MOP.isImplicit() ||
1301 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1302 };
1303
1304 bool FoundDef = false;
1305
1306 // For each instruction between FirstMI and the previous def for RegToRename,
1307 // we
1308 // * check if we can rename RegToRename in this instruction
1309 // * collect the registers used and required register classes for RegToRename.
1310 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1311 bool IsDef) {
1312 LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1313 // Currently we do not try to rename across frame-setup instructions.
1314 if (MI.getFlag(MachineInstr::FrameSetup)) {
1315 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions currently ("
1316 << MI << ")\n");
1317 return false;
1318 }
1319
1320 UsedInBetween.accumulate(MI);
1321
1322 // For a definition, check that we can rename the definition and exit the
1323 // loop.
1324 FoundDef = IsDef;
1325
1326 // For defs, check if we can rename the first def of RegToRename.
1327 if (FoundDef) {
1328 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001329 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +00001330 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1331 continue;
1332 if (!canRenameMOP(MOP)) {
1333 LLVM_DEBUG(dbgs()
1334 << " Cannot rename " << MOP << " in " << MI << "\n");
1335 return false;
1336 }
1337 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1338 }
1339 return true;
1340 } else {
1341 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001342 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1343 !TRI->regsOverlap(MOP.getReg(), RegToRename))
Florian Hahn17554b82019-12-11 09:59:18 +00001344 continue;
1345
1346 if (!canRenameMOP(MOP)) {
1347 LLVM_DEBUG(dbgs()
1348 << " Cannot rename " << MOP << " in " << MI << "\n");
1349 return false;
1350 }
1351 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1352 }
1353 }
1354 return true;
1355 };
1356
1357 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1358 return false;
1359
1360 if (!FoundDef) {
1361 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1362 return false;
1363 }
1364 return true;
1365}
1366
1367// Check if we can find a physical register for renaming. This register must:
1368// * not be defined up to FirstMI (checking DefinedInBB)
1369// * not used between the MI and the defining instruction of the register to
1370// rename (checked using UsedInBetween).
1371// * is available in all used register classes (checked using RequiredClasses).
1372static Optional<MCPhysReg> tryToFindRegisterToRename(
1373 MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1374 LiveRegUnits &UsedInBetween,
1375 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1376 const TargetRegisterInfo *TRI) {
1377 auto &MF = *FirstMI.getParent()->getParent();
Florian Hahnd2692552019-12-21 14:47:08 +01001378 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Florian Hahn17554b82019-12-11 09:59:18 +00001379
1380 // Checks if any sub- or super-register of PR is callee saved.
1381 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1382 return any_of(TRI->sub_and_superregs_inclusive(PR),
1383 [&MF, TRI](MCPhysReg SubOrSuper) {
1384 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1385 });
1386 };
1387
1388 // Check if PR or one of its sub- or super-registers can be used for all
1389 // required register classes.
1390 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1391 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1392 return any_of(TRI->sub_and_superregs_inclusive(PR),
1393 [C, TRI](MCPhysReg SubOrSuper) {
1394 return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1395 });
1396 });
1397 };
1398
1399 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1400 for (const MCPhysReg &PR : *RegClass) {
1401 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
Florian Hahnd2692552019-12-21 14:47:08 +01001402 !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1403 CanBeUsedForAllClasses(PR)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001404 DefinedInBB.addReg(PR);
1405 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1406 << "\n");
1407 return {PR};
1408 }
1409 }
1410 LLVM_DEBUG(dbgs() << "No rename register found from "
1411 << TRI->getRegClassName(RegClass) << "\n");
1412 return None;
1413}
1414
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001415/// Scan the instructions looking for a load/store that can be combined with the
1416/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001417MachineBasicBlock::iterator
1418AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001419 LdStPairFlags &Flags, unsigned Limit,
1420 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001421 MachineBasicBlock::iterator E = I->getParent()->end();
1422 MachineBasicBlock::iterator MBBI = I;
Florian Hahn17554b82019-12-11 09:59:18 +00001423 MachineBasicBlock::iterator MBBIWithRenameReg;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001424 MachineInstr &FirstMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001425 ++MBBI;
1426
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001427 bool MayLoad = FirstMI.mayLoad();
1428 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001429 Register Reg = getLdStRegOp(FirstMI).getReg();
1430 Register BaseReg = getLdStBaseOp(FirstMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001431 int Offset = getLdStOffsetOp(FirstMI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001432 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001433 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001434
Florian Hahn17554b82019-12-11 09:59:18 +00001435 Optional<bool> MaybeCanRename = None;
1436 SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1437 LiveRegUnits UsedInBetween;
1438 UsedInBetween.init(*TRI);
1439
1440 Flags.clearRenameReg();
1441
Jun Bum Lim47aece12018-04-27 18:44:37 +00001442 // Track which register units have been modified and used between the first
1443 // insn (inclusive) and the second insn.
1444 ModifiedRegUnits.clear();
1445 UsedRegUnits.clear();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001446
1447 // Remember any instructions that read/write memory between FirstMI and MI.
1448 SmallVector<MachineInstr *, 4> MemInsns;
1449
Tim Northover3b0846e2014-05-24 12:50:23 +00001450 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001451 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001452
Florian Hahn17554b82019-12-11 09:59:18 +00001453 UsedInBetween.accumulate(MI);
1454
Geoff Berry4ff2e362016-07-21 15:20:25 +00001455 // Don't count transient instructions towards the search limit since there
1456 // may be different numbers of them if e.g. debug information is present.
1457 if (!MI.isTransient())
1458 ++Count;
Tim Northover3b0846e2014-05-24 12:50:23 +00001459
Chad Rosier18896c02016-02-04 16:01:40 +00001460 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001461 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001462 getLdStOffsetOp(MI).isImm()) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001463 assert(MI.mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001464 // If we've found another instruction with the same opcode, check to see
1465 // if the base and offset are compatible with our starting instruction.
1466 // These instructions all have scaled immediate operands, so we just
1467 // check for +1/-1. Make sure to check the new instruction offset is
1468 // actually an immediate and not a symbolic reference destined for
1469 // a relocation.
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001470 Register MIBaseReg = getLdStBaseOp(MI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001471 int MIOffset = getLdStOffsetOp(MI).getImm();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001472 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001473 if (IsUnscaled != MIIsUnscaled) {
1474 // We're trying to pair instructions that differ in how they are scaled.
1475 // If FirstMI is scaled then scale the offset of MI accordingly.
1476 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +00001477 int MemSize = TII->getMemScale(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001478 if (MIIsUnscaled) {
1479 // If the unscaled offset isn't a multiple of the MemSize, we can't
1480 // pair the operations together: bail and keep looking.
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001481 if (MIOffset % MemSize) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001482 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1483 UsedRegUnits, TRI);
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001484 MemInsns.push_back(&MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001485 continue;
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001486 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001487 MIOffset /= MemSize;
1488 } else {
1489 MIOffset *= MemSize;
1490 }
1491 }
1492
Tim Northover3b0846e2014-05-24 12:50:23 +00001493 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1494 (Offset + OffsetStride == MIOffset))) {
1495 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001496 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001497 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001498 // instruction can't express the offset of the scaled narrow input,
1499 // bail and keep looking. For promotable zero stores, allow only when
1500 // the stored value is the same (i.e., WZR).
1501 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1502 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001503 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1504 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001505 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001506 continue;
1507 }
1508 } else {
Chad Rosierd1f6c842016-06-10 20:49:18 +00001509 // Pairwise instructions have a 7-bit signed offset field. Single
1510 // insns have a 12-bit unsigned offset field. If the resultant
1511 // immediate offset of merging these instructions is out of range for
1512 // a pairwise instruction, bail and keep looking.
Jun Bum Limcf974432016-03-31 14:47:24 +00001513 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001514 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1515 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001516 MemInsns.push_back(&MI);
Jun Bum Limcf974432016-03-31 14:47:24 +00001517 continue;
1518 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001519 // If the alignment requirements of the paired (scaled) instruction
1520 // can't express the offset of the unscaled input, bail and keep
1521 // looking.
1522 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001523 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1524 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001525 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001526 continue;
1527 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001528 }
1529 // If the destination register of the loads is the same register, bail
1530 // and keep looking. A load-pair instruction with both destination
1531 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001532 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001533 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1534 TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001535 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001536 continue;
1537 }
1538
1539 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001540 // the two instructions and none of the instructions between the second
1541 // and first alias with the second, we can combine the second into the
1542 // first.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001543 if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1544 !(MI.mayLoad() &&
1545 !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001546 !mayAlias(MI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001547
Chad Rosier96a18a92015-07-21 17:42:04 +00001548 Flags.setMergeForward(false);
Florian Hahn17554b82019-12-11 09:59:18 +00001549 Flags.clearRenameReg();
Tim Northover3b0846e2014-05-24 12:50:23 +00001550 return MBBI;
1551 }
1552
1553 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001554 // between the two instructions and none of the instructions between the
1555 // first and the second alias with the first, we can combine the first
1556 // into the second.
Florian Hahn17554b82019-12-11 09:59:18 +00001557 if (!(MayLoad &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001558 !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001559 !mayAlias(FirstMI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001560
1561 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1562 Flags.setMergeForward(true);
1563 Flags.clearRenameReg();
1564 return MBBI;
1565 }
1566
1567 if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1568 if (!MaybeCanRename)
1569 MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1570 RequiredClasses, TRI)};
1571
1572 if (*MaybeCanRename) {
1573 Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1574 FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1575 TRI);
1576 if (MaybeRenameReg) {
1577 Flags.setRenameReg(*MaybeRenameReg);
1578 Flags.setMergeForward(true);
1579 MBBIWithRenameReg = MBBI;
1580 }
1581 }
1582 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001583 }
1584 // Unable to combine these instructions due to interference in between.
1585 // Keep looking.
1586 }
1587 }
1588
Florian Hahn17554b82019-12-11 09:59:18 +00001589 if (Flags.getRenameReg())
1590 return MBBIWithRenameReg;
1591
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001592 // If the instruction wasn't a matching load or store. Stop searching if we
1593 // encounter a call instruction that might modify memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001594 if (MI.isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001595 return E;
1596
Jun Bum Lim47aece12018-04-27 18:44:37 +00001597 // Update modified / uses register units.
1598 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001599
1600 // Otherwise, if the base register is modified, we have no match, so
1601 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001602 if (!ModifiedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001603 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001604
1605 // Update list of instructions that read/write memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001606 if (MI.mayLoadOrStore())
1607 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001608 }
1609 return E;
1610}
1611
1612MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001613AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1614 MachineBasicBlock::iterator Update,
1615 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001616 assert((Update->getOpcode() == AArch64::ADDXri ||
1617 Update->getOpcode() == AArch64::SUBXri) &&
1618 "Unexpected base register update instruction to merge!");
1619 MachineBasicBlock::iterator NextI = I;
1620 // Return the instruction following the merged instruction, which is
1621 // the instruction following our unmerged load. Unless that's the add/sub
1622 // instruction we're merging, in which case it's the one after that.
1623 if (++NextI == Update)
1624 ++NextI;
1625
1626 int Value = Update->getOperand(2).getImm();
1627 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001628 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001629 if (Update->getOpcode() == AArch64::SUBXri)
1630 Value = -Value;
1631
Chad Rosier2dfd3542015-09-23 13:51:44 +00001632 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1633 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001634 MachineInstrBuilder MIB;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001635 int Scale, MinOffset, MaxOffset;
1636 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001637 if (!isPairedLdSt(*I)) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001638 // Non-paired instruction.
1639 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001640 .add(getLdStRegOp(*Update))
1641 .add(getLdStRegOp(*I))
1642 .add(getLdStBaseOp(*I))
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001643 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001644 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001645 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001646 } else {
1647 // Paired instruction.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001648 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001649 .add(getLdStRegOp(*Update))
1650 .add(getLdStRegOp(*I, 0))
1651 .add(getLdStRegOp(*I, 1))
1652 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001653 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001654 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001655 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001656 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001657 (void)MIB;
1658
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001659 if (IsPreIdx) {
1660 ++NumPreFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001661 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001662 } else {
1663 ++NumPostFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001664 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001665 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001666 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
1667 LLVM_DEBUG(I->print(dbgs()));
1668 LLVM_DEBUG(dbgs() << " ");
1669 LLVM_DEBUG(Update->print(dbgs()));
1670 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1671 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1672 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001673
1674 // Erase the old instructions for the block.
1675 I->eraseFromParent();
1676 Update->eraseFromParent();
1677
1678 return NextI;
1679}
1680
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001681bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1682 MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001683 unsigned BaseReg, int Offset) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001684 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001685 default:
1686 break;
1687 case AArch64::SUBXri:
Tim Northover3b0846e2014-05-24 12:50:23 +00001688 case AArch64::ADDXri:
1689 // Make sure it's a vanilla immediate operand, not a relocation or
1690 // anything else we can't handle.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001691 if (!MI.getOperand(2).isImm())
Tim Northover3b0846e2014-05-24 12:50:23 +00001692 break;
1693 // Watch out for 1 << 12 shifted value.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001694 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
Tim Northover3b0846e2014-05-24 12:50:23 +00001695 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001696
1697 // The update instruction source and destination register must be the
1698 // same as the load/store base register.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001699 if (MI.getOperand(0).getReg() != BaseReg ||
1700 MI.getOperand(1).getReg() != BaseReg)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001701 break;
1702
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001703 int UpdateOffset = MI.getOperand(2).getImm();
Eli Friedman8585e9d2016-08-12 20:28:02 +00001704 if (MI.getOpcode() == AArch64::SUBXri)
1705 UpdateOffset = -UpdateOffset;
1706
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001707 // The immediate must be a multiple of the scaling factor of the pre/post
1708 // indexed instruction.
1709 int Scale, MinOffset, MaxOffset;
1710 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1711 if (UpdateOffset % Scale != 0)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001712 break;
1713
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001714 // Scaled offset must fit in the instruction immediate.
1715 int ScaledOffset = UpdateOffset / Scale;
1716 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1717 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001718
1719 // If we have a non-zero Offset, we check that it matches the amount
1720 // we're adding to the register.
Eli Friedman8585e9d2016-08-12 20:28:02 +00001721 if (!Offset || Offset == UpdateOffset)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001722 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001723 break;
1724 }
1725 return false;
1726}
1727
1728MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001729 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001731 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001732 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001733
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001734 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Jay Foad97ca7c22019-12-11 10:29:23 +00001735 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001736
Chad Rosierb7c5b912015-10-01 13:43:05 +00001737 // Scan forward looking for post-index opportunities. Updating instructions
1738 // can't be formed if the memory instruction doesn't have the offset we're
1739 // looking for.
1740 if (MIUnscaledOffset != UnscaledOffset)
1741 return E;
1742
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001743 // If the base register overlaps a source/destination register, we can't
1744 // merge the update. This does not apply to tag store instructions which
1745 // ignore the address part of the source register.
1746 // This does not apply to STGPi as well, which does not have unpredictable
1747 // behavior in this case unlike normal stores, and always performs writeback
1748 // after reading the source register value.
1749 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1750 bool IsPairedInsn = isPairedLdSt(MemMI);
1751 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1752 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1753 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1754 return E;
1755 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001756 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001757
Jun Bum Lim47aece12018-04-27 18:44:37 +00001758 // Track which register units have been modified and used between the first
1759 // insn (inclusive) and the second insn.
1760 ModifiedRegUnits.clear();
1761 UsedRegUnits.clear();
Tim Northover3b0846e2014-05-24 12:50:23 +00001762 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001763 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001764 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001765
Geoff Berry4ff2e362016-07-21 15:20:25 +00001766 // Don't count transient instructions towards the search limit since there
1767 // may be different numbers of them if e.g. debug information is present.
1768 if (!MI.isTransient())
1769 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001770
Tim Northover3b0846e2014-05-24 12:50:23 +00001771 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001772 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001773 return MBBI;
1774
1775 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001776 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001777
1778 // Otherwise, if the base register is used or modified, we have no match, so
1779 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001780 if (!ModifiedRegUnits.available(BaseReg) ||
1781 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001782 return E;
1783 }
1784 return E;
1785}
1786
1787MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001788 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001789 MachineBasicBlock::iterator B = I->getParent()->begin();
1790 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001791 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001792 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001793
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001794 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001795 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001796
1797 // If the load/store is the first instruction in the block, there's obviously
1798 // not any matching update. Ditto if the memory offset isn't zero.
1799 if (MBBI == B || Offset != 0)
1800 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001801 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001802 // merge the update.
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001803 if (!isTagStore(MemMI)) {
1804 bool IsPairedInsn = isPairedLdSt(MemMI);
1805 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1806 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1807 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1808 return E;
1809 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001810 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001811
Jun Bum Lim47aece12018-04-27 18:44:37 +00001812 // Track which register units have been modified and used between the first
1813 // insn (inclusive) and the second insn.
1814 ModifiedRegUnits.clear();
1815 UsedRegUnits.clear();
Geoff Berry173b14d2016-02-09 20:47:21 +00001816 unsigned Count = 0;
1817 do {
1818 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001819 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001820
Geoff Berry4ff2e362016-07-21 15:20:25 +00001821 // Don't count transient instructions towards the search limit since there
1822 // may be different numbers of them if e.g. debug information is present.
1823 if (!MI.isTransient())
Geoff Berry173b14d2016-02-09 20:47:21 +00001824 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001825
Tim Northover3b0846e2014-05-24 12:50:23 +00001826 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001827 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001828 return MBBI;
1829
1830 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001831 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001832
1833 // Otherwise, if the base register is used or modified, we have no match, so
1834 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001835 if (!ModifiedRegUnits.available(BaseReg) ||
1836 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001838 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 return E;
1840}
1841
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001842bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1843 MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001844 MachineInstr &MI = *MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001845 // If this is a volatile load, don't mess with it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001846 if (MI.hasOrderedMemoryRef())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001847 return false;
1848
1849 // Make sure this is a reg+imm.
1850 // FIXME: It is possible to extend it to handle reg+reg cases.
1851 if (!getLdStOffsetOp(MI).isImm())
1852 return false;
1853
Chad Rosier35706ad2016-02-04 21:26:02 +00001854 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001855 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001856 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001857 ++NumLoadsFromStoresPromoted;
1858 // Promote the load. Keeping the iterator straight is a
1859 // pain, so we let the merge routine tell us what the next instruction
1860 // is after it's done mucking about.
1861 MBBI = promoteLoadFromStore(MBBI, StoreI);
1862 return true;
1863 }
1864 return false;
1865}
1866
Chad Rosierd6daac42016-11-07 15:27:22 +00001867// Merge adjacent zero stores into a wider store.
1868bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
Chad Rosier24c46ad2016-02-09 18:10:20 +00001869 MachineBasicBlock::iterator &MBBI) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001870 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001871 MachineInstr &MI = *MBBI;
1872 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001873
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001874 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001875 return false;
1876
1877 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001878 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001879 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001880 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001881 if (MergeMI != E) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001882 ++NumZeroStoresPromoted;
1883
Chad Rosier24c46ad2016-02-09 18:10:20 +00001884 // Keeping the iterator straight is a pain, so we let the merge routine tell
1885 // us what the next instruction is after it's done mucking about.
Chad Rosierd6daac42016-11-07 15:27:22 +00001886 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001887 return true;
1888 }
1889 return false;
1890}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001891
Chad Rosier24c46ad2016-02-09 18:10:20 +00001892// Find loads and stores that can be merged into a single load or store pair
1893// instruction.
1894bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001895 MachineInstr &MI = *MBBI;
1896 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001897
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001898 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001899 return false;
1900
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001901 // Early exit if the offset is not possible to match. (6 bits of positive
1902 // range, plus allow an extra one in case we find a later insn that matches
1903 // with Offset-1)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001904 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001905 int Offset = getLdStOffsetOp(MI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001906 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
Nirav Dave0f9d1112017-01-04 21:21:46 +00001907 // Allow one more for offset.
1908 if (Offset > 0)
1909 Offset -= OffsetStride;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001910 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1911 return false;
1912
Chad Rosier24c46ad2016-02-09 18:10:20 +00001913 // Look ahead up to LdStLimit instructions for a pairable instruction.
1914 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001915 MachineBasicBlock::iterator Paired =
1916 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001917 if (Paired != E) {
1918 ++NumPairCreated;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001919 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001920 ++NumUnscaledPairCreated;
1921 // Keeping the iterator straight is a pain, so we let the merge routine tell
1922 // us what the next instruction is after it's done mucking about.
Florian Hahn17554b82019-12-11 09:59:18 +00001923 auto Prev = std::prev(MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001924 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Florian Hahn17554b82019-12-11 09:59:18 +00001925 // Collect liveness info for instructions between Prev and the new position
1926 // MBBI.
1927 for (auto I = std::next(Prev); I != MBBI; I++)
1928 updateDefinedRegisters(*I, DefinedInBB, TRI);
1929
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001930 return true;
1931 }
1932 return false;
1933}
1934
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001935bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1936 (MachineBasicBlock::iterator &MBBI) {
1937 MachineInstr &MI = *MBBI;
1938 MachineBasicBlock::iterator E = MI.getParent()->end();
1939 MachineBasicBlock::iterator Update;
1940
1941 // Look forward to try to form a post-index instruction. For example,
1942 // ldr x0, [x20]
1943 // add x20, x20, #32
1944 // merged into:
1945 // ldr x0, [x20], #32
1946 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1947 if (Update != E) {
1948 // Merge the update into the ld/st.
1949 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1950 return true;
1951 }
1952
1953 // Don't know how to handle unscaled pre/post-index versions below, so bail.
1954 if (TII->isUnscaledLdSt(MI.getOpcode()))
1955 return false;
1956
1957 // Look back to try to find a pre-index instruction. For example,
1958 // add x0, x0, #8
1959 // ldr x1, [x0]
1960 // merged into:
1961 // ldr x1, [x0, #8]!
1962 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1963 if (Update != E) {
1964 // Merge the update into the ld/st.
1965 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1966 return true;
1967 }
1968
1969 // The immediate in the load/store is scaled by the size of the memory
1970 // operation. The immediate in the add we're looking for,
1971 // however, is not, so adjust here.
Jay Foad97ca7c22019-12-11 10:29:23 +00001972 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001973
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001974 // Look forward to try to find a pre-index instruction. For example,
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001975 // ldr x1, [x0, #64]
1976 // add x0, x0, #64
1977 // merged into:
1978 // ldr x1, [x0, #64]!
1979 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1980 if (Update != E) {
1981 // Merge the update into the ld/st.
1982 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1983 return true;
1984 }
1985
1986 return false;
1987}
1988
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001989bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
Chad Rosierd6daac42016-11-07 15:27:22 +00001990 bool EnableNarrowZeroStOpt) {
Florian Hahn17554b82019-12-11 09:59:18 +00001991
Tim Northover3b0846e2014-05-24 12:50:23 +00001992 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001993 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001994 // 1) Find loads that directly read from stores and promote them by
1995 // replacing with mov instructions. If the store is wider than the load,
1996 // the load will be replaced with a bitfield extract.
1997 // e.g.,
1998 // str w1, [x0, #4]
1999 // ldrh w2, [x0, #6]
2000 // ; becomes
2001 // str w1, [x0, #4]
NAKAMURA Takumife1202c2016-06-20 00:37:41 +00002002 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00002003 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002004 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002005 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2006 Modified = true;
2007 else
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002008 ++MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002009 }
Chad Rosierd6daac42016-11-07 15:27:22 +00002010 // 2) Merge adjacent zero stores into a wider store.
Jun Bum Lim1de2d442016-02-05 20:02:03 +00002011 // e.g.,
2012 // strh wzr, [x0]
2013 // strh wzr, [x0, #2]
2014 // ; becomes
2015 // str wzr, [x0]
Chad Rosierd6daac42016-11-07 15:27:22 +00002016 // e.g.,
2017 // str wzr, [x0]
2018 // str wzr, [x0, #4]
2019 // ; becomes
2020 // str xzr, [x0]
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002021 if (EnableNarrowZeroStOpt)
2022 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2023 MBBI != E;) {
2024 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002025 Modified = true;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002026 else
Jun Bum Lim33be4992016-05-06 15:08:57 +00002027 ++MBBI;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002028 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002029 // 3) Find loads and stores that can be merged into a single load or store
2030 // pair instruction.
2031 // e.g.,
2032 // ldr x0, [x2]
2033 // ldr x1, [x2, #8]
2034 // ; becomes
2035 // ldp x0, x1, [x2]
Florian Hahn17554b82019-12-11 09:59:18 +00002036
2037 if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2038 DefinedInBB.clear();
2039 DefinedInBB.addLiveIns(MBB);
2040 }
2041
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002042 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00002043 MBBI != E;) {
Florian Hahn17554b82019-12-11 09:59:18 +00002044 // Track currently live registers up to this point, to help with
2045 // searching for a rename register on demand.
2046 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
Geoff Berry22dfbc52016-08-12 15:26:00 +00002047 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2048 Modified = true;
2049 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002050 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002051 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002052 // 4) Find base register updates that can be merged into the load or store
2053 // as a base-reg writeback.
2054 // e.g.,
2055 // ldr x0, [x2]
2056 // add x2, x2, #4
2057 // ; becomes
2058 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00002059 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2060 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002061 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2062 Modified = true;
2063 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002064 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002065 }
2066
2067 return Modified;
2068}
2069
2070bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002071 if (skipFunction(Fn.getFunction()))
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00002072 return false;
2073
Oliver Stannardd414c992015-11-10 11:04:18 +00002074 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2075 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2076 TRI = Subtarget->getRegisterInfo();
Chad Rosiera69dcb62017-03-17 14:19:55 +00002077 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tim Northover3b0846e2014-05-24 12:50:23 +00002078
Jun Bum Lim47aece12018-04-27 18:44:37 +00002079 // Resize the modified and used register unit trackers. We do this once
2080 // per function and then clear the register units each time we optimize a load
2081 // or store.
2082 ModifiedRegUnits.init(*TRI);
2083 UsedRegUnits.init(*TRI);
Florian Hahn17554b82019-12-11 09:59:18 +00002084 DefinedInBB.init(*TRI);
Chad Rosierbba881e2016-02-02 15:02:30 +00002085
Tim Northover3b0846e2014-05-24 12:50:23 +00002086 bool Modified = false;
Chad Rosier10c7aaa2016-11-11 14:10:12 +00002087 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
Florian Hahn17554b82019-12-11 09:59:18 +00002088 for (auto &MBB : Fn) {
2089 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2090 Modified |= M;
2091 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002092
2093 return Modified;
2094}
2095
Chad Rosier8ade0342016-11-11 19:52:45 +00002096// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2097// stores near one another? Note: The pre-RA instruction scheduler already has
2098// hooks to try and schedule pairable loads/stores together to improve pairing
2099// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
Tim Northover3b0846e2014-05-24 12:50:23 +00002100
Chad Rosier3f8b09d2016-02-09 19:42:19 +00002101// FIXME: When pairing store instructions it's very possible for this pass to
2102// hoist a store with a KILL marker above another use (without a KILL marker).
2103// The resulting IR is invalid, but nothing uses the KILL markers after this
2104// pass, so it's never caused a problem in practice.
2105
Chad Rosier43f5c842015-08-05 12:40:13 +00002106/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2107/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00002108FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2109 return new AArch64LoadStoreOpt();
2110}