blob: cbca29b63b703137be010a333885563f41e801a0 [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
Florian Hahn8e3f59b2020-01-27 15:11:45 -080069// Enable register renaming to find additional store pairing opportunities.
70static cl::opt<bool> EnableRenaming("aarch64-load-store-renaming",
71 cl::init(false), cl::Hidden);
72
Chad Rosier96530b32015-08-05 13:44:51 +000073#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
74
Tim Northover3b0846e2014-05-24 12:50:23 +000075namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000076
Eugene Zelenko96d933d2017-07-25 23:51:02 +000077using LdStPairFlags = struct LdStPairFlags {
Chad Rosier96a18a92015-07-21 17:42:04 +000078 // If a matching instruction is found, MergeForward is set to true if the
79 // merge is to remove the first instruction and replace the second with
80 // a pair-wise insn, and false if the reverse is true.
Eugene Zelenko11f69072017-01-25 00:29:26 +000081 bool MergeForward = false;
Chad Rosier96a18a92015-07-21 17:42:04 +000082
83 // SExtIdx gives the index of the result of the load pair that must be
84 // extended. The value of SExtIdx assumes that the paired load produces the
85 // value in this order: (I, returned iterator), i.e., -1 means no value has
86 // to be extended, 0 means I, and 1 means the returned iterator.
Eugene Zelenko11f69072017-01-25 00:29:26 +000087 int SExtIdx = -1;
Chad Rosier96a18a92015-07-21 17:42:04 +000088
Florian Hahn17554b82019-12-11 09:59:18 +000089 // If not none, RenameReg can be used to rename the result register of the
90 // first store in a pair. Currently this only works when merging stores
91 // forward.
92 Optional<MCPhysReg> RenameReg = None;
93
Eugene Zelenko11f69072017-01-25 00:29:26 +000094 LdStPairFlags() = default;
Chad Rosier96a18a92015-07-21 17:42:04 +000095
96 void setMergeForward(bool V = true) { MergeForward = V; }
97 bool getMergeForward() const { return MergeForward; }
98
99 void setSExtIdx(int V) { SExtIdx = V; }
100 int getSExtIdx() const { return SExtIdx; }
Florian Hahn17554b82019-12-11 09:59:18 +0000101
102 void setRenameReg(MCPhysReg R) { RenameReg = R; }
103 void clearRenameReg() { RenameReg = None; }
104 Optional<MCPhysReg> getRenameReg() const { return RenameReg; }
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000105};
Chad Rosier96a18a92015-07-21 17:42:04 +0000106
Tim Northover3b0846e2014-05-24 12:50:23 +0000107struct AArch64LoadStoreOpt : public MachineFunctionPass {
108 static char ID;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000109
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000110 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +0000111 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
112 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000113
Chad Rosiera69dcb62017-03-17 14:19:55 +0000114 AliasAnalysis *AA;
Tim Northover3b0846e2014-05-24 12:50:23 +0000115 const AArch64InstrInfo *TII;
116 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000117 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +0000118
Jun Bum Lim47aece12018-04-27 18:44:37 +0000119 // Track which register units have been modified and used.
120 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
Florian Hahn17554b82019-12-11 09:59:18 +0000121 LiveRegUnits DefinedInBB;
Chad Rosierbba881e2016-02-02 15:02:30 +0000122
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000123 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiera69dcb62017-03-17 14:19:55 +0000124 AU.addRequired<AAResultsWrapperPass>();
125 MachineFunctionPass::getAnalysisUsage(AU);
126 }
127
Tim Northover3b0846e2014-05-24 12:50:23 +0000128 // Scan the instructions looking for a load/store that can be combined
129 // with the current instruction into a load/store pair.
130 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000132 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +0000133 unsigned Limit,
134 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000135
136 // Scan the instructions looking for a store that writes to the address from
137 // which the current load instruction reads. Return true if one is found.
138 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
139 MachineBasicBlock::iterator &StoreI);
140
Chad Rosierd6daac42016-11-07 15:27:22 +0000141 // Merge the two instructions indicated into a wider narrow store instruction.
Chad Rosierb5933d72016-02-09 19:02:12 +0000142 MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000143 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
144 MachineBasicBlock::iterator MergeMI,
145 const LdStPairFlags &Flags);
Chad Rosierb5933d72016-02-09 19:02:12 +0000146
Tim Northover3b0846e2014-05-24 12:50:23 +0000147 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000148 MachineBasicBlock::iterator
149 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000150 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000151 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000152
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000153 // Promote the load that reads directly from the address stored to.
154 MachineBasicBlock::iterator
155 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
156 MachineBasicBlock::iterator StoreI);
157
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 // Scan the instruction list to find a base register update that can
159 // be combined with the current instruction (a load or store) using
160 // pre or post indexed addressing with writeback. Scan forwards.
161 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000162 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000163 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000164
165 // Scan the instruction list to find a base register update that can
166 // be combined with the current instruction (a load or store) using
167 // pre or post indexed addressing with writeback. Scan backwards.
168 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000169 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000170
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000171 // Find an instruction that updates the base register of the ld/st
172 // instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000173 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000174 unsigned BaseReg, int Offset);
175
Chad Rosier2dfd3542015-09-23 13:51:44 +0000176 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000177 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000178 mergeUpdateInsn(MachineBasicBlock::iterator I,
179 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000180
Chad Rosierd6daac42016-11-07 15:27:22 +0000181 // Find and merge zero store instructions.
182 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000183
Chad Rosier24c46ad2016-02-09 18:10:20 +0000184 // Find and pair ldr/str instructions.
185 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
186
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000187 // Find and promote load instructions which read directly from store.
188 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
189
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000190 // Find and merge a base register updates before or after a ld/st instruction.
191 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
192
Chad Rosierd6daac42016-11-07 15:27:22 +0000193 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000194
195 bool runOnMachineFunction(MachineFunction &Fn) override;
196
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000197 MachineFunctionProperties getRequiredProperties() const override {
198 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000199 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000200 }
201
Mehdi Amini117296c2016-10-01 02:56:57 +0000202 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000203};
Eugene Zelenko11f69072017-01-25 00:29:26 +0000204
Tim Northover3b0846e2014-05-24 12:50:23 +0000205char AArch64LoadStoreOpt::ID = 0;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000206
207} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000208
Chad Rosier96530b32015-08-05 13:44:51 +0000209INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
210 AARCH64_LOAD_STORE_OPT_NAME, false, false)
211
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000212static bool isNarrowStore(unsigned Opc) {
213 switch (Opc) {
214 default:
215 return false;
216 case AArch64::STRBBui:
217 case AArch64::STURBBi:
218 case AArch64::STRHHui:
219 case AArch64::STURHHi:
220 return true;
221 }
222}
223
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000224// These instruction set memory tag and either keep memory contents unchanged or
225// set it to zero, ignoring the address part of the source register.
226static bool isTagStore(const MachineInstr &MI) {
227 switch (MI.getOpcode()) {
228 default:
229 return false;
230 case AArch64::STGOffset:
231 case AArch64::STZGOffset:
232 case AArch64::ST2GOffset:
233 case AArch64::STZ2GOffset:
234 return true;
235 }
236}
237
Quentin Colombet66b61632015-03-06 22:42:10 +0000238static unsigned getMatchingNonSExtOpcode(unsigned Opc,
239 bool *IsValidLdStrOpc = nullptr) {
240 if (IsValidLdStrOpc)
241 *IsValidLdStrOpc = true;
242 switch (Opc) {
243 default:
244 if (IsValidLdStrOpc)
245 *IsValidLdStrOpc = false;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000246 return std::numeric_limits<unsigned>::max();
Quentin Colombet66b61632015-03-06 22:42:10 +0000247 case AArch64::STRDui:
248 case AArch64::STURDi:
249 case AArch64::STRQui:
250 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000251 case AArch64::STRBBui:
252 case AArch64::STURBBi:
253 case AArch64::STRHHui:
254 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000255 case AArch64::STRWui:
256 case AArch64::STURWi:
257 case AArch64::STRXui:
258 case AArch64::STURXi:
259 case AArch64::LDRDui:
260 case AArch64::LDURDi:
261 case AArch64::LDRQui:
262 case AArch64::LDURQi:
263 case AArch64::LDRWui:
264 case AArch64::LDURWi:
265 case AArch64::LDRXui:
266 case AArch64::LDURXi:
267 case AArch64::STRSui:
268 case AArch64::STURSi:
269 case AArch64::LDRSui:
270 case AArch64::LDURSi:
271 return Opc;
272 case AArch64::LDRSWui:
273 return AArch64::LDRWui;
274 case AArch64::LDURSWi:
275 return AArch64::LDURWi;
276 }
277}
278
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000279static unsigned getMatchingWideOpcode(unsigned Opc) {
280 switch (Opc) {
281 default:
282 llvm_unreachable("Opcode has no wide equivalent!");
283 case AArch64::STRBBui:
284 return AArch64::STRHHui;
285 case AArch64::STRHHui:
286 return AArch64::STRWui;
287 case AArch64::STURBBi:
288 return AArch64::STURHHi;
289 case AArch64::STURHHi:
290 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000291 case AArch64::STURWi:
292 return AArch64::STURXi;
293 case AArch64::STRWui:
294 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000295 }
296}
297
Tim Northover3b0846e2014-05-24 12:50:23 +0000298static unsigned getMatchingPairOpcode(unsigned Opc) {
299 switch (Opc) {
300 default:
301 llvm_unreachable("Opcode has no pairwise equivalent!");
302 case AArch64::STRSui:
303 case AArch64::STURSi:
304 return AArch64::STPSi;
305 case AArch64::STRDui:
306 case AArch64::STURDi:
307 return AArch64::STPDi;
308 case AArch64::STRQui:
309 case AArch64::STURQi:
310 return AArch64::STPQi;
311 case AArch64::STRWui:
312 case AArch64::STURWi:
313 return AArch64::STPWi;
314 case AArch64::STRXui:
315 case AArch64::STURXi:
316 return AArch64::STPXi;
317 case AArch64::LDRSui:
318 case AArch64::LDURSi:
319 return AArch64::LDPSi;
320 case AArch64::LDRDui:
321 case AArch64::LDURDi:
322 return AArch64::LDPDi;
323 case AArch64::LDRQui:
324 case AArch64::LDURQi:
325 return AArch64::LDPQi;
326 case AArch64::LDRWui:
327 case AArch64::LDURWi:
328 return AArch64::LDPWi;
329 case AArch64::LDRXui:
330 case AArch64::LDURXi:
331 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000332 case AArch64::LDRSWui:
333 case AArch64::LDURSWi:
334 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000335 }
336}
337
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000338static unsigned isMatchingStore(MachineInstr &LoadInst,
339 MachineInstr &StoreInst) {
340 unsigned LdOpc = LoadInst.getOpcode();
341 unsigned StOpc = StoreInst.getOpcode();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000342 switch (LdOpc) {
343 default:
344 llvm_unreachable("Unsupported load instruction!");
345 case AArch64::LDRBBui:
346 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
347 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
348 case AArch64::LDURBBi:
349 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
350 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
351 case AArch64::LDRHHui:
352 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
353 StOpc == AArch64::STRXui;
354 case AArch64::LDURHHi:
355 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
356 StOpc == AArch64::STURXi;
357 case AArch64::LDRWui:
358 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
359 case AArch64::LDURWi:
360 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
361 case AArch64::LDRXui:
362 return StOpc == AArch64::STRXui;
363 case AArch64::LDURXi:
364 return StOpc == AArch64::STURXi;
365 }
366}
367
Tim Northover3b0846e2014-05-24 12:50:23 +0000368static unsigned getPreIndexedOpcode(unsigned Opc) {
Chad Rosier14fc82a2017-08-04 16:44:06 +0000369 // FIXME: We don't currently support creating pre-indexed loads/stores when
370 // the load or store is the unscaled version. If we decide to perform such an
371 // optimization in the future the cases for the unscaled loads/stores will
372 // need to be added here.
Tim Northover3b0846e2014-05-24 12:50:23 +0000373 switch (Opc) {
374 default:
375 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000376 case AArch64::STRSui:
377 return AArch64::STRSpre;
378 case AArch64::STRDui:
379 return AArch64::STRDpre;
380 case AArch64::STRQui:
381 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000382 case AArch64::STRBBui:
383 return AArch64::STRBBpre;
384 case AArch64::STRHHui:
385 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000386 case AArch64::STRWui:
387 return AArch64::STRWpre;
388 case AArch64::STRXui:
389 return AArch64::STRXpre;
390 case AArch64::LDRSui:
391 return AArch64::LDRSpre;
392 case AArch64::LDRDui:
393 return AArch64::LDRDpre;
394 case AArch64::LDRQui:
395 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000396 case AArch64::LDRBBui:
397 return AArch64::LDRBBpre;
398 case AArch64::LDRHHui:
399 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000400 case AArch64::LDRWui:
401 return AArch64::LDRWpre;
402 case AArch64::LDRXui:
403 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000404 case AArch64::LDRSWui:
405 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000406 case AArch64::LDPSi:
407 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000408 case AArch64::LDPSWi:
409 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000410 case AArch64::LDPDi:
411 return AArch64::LDPDpre;
412 case AArch64::LDPQi:
413 return AArch64::LDPQpre;
414 case AArch64::LDPWi:
415 return AArch64::LDPWpre;
416 case AArch64::LDPXi:
417 return AArch64::LDPXpre;
418 case AArch64::STPSi:
419 return AArch64::STPSpre;
420 case AArch64::STPDi:
421 return AArch64::STPDpre;
422 case AArch64::STPQi:
423 return AArch64::STPQpre;
424 case AArch64::STPWi:
425 return AArch64::STPWpre;
426 case AArch64::STPXi:
427 return AArch64::STPXpre;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000428 case AArch64::STGOffset:
429 return AArch64::STGPreIndex;
430 case AArch64::STZGOffset:
431 return AArch64::STZGPreIndex;
432 case AArch64::ST2GOffset:
433 return AArch64::ST2GPreIndex;
434 case AArch64::STZ2GOffset:
435 return AArch64::STZ2GPreIndex;
436 case AArch64::STGPi:
437 return AArch64::STGPpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 }
439}
440
441static unsigned getPostIndexedOpcode(unsigned Opc) {
442 switch (Opc) {
443 default:
444 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
445 case AArch64::STRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000446 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000447 return AArch64::STRSpost;
448 case AArch64::STRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000449 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 return AArch64::STRDpost;
451 case AArch64::STRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000452 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000454 case AArch64::STRBBui:
455 return AArch64::STRBBpost;
456 case AArch64::STRHHui:
457 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000458 case AArch64::STRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000459 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 return AArch64::STRWpost;
461 case AArch64::STRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000462 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000463 return AArch64::STRXpost;
464 case AArch64::LDRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000465 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000466 return AArch64::LDRSpost;
467 case AArch64::LDRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000468 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 return AArch64::LDRDpost;
470 case AArch64::LDRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000471 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000472 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000473 case AArch64::LDRBBui:
474 return AArch64::LDRBBpost;
475 case AArch64::LDRHHui:
476 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 case AArch64::LDRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000478 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 return AArch64::LDRWpost;
480 case AArch64::LDRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000481 case AArch64::LDURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000482 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000483 case AArch64::LDRSWui:
484 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000485 case AArch64::LDPSi:
486 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000487 case AArch64::LDPSWi:
488 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000489 case AArch64::LDPDi:
490 return AArch64::LDPDpost;
491 case AArch64::LDPQi:
492 return AArch64::LDPQpost;
493 case AArch64::LDPWi:
494 return AArch64::LDPWpost;
495 case AArch64::LDPXi:
496 return AArch64::LDPXpost;
497 case AArch64::STPSi:
498 return AArch64::STPSpost;
499 case AArch64::STPDi:
500 return AArch64::STPDpost;
501 case AArch64::STPQi:
502 return AArch64::STPQpost;
503 case AArch64::STPWi:
504 return AArch64::STPWpost;
505 case AArch64::STPXi:
506 return AArch64::STPXpost;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000507 case AArch64::STGOffset:
508 return AArch64::STGPostIndex;
509 case AArch64::STZGOffset:
510 return AArch64::STZGPostIndex;
511 case AArch64::ST2GOffset:
512 return AArch64::ST2GPostIndex;
513 case AArch64::STZ2GOffset:
514 return AArch64::STZ2GPostIndex;
515 case AArch64::STGPi:
516 return AArch64::STGPpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000517 }
518}
519
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000520static bool isPairedLdSt(const MachineInstr &MI) {
521 switch (MI.getOpcode()) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000522 default:
523 return false;
524 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000525 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000526 case AArch64::LDPDi:
527 case AArch64::LDPQi:
528 case AArch64::LDPWi:
529 case AArch64::LDPXi:
530 case AArch64::STPSi:
531 case AArch64::STPDi:
532 case AArch64::STPQi:
533 case AArch64::STPWi:
534 case AArch64::STPXi:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000535 case AArch64::STGPi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000536 return true;
537 }
538}
539
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000540// Returns the scale and offset range of pre/post indexed variants of MI.
541static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
542 int &MinOffset, int &MaxOffset) {
543 bool IsPaired = isPairedLdSt(MI);
544 bool IsTagStore = isTagStore(MI);
545 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
546 // as in the "unsigned offset" variant.
547 // All other pre/post indexed ldst instructions are unscaled.
Jay Foad97ca7c22019-12-11 10:29:23 +0000548 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000549
550 if (IsPaired) {
551 MinOffset = -64;
552 MaxOffset = 63;
553 } else {
554 MinOffset = -256;
555 MaxOffset = 255;
556 }
557}
558
Florian Hahn17554b82019-12-11 09:59:18 +0000559static MachineOperand &getLdStRegOp(MachineInstr &MI,
560 unsigned PairedRegOp = 0) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000561 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
562 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000563 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000564}
565
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000566static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000568 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000569}
570
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000571static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000572 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000573 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000574}
575
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000576static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
577 MachineInstr &StoreInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000578 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000579 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000580 int LoadSize = TII->getMemScale(LoadInst);
581 int StoreSize = TII->getMemScale(StoreInst);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000582 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000583 ? getLdStOffsetOp(StoreInst).getImm()
584 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000585 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000586 ? getLdStOffsetOp(LoadInst).getImm()
587 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
588 return (UnscaledStOffset <= UnscaledLdOffset) &&
589 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
590}
591
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000592static bool isPromotableZeroStoreInst(MachineInstr &MI) {
Chad Rosierd6daac42016-11-07 15:27:22 +0000593 unsigned Opc = MI.getOpcode();
594 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
595 isNarrowStore(Opc)) &&
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000596 getLdStRegOp(MI).getReg() == AArch64::WZR;
597}
598
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000599static bool isPromotableLoadFromStore(MachineInstr &MI) {
600 switch (MI.getOpcode()) {
601 default:
602 return false;
603 // Scaled instructions.
604 case AArch64::LDRBBui:
605 case AArch64::LDRHHui:
606 case AArch64::LDRWui:
607 case AArch64::LDRXui:
608 // Unscaled instructions.
609 case AArch64::LDURBBi:
610 case AArch64::LDURHHi:
611 case AArch64::LDURWi:
612 case AArch64::LDURXi:
613 return true;
614 }
615}
616
617static bool isMergeableLdStUpdate(MachineInstr &MI) {
618 unsigned Opc = MI.getOpcode();
619 switch (Opc) {
620 default:
621 return false;
622 // Scaled instructions.
623 case AArch64::STRSui:
624 case AArch64::STRDui:
625 case AArch64::STRQui:
626 case AArch64::STRXui:
627 case AArch64::STRWui:
628 case AArch64::STRHHui:
629 case AArch64::STRBBui:
630 case AArch64::LDRSui:
631 case AArch64::LDRDui:
632 case AArch64::LDRQui:
633 case AArch64::LDRXui:
634 case AArch64::LDRWui:
635 case AArch64::LDRHHui:
636 case AArch64::LDRBBui:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000637 case AArch64::STGOffset:
638 case AArch64::STZGOffset:
639 case AArch64::ST2GOffset:
640 case AArch64::STZ2GOffset:
641 case AArch64::STGPi:
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000642 // Unscaled instructions.
643 case AArch64::STURSi:
644 case AArch64::STURDi:
645 case AArch64::STURQi:
646 case AArch64::STURWi:
647 case AArch64::STURXi:
648 case AArch64::LDURSi:
649 case AArch64::LDURDi:
650 case AArch64::LDURQi:
651 case AArch64::LDURWi:
652 case AArch64::LDURXi:
653 // Paired instructions.
654 case AArch64::LDPSi:
655 case AArch64::LDPSWi:
656 case AArch64::LDPDi:
657 case AArch64::LDPQi:
658 case AArch64::LDPWi:
659 case AArch64::LDPXi:
660 case AArch64::STPSi:
661 case AArch64::STPDi:
662 case AArch64::STPQi:
663 case AArch64::STPWi:
664 case AArch64::STPXi:
665 // Make sure this is a reg+imm (as opposed to an address reloc).
666 if (!getLdStOffsetOp(MI).isImm())
667 return false;
668
669 return true;
670 }
671}
672
Tim Northover3b0846e2014-05-24 12:50:23 +0000673MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000674AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
675 MachineBasicBlock::iterator MergeMI,
676 const LdStPairFlags &Flags) {
677 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
678 "Expected promotable zero stores.");
679
Tim Northover3b0846e2014-05-24 12:50:23 +0000680 MachineBasicBlock::iterator NextI = I;
681 ++NextI;
682 // If NextI is the second of the two instructions to be merged, we need
683 // to skip one further. Either way we merge will invalidate the iterator,
684 // and we don't need to scan the new instruction, as it's a pairwise
685 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000686 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000687 ++NextI;
688
Chad Rosierb5933d72016-02-09 19:02:12 +0000689 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000690 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000691 int OffsetStride = IsScaled ? 1 : TII->getMemScale(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000692
Chad Rosier96a18a92015-07-21 17:42:04 +0000693 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000694 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000695 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000696 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000697 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000698 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000699 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000700 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000701
702 // Which register is Rt and which is Rt2 depends on the offset order.
Davide Italiano5df60662016-11-07 19:11:25 +0000703 MachineInstr *RtMI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000704 if (getLdStOffsetOp(*I).getImm() ==
Davide Italiano5df60662016-11-07 19:11:25 +0000705 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000706 RtMI = &*MergeMI;
Davide Italiano5df60662016-11-07 19:11:25 +0000707 else
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000708 RtMI = &*I;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000709
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000710 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000711 // Change the scaled offset from small to large type.
712 if (IsScaled) {
713 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
714 OffsetImm /= 2;
715 }
716
Chad Rosierd6daac42016-11-07 15:27:22 +0000717 // Construct the new instruction.
Chad Rosierc46ef882016-02-09 19:33:42 +0000718 DebugLoc DL = I->getDebugLoc();
719 MachineBasicBlock *MBB = I->getParent();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000720 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000721 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000722 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Diana Picus116bbab2017-01-13 09:58:52 +0000723 .add(BaseRegOp)
Chad Rosierb5933d72016-02-09 19:02:12 +0000724 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000725 .cloneMergedMemRefs({&*I, &*MergeMI})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000726 .setMIFlags(I->mergeFlagsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000727 (void)MIB;
728
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000729 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
730 LLVM_DEBUG(I->print(dbgs()));
731 LLVM_DEBUG(dbgs() << " ");
732 LLVM_DEBUG(MergeMI->print(dbgs()));
733 LLVM_DEBUG(dbgs() << " with instruction:\n ");
734 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
735 LLVM_DEBUG(dbgs() << "\n");
Chad Rosierb5933d72016-02-09 19:02:12 +0000736
737 // Erase the old instructions.
738 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000739 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000740 return NextI;
741}
742
Florian Hahn17554b82019-12-11 09:59:18 +0000743// Apply Fn to all instructions between MI and the beginning of the block, until
744// a def for DefReg is reached. Returns true, iff Fn returns true for all
745// visited instructions. Stop after visiting Limit iterations.
746static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg,
747 const TargetRegisterInfo *TRI, unsigned Limit,
748 std::function<bool(MachineInstr &, bool)> &Fn) {
749 auto MBB = MI.getParent();
750 for (MachineBasicBlock::reverse_iterator I = MI.getReverseIterator(),
751 E = MBB->rend();
752 I != E; I++) {
753 if (!Limit)
754 return false;
755 --Limit;
756
757 bool isDef = any_of(I->operands(), [DefReg, TRI](MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000758 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000759 TRI->regsOverlap(MOP.getReg(), DefReg);
760 });
761 if (!Fn(*I, isDef))
762 return false;
763 if (isDef)
764 break;
765 }
766 return true;
767}
768
769static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
770 const TargetRegisterInfo *TRI) {
771
772 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
773 if (MOP.isReg() && MOP.isKill())
774 Units.removeReg(MOP.getReg());
775
776 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
777 if (MOP.isReg() && !MOP.isKill())
778 Units.addReg(MOP.getReg());
779}
780
Chad Rosierb5933d72016-02-09 19:02:12 +0000781MachineBasicBlock::iterator
782AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
783 MachineBasicBlock::iterator Paired,
784 const LdStPairFlags &Flags) {
785 MachineBasicBlock::iterator NextI = I;
786 ++NextI;
787 // If NextI is the second of the two instructions to be merged, we need
788 // to skip one further. Either way we merge will invalidate the iterator,
789 // and we don't need to scan the new instruction, as it's a pairwise
790 // instruction, which we're not considering for further action anyway.
791 if (NextI == Paired)
792 ++NextI;
793
794 int SExtIdx = Flags.getSExtIdx();
795 unsigned Opc =
796 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000797 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000798 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
Chad Rosierb5933d72016-02-09 19:02:12 +0000799
800 bool MergeForward = Flags.getMergeForward();
Florian Hahn17554b82019-12-11 09:59:18 +0000801
802 Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
803 if (MergeForward && RenameReg) {
804 MCRegister RegToRename = getLdStRegOp(*I).getReg();
805 DefinedInBB.addReg(*RenameReg);
806
807 // Return the sub/super register for RenameReg, matching the size of
808 // OriginalReg.
809 auto GetMatchingSubReg = [this,
810 RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
811 for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
812 if (TRI->getMinimalPhysRegClass(OriginalReg) ==
813 TRI->getMinimalPhysRegClass(SubOrSuper))
814 return SubOrSuper;
815 llvm_unreachable("Should have found matching sub or super register!");
816 };
817
818 std::function<bool(MachineInstr &, bool)> UpdateMIs =
819 [this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
820 if (IsDef) {
821 bool SeenDef = false;
822 for (auto &MOP : MI.operands()) {
823 // Rename the first explicit definition and all implicit
824 // definitions matching RegToRename.
Florian Hahn2675a3c2019-12-11 17:17:29 +0000825 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000826 (!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
827 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
828 assert((MOP.isImplicit() ||
829 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
830 "Need renamable operands");
831 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
832 SeenDef = true;
833 }
834 }
835 } else {
836 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000837 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
838 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
Bill Wendlingdc03b962019-12-20 12:47:38 -0800839 assert((MOP.isImplicit() ||
840 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
Florian Hahn17554b82019-12-11 09:59:18 +0000841 "Need renamable operands");
842 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
843 }
844 }
845 }
846 LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
847 return true;
848 };
849 forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
850
Fangrui Song25e21a02019-12-11 10:59:45 -0800851#if !defined(NDEBUG)
Florian Hahn17554b82019-12-11 09:59:18 +0000852 // Make sure the register used for renaming is not used between the paired
853 // instructions. That would trash the content before the new paired
854 // instruction.
855 for (auto &MI :
856 iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
857 std::next(I), std::next(Paired)))
858 assert(all_of(MI.operands(),
859 [this, &RenameReg](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000860 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +0000861 !TRI->regsOverlap(MOP.getReg(), *RenameReg);
862 }) &&
863 "Rename register used between paired instruction, trashing the "
864 "content");
Fangrui Song25e21a02019-12-11 10:59:45 -0800865#endif
Florian Hahn17554b82019-12-11 09:59:18 +0000866 }
867
Chad Rosierb5933d72016-02-09 19:02:12 +0000868 // Insert our new paired instruction after whichever of the paired
869 // instructions MergeForward indicates.
870 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
871 // Also based on MergeForward is from where we copy the base register operand
872 // so we get the flags compatible with the input code.
873 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000874 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
Chad Rosierb5933d72016-02-09 19:02:12 +0000875
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000876 int Offset = getLdStOffsetOp(*I).getImm();
877 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000878 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000879 if (IsUnscaled != PairedIsUnscaled) {
880 // We're trying to pair instructions that differ in how they are scaled. If
881 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
882 // the opposite (i.e., make Paired's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +0000883 int MemSize = TII->getMemScale(*Paired);
Chad Rosier00f9d232016-02-11 14:25:08 +0000884 if (PairedIsUnscaled) {
885 // If the unscaled offset isn't a multiple of the MemSize, we can't
886 // pair the operations together.
Jay Foad97ca7c22019-12-11 10:29:23 +0000887 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000888 "Offset should be a multiple of the stride!");
889 PairedOffset /= MemSize;
890 } else {
891 PairedOffset *= MemSize;
892 }
893 }
894
Chad Rosierb5933d72016-02-09 19:02:12 +0000895 // Which register is Rt and which is Rt2 depends on the offset order.
896 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000897 if (Offset == PairedOffset + OffsetStride) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000898 RtMI = &*Paired;
899 Rt2MI = &*I;
Chad Rosierb5933d72016-02-09 19:02:12 +0000900 // Here we swapped the assumption made for SExtIdx.
901 // I.e., we turn ldp I, Paired into ldp Paired, I.
902 // Update the index accordingly.
903 if (SExtIdx != -1)
904 SExtIdx = (SExtIdx + 1) % 2;
905 } else {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000906 RtMI = &*I;
907 Rt2MI = &*Paired;
Chad Rosierb5933d72016-02-09 19:02:12 +0000908 }
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000909 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000910 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000911 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Jay Foad97ca7c22019-12-11 10:29:23 +0000912 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000913 "Unscaled offset cannot be scaled.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000914 OffsetImm /= TII->getMemScale(*RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000915 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000916
917 // Construct the new instruction.
918 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000919 DebugLoc DL = I->getDebugLoc();
920 MachineBasicBlock *MBB = I->getParent();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000921 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
922 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
923 // Kill flags may become invalid when moving stores for pairing.
924 if (RegOp0.isUse()) {
925 if (!MergeForward) {
926 // Clear kill flags on store if moving upwards. Example:
927 // STRWui %w0, ...
928 // USE %w1
929 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
930 RegOp0.setIsKill(false);
931 RegOp1.setIsKill(false);
932 } else {
933 // Clear kill flags of the first stores register. Example:
934 // STRWui %w1, ...
935 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
936 // STRW %w0
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000937 Register Reg = getLdStRegOp(*I).getReg();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000938 for (MachineInstr &MI : make_range(std::next(I), Paired))
939 MI.clearRegisterKills(Reg, TRI);
940 }
941 }
Chad Rosierc46ef882016-02-09 19:33:42 +0000942 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000943 .add(RegOp0)
944 .add(RegOp1)
Diana Picus116bbab2017-01-13 09:58:52 +0000945 .add(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000946 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000947 .cloneMergedMemRefs({&*I, &*Paired})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000948 .setMIFlags(I->mergeFlagsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000949
950 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000951
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000952 LLVM_DEBUG(
953 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
954 LLVM_DEBUG(I->print(dbgs()));
955 LLVM_DEBUG(dbgs() << " ");
956 LLVM_DEBUG(Paired->print(dbgs()));
957 LLVM_DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000958 if (SExtIdx != -1) {
959 // Generate the sign extension for the proper result of the ldp.
960 // I.e., with X1, that would be:
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000961 // %w1 = KILL %w1, implicit-def %x1
962 // %x1 = SBFMXri killed %x1, 0, 31
Quentin Colombet66b61632015-03-06 22:42:10 +0000963 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
964 // Right now, DstMO has the extended register, since it comes from an
965 // extended opcode.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000966 Register DstRegX = DstMO.getReg();
Quentin Colombet66b61632015-03-06 22:42:10 +0000967 // Get the W variant of that register.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000968 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
Quentin Colombet66b61632015-03-06 22:42:10 +0000969 // Update the result of LDP to use the W instead of the X variant.
970 DstMO.setReg(DstRegW);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000971 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
972 LLVM_DEBUG(dbgs() << "\n");
Quentin Colombet66b61632015-03-06 22:42:10 +0000973 // Make the machine verifier happy by providing a definition for
974 // the X register.
975 // Insert this definition right after the generated LDP, i.e., before
976 // InsertionPoint.
977 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000978 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000979 .addReg(DstRegW)
980 .addReg(DstRegX, RegState::Define);
981 MIBKill->getOperand(2).setImplicit();
982 // Create the sign extension.
983 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000984 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000985 .addReg(DstRegX)
986 .addImm(0)
987 .addImm(31);
988 (void)MIBSXTW;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000989 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
990 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000991 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000992 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000993 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000994 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000995
Florian Hahn17554b82019-12-11 09:59:18 +0000996 if (MergeForward)
997 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
998 if (MOP.isReg() && MOP.isKill())
999 DefinedInBB.addReg(MOP.getReg());
1000
Tim Northover3b0846e2014-05-24 12:50:23 +00001001 // Erase the old instructions.
1002 I->eraseFromParent();
1003 Paired->eraseFromParent();
1004
1005 return NextI;
1006}
1007
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001008MachineBasicBlock::iterator
1009AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1010 MachineBasicBlock::iterator StoreI) {
1011 MachineBasicBlock::iterator NextI = LoadI;
1012 ++NextI;
1013
Jay Foad97ca7c22019-12-11 10:29:23 +00001014 int LoadSize = TII->getMemScale(*LoadI);
1015 int StoreSize = TII->getMemScale(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001016 Register LdRt = getLdStRegOp(*LoadI).getReg();
Florian Hahn80e48512017-06-21 08:47:23 +00001017 const MachineOperand &StMO = getLdStRegOp(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001018 Register StRt = getLdStRegOp(*StoreI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001019 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1020
1021 assert((IsStoreXReg ||
1022 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1023 "Unexpected RegClass");
1024
1025 MachineInstr *BitExtMI;
1026 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1027 // Remove the load, if the destination register of the loads is the same
1028 // register for stored value.
1029 if (StRt == LdRt && LoadSize == 8) {
Tim Northover9ac3e422017-06-26 18:49:25 +00001030 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1031 LoadI->getIterator())) {
1032 if (MI.killsRegister(StRt, TRI)) {
1033 MI.clearRegisterKills(StRt, TRI);
1034 break;
1035 }
1036 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001037 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1038 LLVM_DEBUG(LoadI->print(dbgs()));
1039 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001040 LoadI->eraseFromParent();
1041 return NextI;
1042 }
1043 // Replace the load with a mov if the load and store are in the same size.
1044 BitExtMI =
1045 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1046 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1047 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
Florian Hahn80e48512017-06-21 08:47:23 +00001048 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001049 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1050 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001051 } else {
1052 // FIXME: Currently we disable this transformation in big-endian targets as
1053 // performance and correctness are verified only in little-endian.
1054 if (!Subtarget->isLittleEndian())
1055 return NextI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001056 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
1057 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001058 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001059 assert(LoadSize <= StoreSize && "Invalid load size");
1060 int UnscaledLdOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001061 ? getLdStOffsetOp(*LoadI).getImm()
1062 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001063 int UnscaledStOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001064 ? getLdStOffsetOp(*StoreI).getImm()
1065 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001066 int Width = LoadSize * 8;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001067 unsigned DestReg =
1068 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1069 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1070 : LdRt;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001071
1072 assert((UnscaledLdOffset >= UnscaledStOffset &&
1073 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1074 "Invalid offset");
1075
Simon Pilgrime461e9a2019-05-08 16:29:39 +00001076 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1077 int Imms = Immr + Width - 1;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001078 if (UnscaledLdOffset == UnscaledStOffset) {
1079 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1080 | ((Immr) << 6) // immr
1081 | ((Imms) << 0) // imms
1082 ;
1083
1084 BitExtMI =
1085 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1086 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1087 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001088 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001089 .addImm(AndMaskEncoded)
1090 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001091 } else {
1092 BitExtMI =
1093 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1094 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1095 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001096 .add(StMO)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001097 .addImm(Immr)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001098 .addImm(Imms)
1099 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001100 }
1101 }
Matthias Braun76bb4132016-12-16 23:55:43 +00001102
Matthias Braund9a59a82017-02-17 23:15:03 +00001103 // Clear kill flags between store and load.
1104 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1105 BitExtMI->getIterator()))
Florian Hahn8552e592017-06-21 09:51:52 +00001106 if (MI.killsRegister(StRt, TRI)) {
1107 MI.clearRegisterKills(StRt, TRI);
1108 break;
1109 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001110
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001111 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1112 LLVM_DEBUG(StoreI->print(dbgs()));
1113 LLVM_DEBUG(dbgs() << " ");
1114 LLVM_DEBUG(LoadI->print(dbgs()));
1115 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1116 LLVM_DEBUG(StoreI->print(dbgs()));
1117 LLVM_DEBUG(dbgs() << " ");
1118 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1119 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001120
1121 // Erase the old instructions.
1122 LoadI->eraseFromParent();
1123 return NextI;
1124}
1125
Tim Northover3b0846e2014-05-24 12:50:23 +00001126static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001127 // Convert the byte-offset used by unscaled into an "element" offset used
1128 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001129 if (IsUnscaled) {
1130 // If the byte-offset isn't a multiple of the stride, there's no point
1131 // trying to match it.
1132 if (Offset % OffsetStride)
1133 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001134 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001135 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001136 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001137}
1138
1139// Do alignment, specialized to power of 2 and for signed ints,
1140// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001141// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001142// FIXME: Move this function to include/MathExtras.h?
1143static int alignTo(int Num, int PowOf2) {
1144 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1145}
1146
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001147static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001148 AliasAnalysis *AA) {
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001149 // One of the instructions must modify memory.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001150 if (!MIa.mayStore() && !MIb.mayStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001151 return false;
1152
1153 // Both instructions must be memory operations.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001154 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001155 return false;
1156
Chad Rosiera69dcb62017-03-17 14:19:55 +00001157 return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001158}
1159
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001160static bool mayAlias(MachineInstr &MIa,
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001161 SmallVectorImpl<MachineInstr *> &MemInsns,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001162 AliasAnalysis *AA) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001163 for (MachineInstr *MIb : MemInsns)
Chad Rosiera69dcb62017-03-17 14:19:55 +00001164 if (mayAlias(MIa, *MIb, AA))
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001165 return true;
1166
1167 return false;
1168}
1169
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001170bool AArch64LoadStoreOpt::findMatchingStore(
1171 MachineBasicBlock::iterator I, unsigned Limit,
1172 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001173 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001174 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001175 MachineInstr &LoadMI = *I;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001176 Register BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001177
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001178 // If the load is the first instruction in the block, there's obviously
1179 // not any matching store.
1180 if (MBBI == B)
1181 return false;
1182
Jun Bum Lim47aece12018-04-27 18:44:37 +00001183 // Track which register units have been modified and used between the first
1184 // insn and the second insn.
1185 ModifiedRegUnits.clear();
1186 UsedRegUnits.clear();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001187
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001188 unsigned Count = 0;
1189 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001190 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001191 MachineInstr &MI = *MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001192
Geoff Berry4ff2e362016-07-21 15:20:25 +00001193 // Don't count transient instructions towards the search limit since there
1194 // may be different numbers of them if e.g. debug information is present.
1195 if (!MI.isTransient())
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001196 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001197
1198 // If the load instruction reads directly from the address to which the
1199 // store instruction writes and the stored value is not modified, we can
1200 // promote the load. Since we do not handle stores with pre-/post-index,
1201 // it's unnecessary to check if BaseReg is modified by the store itself.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001202 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001203 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001204 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001205 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001206 StoreI = MBBI;
1207 return true;
1208 }
1209
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001210 if (MI.isCall())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001211 return false;
1212
Jun Bum Lim47aece12018-04-27 18:44:37 +00001213 // Update modified / uses register units.
1214 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001215
1216 // Otherwise, if the base register is modified, we have no match, so
1217 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001218 if (!ModifiedRegUnits.available(BaseReg))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001219 return false;
1220
1221 // If we encounter a store aliased with the load, return early.
Chad Rosiera69dcb62017-03-17 14:19:55 +00001222 if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001223 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001224 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001225 return false;
1226}
1227
Chad Rosierc5083c22016-06-10 20:47:14 +00001228// Returns true if FirstMI and MI are candidates for merging or pairing.
1229// Otherwise, returns false.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001230static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
Chad Rosierc5083c22016-06-10 20:47:14 +00001231 LdStPairFlags &Flags,
1232 const AArch64InstrInfo *TII) {
1233 // If this is volatile or if pairing is suppressed, not a candidate.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001234 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
Chad Rosierc5083c22016-06-10 20:47:14 +00001235 return false;
1236
1237 // We should have already checked FirstMI for pair suppression and volatility.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001238 assert(!FirstMI.hasOrderedMemoryRef() &&
1239 !TII->isLdStPairSuppressed(FirstMI) &&
Chad Rosierc5083c22016-06-10 20:47:14 +00001240 "FirstMI shouldn't get here if either of these checks are true.");
1241
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001242 unsigned OpcA = FirstMI.getOpcode();
1243 unsigned OpcB = MI.getOpcode();
Chad Rosierc5083c22016-06-10 20:47:14 +00001244
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001245 // Opcodes match: nothing more to check.
1246 if (OpcA == OpcB)
1247 return true;
1248
1249 // Try to match a sign-extended load/store with a zero-extended load/store.
1250 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1251 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1252 assert(IsValidLdStrOpc &&
1253 "Given Opc should be a Load or Store with an immediate");
1254 // OpcA will be the first instruction in the pair.
1255 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1256 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1257 return true;
1258 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001259
Chad Rosierd6daac42016-11-07 15:27:22 +00001260 // If the second instruction isn't even a mergable/pairable load/store, bail
1261 // out.
Chad Rosier00f9d232016-02-11 14:25:08 +00001262 if (!PairIsValidLdStrOpc)
1263 return false;
1264
Chad Rosierd6daac42016-11-07 15:27:22 +00001265 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1266 // offsets.
1267 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
Chad Rosier00f9d232016-02-11 14:25:08 +00001268 return false;
1269
1270 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001271 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001272 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1273
1274 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001275}
1276
Florian Hahn17554b82019-12-11 09:59:18 +00001277static bool
1278canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1279 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1280 const TargetRegisterInfo *TRI) {
1281 if (!FirstMI.mayStore())
1282 return false;
1283
1284 // Check if we can find an unused register which we can use to rename
1285 // the register used by the first load/store.
1286 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1287 MachineFunction &MF = *FirstMI.getParent()->getParent();
1288 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1289 return false;
1290
1291 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1292 // For now, we only rename if the store operand gets killed at the store.
1293 if (!getLdStRegOp(FirstMI).isKill() &&
1294 !any_of(FirstMI.operands(),
1295 [TRI, RegToRename](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001296 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1297 MOP.isImplicit() && MOP.isKill() &&
Florian Hahn17554b82019-12-11 09:59:18 +00001298 TRI->regsOverlap(RegToRename, MOP.getReg());
1299 })) {
1300 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI << "\n");
1301 return false;
1302 }
1303 auto canRenameMOP = [](const MachineOperand &MOP) {
1304 return MOP.isImplicit() ||
1305 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1306 };
1307
1308 bool FoundDef = false;
1309
1310 // For each instruction between FirstMI and the previous def for RegToRename,
1311 // we
1312 // * check if we can rename RegToRename in this instruction
1313 // * collect the registers used and required register classes for RegToRename.
1314 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1315 bool IsDef) {
1316 LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1317 // Currently we do not try to rename across frame-setup instructions.
1318 if (MI.getFlag(MachineInstr::FrameSetup)) {
1319 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions currently ("
1320 << MI << ")\n");
1321 return false;
1322 }
1323
1324 UsedInBetween.accumulate(MI);
1325
1326 // For a definition, check that we can rename the definition and exit the
1327 // loop.
1328 FoundDef = IsDef;
1329
1330 // For defs, check if we can rename the first def of RegToRename.
1331 if (FoundDef) {
Florian Hahn300997c2020-01-22 09:16:40 -08001332 // For some pseudo instructions, we might not generate code in the end
1333 // (e.g. KILL) and we would end up without a correct def for the rename
1334 // register.
1335 // TODO: This might be overly conservative and we could handle those cases
1336 // in multiple ways:
1337 // 1. Insert an extra copy, to materialize the def.
1338 // 2. Skip pseudo-defs until we find an non-pseudo def.
1339 if (MI.isPseudo()) {
1340 LLVM_DEBUG(dbgs() << " Cannot rename pseudo instruction " << MI
1341 << "\n");
1342 return false;
1343 }
1344
Florian Hahn17554b82019-12-11 09:59:18 +00001345 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001346 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +00001347 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1348 continue;
1349 if (!canRenameMOP(MOP)) {
1350 LLVM_DEBUG(dbgs()
1351 << " Cannot rename " << MOP << " in " << MI << "\n");
1352 return false;
1353 }
1354 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1355 }
1356 return true;
1357 } else {
1358 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001359 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1360 !TRI->regsOverlap(MOP.getReg(), RegToRename))
Florian Hahn17554b82019-12-11 09:59:18 +00001361 continue;
1362
1363 if (!canRenameMOP(MOP)) {
1364 LLVM_DEBUG(dbgs()
1365 << " Cannot rename " << MOP << " in " << MI << "\n");
1366 return false;
1367 }
1368 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1369 }
1370 }
1371 return true;
1372 };
1373
1374 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1375 return false;
1376
1377 if (!FoundDef) {
1378 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1379 return false;
1380 }
1381 return true;
1382}
1383
1384// Check if we can find a physical register for renaming. This register must:
1385// * not be defined up to FirstMI (checking DefinedInBB)
1386// * not used between the MI and the defining instruction of the register to
1387// rename (checked using UsedInBetween).
1388// * is available in all used register classes (checked using RequiredClasses).
1389static Optional<MCPhysReg> tryToFindRegisterToRename(
1390 MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1391 LiveRegUnits &UsedInBetween,
1392 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1393 const TargetRegisterInfo *TRI) {
1394 auto &MF = *FirstMI.getParent()->getParent();
Florian Hahnd2692552019-12-21 14:47:08 +01001395 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Florian Hahn17554b82019-12-11 09:59:18 +00001396
1397 // Checks if any sub- or super-register of PR is callee saved.
1398 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1399 return any_of(TRI->sub_and_superregs_inclusive(PR),
1400 [&MF, TRI](MCPhysReg SubOrSuper) {
1401 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1402 });
1403 };
1404
1405 // Check if PR or one of its sub- or super-registers can be used for all
1406 // required register classes.
1407 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1408 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1409 return any_of(TRI->sub_and_superregs_inclusive(PR),
1410 [C, TRI](MCPhysReg SubOrSuper) {
1411 return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1412 });
1413 });
1414 };
1415
1416 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1417 for (const MCPhysReg &PR : *RegClass) {
1418 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
Florian Hahnd2692552019-12-21 14:47:08 +01001419 !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1420 CanBeUsedForAllClasses(PR)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001421 DefinedInBB.addReg(PR);
1422 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1423 << "\n");
1424 return {PR};
1425 }
1426 }
1427 LLVM_DEBUG(dbgs() << "No rename register found from "
1428 << TRI->getRegClassName(RegClass) << "\n");
1429 return None;
1430}
1431
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001432/// Scan the instructions looking for a load/store that can be combined with the
1433/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001434MachineBasicBlock::iterator
1435AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001436 LdStPairFlags &Flags, unsigned Limit,
1437 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001438 MachineBasicBlock::iterator E = I->getParent()->end();
1439 MachineBasicBlock::iterator MBBI = I;
Florian Hahn17554b82019-12-11 09:59:18 +00001440 MachineBasicBlock::iterator MBBIWithRenameReg;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001441 MachineInstr &FirstMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001442 ++MBBI;
1443
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001444 bool MayLoad = FirstMI.mayLoad();
1445 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001446 Register Reg = getLdStRegOp(FirstMI).getReg();
1447 Register BaseReg = getLdStBaseOp(FirstMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001448 int Offset = getLdStOffsetOp(FirstMI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001449 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001450 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001451
Florian Hahn17554b82019-12-11 09:59:18 +00001452 Optional<bool> MaybeCanRename = None;
Florian Hahn8e3f59b2020-01-27 15:11:45 -08001453 if (!EnableRenaming)
1454 MaybeCanRename = {false};
1455
Florian Hahn17554b82019-12-11 09:59:18 +00001456 SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1457 LiveRegUnits UsedInBetween;
1458 UsedInBetween.init(*TRI);
1459
1460 Flags.clearRenameReg();
1461
Jun Bum Lim47aece12018-04-27 18:44:37 +00001462 // Track which register units have been modified and used between the first
1463 // insn (inclusive) and the second insn.
1464 ModifiedRegUnits.clear();
1465 UsedRegUnits.clear();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001466
1467 // Remember any instructions that read/write memory between FirstMI and MI.
1468 SmallVector<MachineInstr *, 4> MemInsns;
1469
Tim Northover3b0846e2014-05-24 12:50:23 +00001470 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001471 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001472
Florian Hahn17554b82019-12-11 09:59:18 +00001473 UsedInBetween.accumulate(MI);
1474
Geoff Berry4ff2e362016-07-21 15:20:25 +00001475 // Don't count transient instructions towards the search limit since there
1476 // may be different numbers of them if e.g. debug information is present.
1477 if (!MI.isTransient())
1478 ++Count;
Tim Northover3b0846e2014-05-24 12:50:23 +00001479
Chad Rosier18896c02016-02-04 16:01:40 +00001480 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001481 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001482 getLdStOffsetOp(MI).isImm()) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001483 assert(MI.mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001484 // If we've found another instruction with the same opcode, check to see
1485 // if the base and offset are compatible with our starting instruction.
1486 // These instructions all have scaled immediate operands, so we just
1487 // check for +1/-1. Make sure to check the new instruction offset is
1488 // actually an immediate and not a symbolic reference destined for
1489 // a relocation.
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001490 Register MIBaseReg = getLdStBaseOp(MI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001491 int MIOffset = getLdStOffsetOp(MI).getImm();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001492 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001493 if (IsUnscaled != MIIsUnscaled) {
1494 // We're trying to pair instructions that differ in how they are scaled.
1495 // If FirstMI is scaled then scale the offset of MI accordingly.
1496 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +00001497 int MemSize = TII->getMemScale(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001498 if (MIIsUnscaled) {
1499 // If the unscaled offset isn't a multiple of the MemSize, we can't
1500 // pair the operations together: bail and keep looking.
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001501 if (MIOffset % MemSize) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001502 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1503 UsedRegUnits, TRI);
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001504 MemInsns.push_back(&MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001505 continue;
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001506 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001507 MIOffset /= MemSize;
1508 } else {
1509 MIOffset *= MemSize;
1510 }
1511 }
1512
Tim Northover3b0846e2014-05-24 12:50:23 +00001513 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1514 (Offset + OffsetStride == MIOffset))) {
1515 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001516 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001517 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001518 // instruction can't express the offset of the scaled narrow input,
1519 // bail and keep looking. For promotable zero stores, allow only when
1520 // the stored value is the same (i.e., WZR).
1521 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1522 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
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 }
1528 } else {
Chad Rosierd1f6c842016-06-10 20:49:18 +00001529 // Pairwise instructions have a 7-bit signed offset field. Single
1530 // insns have a 12-bit unsigned offset field. If the resultant
1531 // immediate offset of merging these instructions is out of range for
1532 // a pairwise instruction, bail and keep looking.
Jun Bum Limcf974432016-03-31 14:47:24 +00001533 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001534 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1535 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001536 MemInsns.push_back(&MI);
Jun Bum Limcf974432016-03-31 14:47:24 +00001537 continue;
1538 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001539 // If the alignment requirements of the paired (scaled) instruction
1540 // can't express the offset of the unscaled input, bail and keep
1541 // looking.
1542 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001543 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1544 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001545 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001546 continue;
1547 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001548 }
1549 // If the destination register of the loads is the same register, bail
1550 // and keep looking. A load-pair instruction with both destination
1551 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001552 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001553 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1554 TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001555 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001556 continue;
1557 }
1558
1559 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001560 // the two instructions and none of the instructions between the second
1561 // and first alias with the second, we can combine the second into the
1562 // first.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001563 if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1564 !(MI.mayLoad() &&
1565 !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001566 !mayAlias(MI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001567
Chad Rosier96a18a92015-07-21 17:42:04 +00001568 Flags.setMergeForward(false);
Florian Hahn17554b82019-12-11 09:59:18 +00001569 Flags.clearRenameReg();
Tim Northover3b0846e2014-05-24 12:50:23 +00001570 return MBBI;
1571 }
1572
1573 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001574 // between the two instructions and none of the instructions between the
1575 // first and the second alias with the first, we can combine the first
1576 // into the second.
Florian Hahn17554b82019-12-11 09:59:18 +00001577 if (!(MayLoad &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001578 !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001579 !mayAlias(FirstMI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001580
1581 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1582 Flags.setMergeForward(true);
1583 Flags.clearRenameReg();
1584 return MBBI;
1585 }
1586
1587 if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1588 if (!MaybeCanRename)
1589 MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1590 RequiredClasses, TRI)};
1591
1592 if (*MaybeCanRename) {
1593 Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1594 FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1595 TRI);
1596 if (MaybeRenameReg) {
1597 Flags.setRenameReg(*MaybeRenameReg);
1598 Flags.setMergeForward(true);
1599 MBBIWithRenameReg = MBBI;
1600 }
1601 }
1602 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001603 }
1604 // Unable to combine these instructions due to interference in between.
1605 // Keep looking.
1606 }
1607 }
1608
Florian Hahn17554b82019-12-11 09:59:18 +00001609 if (Flags.getRenameReg())
1610 return MBBIWithRenameReg;
1611
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001612 // If the instruction wasn't a matching load or store. Stop searching if we
1613 // encounter a call instruction that might modify memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001614 if (MI.isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001615 return E;
1616
Jun Bum Lim47aece12018-04-27 18:44:37 +00001617 // Update modified / uses register units.
1618 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001619
1620 // Otherwise, if the base register is modified, we have no match, so
1621 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001622 if (!ModifiedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001623 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001624
1625 // Update list of instructions that read/write memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001626 if (MI.mayLoadOrStore())
1627 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001628 }
1629 return E;
1630}
1631
1632MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001633AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1634 MachineBasicBlock::iterator Update,
1635 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001636 assert((Update->getOpcode() == AArch64::ADDXri ||
1637 Update->getOpcode() == AArch64::SUBXri) &&
1638 "Unexpected base register update instruction to merge!");
1639 MachineBasicBlock::iterator NextI = I;
1640 // Return the instruction following the merged instruction, which is
1641 // the instruction following our unmerged load. Unless that's the add/sub
1642 // instruction we're merging, in which case it's the one after that.
1643 if (++NextI == Update)
1644 ++NextI;
1645
1646 int Value = Update->getOperand(2).getImm();
1647 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001648 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001649 if (Update->getOpcode() == AArch64::SUBXri)
1650 Value = -Value;
1651
Chad Rosier2dfd3542015-09-23 13:51:44 +00001652 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1653 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001654 MachineInstrBuilder MIB;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001655 int Scale, MinOffset, MaxOffset;
1656 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001657 if (!isPairedLdSt(*I)) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001658 // Non-paired instruction.
1659 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001660 .add(getLdStRegOp(*Update))
1661 .add(getLdStRegOp(*I))
1662 .add(getLdStBaseOp(*I))
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001663 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001664 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001665 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001666 } else {
1667 // Paired instruction.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001668 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001669 .add(getLdStRegOp(*Update))
1670 .add(getLdStRegOp(*I, 0))
1671 .add(getLdStRegOp(*I, 1))
1672 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001673 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001674 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001675 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001676 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001677 (void)MIB;
1678
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001679 if (IsPreIdx) {
1680 ++NumPreFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001681 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001682 } else {
1683 ++NumPostFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001684 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001685 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001686 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
1687 LLVM_DEBUG(I->print(dbgs()));
1688 LLVM_DEBUG(dbgs() << " ");
1689 LLVM_DEBUG(Update->print(dbgs()));
1690 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1691 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1692 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001693
1694 // Erase the old instructions for the block.
1695 I->eraseFromParent();
1696 Update->eraseFromParent();
1697
1698 return NextI;
1699}
1700
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001701bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1702 MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001703 unsigned BaseReg, int Offset) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001704 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001705 default:
1706 break;
1707 case AArch64::SUBXri:
Tim Northover3b0846e2014-05-24 12:50:23 +00001708 case AArch64::ADDXri:
1709 // Make sure it's a vanilla immediate operand, not a relocation or
1710 // anything else we can't handle.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001711 if (!MI.getOperand(2).isImm())
Tim Northover3b0846e2014-05-24 12:50:23 +00001712 break;
1713 // Watch out for 1 << 12 shifted value.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001714 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
Tim Northover3b0846e2014-05-24 12:50:23 +00001715 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001716
1717 // The update instruction source and destination register must be the
1718 // same as the load/store base register.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001719 if (MI.getOperand(0).getReg() != BaseReg ||
1720 MI.getOperand(1).getReg() != BaseReg)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001721 break;
1722
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001723 int UpdateOffset = MI.getOperand(2).getImm();
Eli Friedman8585e9d2016-08-12 20:28:02 +00001724 if (MI.getOpcode() == AArch64::SUBXri)
1725 UpdateOffset = -UpdateOffset;
1726
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001727 // The immediate must be a multiple of the scaling factor of the pre/post
1728 // indexed instruction.
1729 int Scale, MinOffset, MaxOffset;
1730 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1731 if (UpdateOffset % Scale != 0)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001732 break;
1733
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001734 // Scaled offset must fit in the instruction immediate.
1735 int ScaledOffset = UpdateOffset / Scale;
1736 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1737 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001738
1739 // If we have a non-zero Offset, we check that it matches the amount
1740 // we're adding to the register.
Eli Friedman8585e9d2016-08-12 20:28:02 +00001741 if (!Offset || Offset == UpdateOffset)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001742 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001743 break;
1744 }
1745 return false;
1746}
1747
1748MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001749 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001750 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001751 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001752 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001753
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001754 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Jay Foad97ca7c22019-12-11 10:29:23 +00001755 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001756
Chad Rosierb7c5b912015-10-01 13:43:05 +00001757 // Scan forward looking for post-index opportunities. Updating instructions
1758 // can't be formed if the memory instruction doesn't have the offset we're
1759 // looking for.
1760 if (MIUnscaledOffset != UnscaledOffset)
1761 return E;
1762
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001763 // If the base register overlaps a source/destination register, we can't
1764 // merge the update. This does not apply to tag store instructions which
1765 // ignore the address part of the source register.
1766 // This does not apply to STGPi as well, which does not have unpredictable
1767 // behavior in this case unlike normal stores, and always performs writeback
1768 // after reading the source register value.
1769 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1770 bool IsPairedInsn = isPairedLdSt(MemMI);
1771 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1772 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1773 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1774 return E;
1775 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001776 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001777
Jun Bum Lim47aece12018-04-27 18:44:37 +00001778 // Track which register units have been modified and used between the first
1779 // insn (inclusive) and the second insn.
1780 ModifiedRegUnits.clear();
1781 UsedRegUnits.clear();
Tim Northover3b0846e2014-05-24 12:50:23 +00001782 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001783 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001784 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001785
Geoff Berry4ff2e362016-07-21 15:20:25 +00001786 // Don't count transient instructions towards the search limit since there
1787 // may be different numbers of them if e.g. debug information is present.
1788 if (!MI.isTransient())
1789 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001790
Tim Northover3b0846e2014-05-24 12:50:23 +00001791 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001792 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001793 return MBBI;
1794
1795 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001796 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001797
1798 // Otherwise, if the base register is used or modified, we have no match, so
1799 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001800 if (!ModifiedRegUnits.available(BaseReg) ||
1801 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001802 return E;
1803 }
1804 return E;
1805}
1806
1807MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001808 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001809 MachineBasicBlock::iterator B = I->getParent()->begin();
1810 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001811 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001812 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001813
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001814 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001815 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001816
1817 // If the load/store is the first instruction in the block, there's obviously
1818 // not any matching update. Ditto if the memory offset isn't zero.
1819 if (MBBI == B || Offset != 0)
1820 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001821 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001822 // merge the update.
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001823 if (!isTagStore(MemMI)) {
1824 bool IsPairedInsn = isPairedLdSt(MemMI);
1825 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1826 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1827 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1828 return E;
1829 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001830 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001831
Jun Bum Lim47aece12018-04-27 18:44:37 +00001832 // Track which register units have been modified and used between the first
1833 // insn (inclusive) and the second insn.
1834 ModifiedRegUnits.clear();
1835 UsedRegUnits.clear();
Geoff Berry173b14d2016-02-09 20:47:21 +00001836 unsigned Count = 0;
1837 do {
1838 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001839 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001840
Geoff Berry4ff2e362016-07-21 15:20:25 +00001841 // Don't count transient instructions towards the search limit since there
1842 // may be different numbers of them if e.g. debug information is present.
1843 if (!MI.isTransient())
Geoff Berry173b14d2016-02-09 20:47:21 +00001844 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001845
Tim Northover3b0846e2014-05-24 12:50:23 +00001846 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001847 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001848 return MBBI;
1849
1850 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001851 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001852
1853 // Otherwise, if the base register is used or modified, we have no match, so
1854 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001855 if (!ModifiedRegUnits.available(BaseReg) ||
1856 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001857 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001858 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001859 return E;
1860}
1861
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001862bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1863 MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001864 MachineInstr &MI = *MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001865 // If this is a volatile load, don't mess with it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001866 if (MI.hasOrderedMemoryRef())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001867 return false;
1868
1869 // Make sure this is a reg+imm.
1870 // FIXME: It is possible to extend it to handle reg+reg cases.
1871 if (!getLdStOffsetOp(MI).isImm())
1872 return false;
1873
Chad Rosier35706ad2016-02-04 21:26:02 +00001874 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001875 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001876 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001877 ++NumLoadsFromStoresPromoted;
1878 // Promote the load. Keeping the iterator straight is a
1879 // pain, so we let the merge routine tell us what the next instruction
1880 // is after it's done mucking about.
1881 MBBI = promoteLoadFromStore(MBBI, StoreI);
1882 return true;
1883 }
1884 return false;
1885}
1886
Chad Rosierd6daac42016-11-07 15:27:22 +00001887// Merge adjacent zero stores into a wider store.
1888bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
Chad Rosier24c46ad2016-02-09 18:10:20 +00001889 MachineBasicBlock::iterator &MBBI) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001890 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001891 MachineInstr &MI = *MBBI;
1892 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001893
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001894 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001895 return false;
1896
1897 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001898 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001899 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001900 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001901 if (MergeMI != E) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001902 ++NumZeroStoresPromoted;
1903
Chad Rosier24c46ad2016-02-09 18:10:20 +00001904 // Keeping the iterator straight is a pain, so we let the merge routine tell
1905 // us what the next instruction is after it's done mucking about.
Chad Rosierd6daac42016-11-07 15:27:22 +00001906 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001907 return true;
1908 }
1909 return false;
1910}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001911
Chad Rosier24c46ad2016-02-09 18:10:20 +00001912// Find loads and stores that can be merged into a single load or store pair
1913// instruction.
1914bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001915 MachineInstr &MI = *MBBI;
1916 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001917
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001918 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001919 return false;
1920
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001921 // Early exit if the offset is not possible to match. (6 bits of positive
1922 // range, plus allow an extra one in case we find a later insn that matches
1923 // with Offset-1)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001924 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001925 int Offset = getLdStOffsetOp(MI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001926 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
Nirav Dave0f9d1112017-01-04 21:21:46 +00001927 // Allow one more for offset.
1928 if (Offset > 0)
1929 Offset -= OffsetStride;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001930 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1931 return false;
1932
Chad Rosier24c46ad2016-02-09 18:10:20 +00001933 // Look ahead up to LdStLimit instructions for a pairable instruction.
1934 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001935 MachineBasicBlock::iterator Paired =
1936 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001937 if (Paired != E) {
1938 ++NumPairCreated;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001939 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001940 ++NumUnscaledPairCreated;
1941 // Keeping the iterator straight is a pain, so we let the merge routine tell
1942 // us what the next instruction is after it's done mucking about.
Florian Hahn17554b82019-12-11 09:59:18 +00001943 auto Prev = std::prev(MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001944 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Florian Hahn17554b82019-12-11 09:59:18 +00001945 // Collect liveness info for instructions between Prev and the new position
1946 // MBBI.
1947 for (auto I = std::next(Prev); I != MBBI; I++)
1948 updateDefinedRegisters(*I, DefinedInBB, TRI);
1949
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001950 return true;
1951 }
1952 return false;
1953}
1954
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001955bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1956 (MachineBasicBlock::iterator &MBBI) {
1957 MachineInstr &MI = *MBBI;
1958 MachineBasicBlock::iterator E = MI.getParent()->end();
1959 MachineBasicBlock::iterator Update;
1960
1961 // Look forward to try to form a post-index instruction. For example,
1962 // ldr x0, [x20]
1963 // add x20, x20, #32
1964 // merged into:
1965 // ldr x0, [x20], #32
1966 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1967 if (Update != E) {
1968 // Merge the update into the ld/st.
1969 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1970 return true;
1971 }
1972
1973 // Don't know how to handle unscaled pre/post-index versions below, so bail.
1974 if (TII->isUnscaledLdSt(MI.getOpcode()))
1975 return false;
1976
1977 // Look back to try to find a pre-index instruction. For example,
1978 // add x0, x0, #8
1979 // ldr x1, [x0]
1980 // merged into:
1981 // ldr x1, [x0, #8]!
1982 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1983 if (Update != E) {
1984 // Merge the update into the ld/st.
1985 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1986 return true;
1987 }
1988
1989 // The immediate in the load/store is scaled by the size of the memory
1990 // operation. The immediate in the add we're looking for,
1991 // however, is not, so adjust here.
Jay Foad97ca7c22019-12-11 10:29:23 +00001992 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001993
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001994 // Look forward to try to find a pre-index instruction. For example,
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001995 // ldr x1, [x0, #64]
1996 // add x0, x0, #64
1997 // merged into:
1998 // ldr x1, [x0, #64]!
1999 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2000 if (Update != E) {
2001 // Merge the update into the ld/st.
2002 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2003 return true;
2004 }
2005
2006 return false;
2007}
2008
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00002009bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
Chad Rosierd6daac42016-11-07 15:27:22 +00002010 bool EnableNarrowZeroStOpt) {
Florian Hahn17554b82019-12-11 09:59:18 +00002011
Tim Northover3b0846e2014-05-24 12:50:23 +00002012 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002013 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002014 // 1) Find loads that directly read from stores and promote them by
2015 // replacing with mov instructions. If the store is wider than the load,
2016 // the load will be replaced with a bitfield extract.
2017 // e.g.,
2018 // str w1, [x0, #4]
2019 // ldrh w2, [x0, #6]
2020 // ; becomes
2021 // str w1, [x0, #4]
NAKAMURA Takumife1202c2016-06-20 00:37:41 +00002022 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00002023 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002024 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002025 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2026 Modified = true;
2027 else
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002028 ++MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002029 }
Chad Rosierd6daac42016-11-07 15:27:22 +00002030 // 2) Merge adjacent zero stores into a wider store.
Jun Bum Lim1de2d442016-02-05 20:02:03 +00002031 // e.g.,
2032 // strh wzr, [x0]
2033 // strh wzr, [x0, #2]
2034 // ; becomes
2035 // str wzr, [x0]
Chad Rosierd6daac42016-11-07 15:27:22 +00002036 // e.g.,
2037 // str wzr, [x0]
2038 // str wzr, [x0, #4]
2039 // ; becomes
2040 // str xzr, [x0]
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002041 if (EnableNarrowZeroStOpt)
2042 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2043 MBBI != E;) {
2044 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002045 Modified = true;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002046 else
Jun Bum Lim33be4992016-05-06 15:08:57 +00002047 ++MBBI;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002048 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002049 // 3) Find loads and stores that can be merged into a single load or store
2050 // pair instruction.
2051 // e.g.,
2052 // ldr x0, [x2]
2053 // ldr x1, [x2, #8]
2054 // ; becomes
2055 // ldp x0, x1, [x2]
Florian Hahn17554b82019-12-11 09:59:18 +00002056
2057 if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2058 DefinedInBB.clear();
2059 DefinedInBB.addLiveIns(MBB);
2060 }
2061
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002062 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00002063 MBBI != E;) {
Florian Hahn17554b82019-12-11 09:59:18 +00002064 // Track currently live registers up to this point, to help with
2065 // searching for a rename register on demand.
2066 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
Geoff Berry22dfbc52016-08-12 15:26:00 +00002067 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2068 Modified = true;
2069 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002070 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002071 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002072 // 4) Find base register updates that can be merged into the load or store
2073 // as a base-reg writeback.
2074 // e.g.,
2075 // ldr x0, [x2]
2076 // add x2, x2, #4
2077 // ; becomes
2078 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00002079 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2080 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002081 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2082 Modified = true;
2083 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002084 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002085 }
2086
2087 return Modified;
2088}
2089
2090bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002091 if (skipFunction(Fn.getFunction()))
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00002092 return false;
2093
Oliver Stannardd414c992015-11-10 11:04:18 +00002094 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2095 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2096 TRI = Subtarget->getRegisterInfo();
Chad Rosiera69dcb62017-03-17 14:19:55 +00002097 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tim Northover3b0846e2014-05-24 12:50:23 +00002098
Jun Bum Lim47aece12018-04-27 18:44:37 +00002099 // Resize the modified and used register unit trackers. We do this once
2100 // per function and then clear the register units each time we optimize a load
2101 // or store.
2102 ModifiedRegUnits.init(*TRI);
2103 UsedRegUnits.init(*TRI);
Florian Hahn17554b82019-12-11 09:59:18 +00002104 DefinedInBB.init(*TRI);
Chad Rosierbba881e2016-02-02 15:02:30 +00002105
Tim Northover3b0846e2014-05-24 12:50:23 +00002106 bool Modified = false;
Chad Rosier10c7aaa2016-11-11 14:10:12 +00002107 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
Florian Hahn17554b82019-12-11 09:59:18 +00002108 for (auto &MBB : Fn) {
2109 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2110 Modified |= M;
2111 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002112
2113 return Modified;
2114}
2115
Chad Rosier8ade0342016-11-11 19:52:45 +00002116// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2117// stores near one another? Note: The pre-RA instruction scheduler already has
2118// hooks to try and schedule pairable loads/stores together to improve pairing
2119// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
Tim Northover3b0846e2014-05-24 12:50:23 +00002120
Chad Rosier3f8b09d2016-02-09 19:42:19 +00002121// FIXME: When pairing store instructions it's very possible for this pass to
2122// hoist a store with a KILL marker above another use (without a KILL marker).
2123// The resulting IR is invalid, but nothing uses the KILL markers after this
2124// pass, so it's never caused a problem in practice.
2125
Chad Rosier43f5c842015-08-05 12:40:13 +00002126/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2127/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00002128FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2129 return new AArch64LoadStoreOpt();
2130}