LLVM 20.0.0git
AArch64LoadStoreOptimizer.cpp
Go to the documentation of this file.
1//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
2//
3// 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
6//
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// The pass runs after the PrologEpilogInserter where we emit the CFI
13// instructions. In order to preserve the correctness of the unwind informaiton,
14// the pass should not change the order of any two instructions, one of which
15// has the FrameSetup/FrameDestroy flag or, alternatively, apply an add-hoc fix
16// to unwind information.
17//
18//===----------------------------------------------------------------------===//
19
20#include "AArch64InstrInfo.h"
22#include "AArch64Subtarget.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/DebugLoc.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCDwarf.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
47#include <cassert>
48#include <cstdint>
49#include <functional>
50#include <iterator>
51#include <limits>
52#include <optional>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "aarch64-ldst-opt"
57
58STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
59STATISTIC(NumPostFolded, "Number of post-index updates folded");
60STATISTIC(NumPreFolded, "Number of pre-index updates folded");
61STATISTIC(NumUnscaledPairCreated,
62 "Number of load/store from unscaled generated");
63STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
64STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
65STATISTIC(NumFailedAlignmentCheck, "Number of load/store pair transformation "
66 "not passed the alignment check");
67STATISTIC(NumConstOffsetFolded,
68 "Number of const offset of index address folded");
69
70DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
71 "Controls which pairs are considered for renaming");
72
73// The LdStLimit limits how far we search for load/store pairs.
74static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
75 cl::init(20), cl::Hidden);
76
77// The UpdateLimit limits how far we search for update instructions when we form
78// pre-/post-index instructions.
79static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
81
82// The LdStConstLimit limits how far we search for const offset instructions
83// when we form index address load/store instructions.
84static cl::opt<unsigned> LdStConstLimit("aarch64-load-store-const-scan-limit",
85 cl::init(10), cl::Hidden);
86
87// Enable register renaming to find additional store pairing opportunities.
88static cl::opt<bool> EnableRenaming("aarch64-load-store-renaming",
89 cl::init(true), cl::Hidden);
90
91#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
92
93namespace {
94
95using LdStPairFlags = struct LdStPairFlags {
96 // If a matching instruction is found, MergeForward is set to true if the
97 // merge is to remove the first instruction and replace the second with
98 // a pair-wise insn, and false if the reverse is true.
99 bool MergeForward = false;
100
101 // SExtIdx gives the index of the result of the load pair that must be
102 // extended. The value of SExtIdx assumes that the paired load produces the
103 // value in this order: (I, returned iterator), i.e., -1 means no value has
104 // to be extended, 0 means I, and 1 means the returned iterator.
105 int SExtIdx = -1;
106
107 // If not none, RenameReg can be used to rename the result register of the
108 // first store in a pair. Currently this only works when merging stores
109 // forward.
110 std::optional<MCPhysReg> RenameReg;
111
112 LdStPairFlags() = default;
113
114 void setMergeForward(bool V = true) { MergeForward = V; }
115 bool getMergeForward() const { return MergeForward; }
116
117 void setSExtIdx(int V) { SExtIdx = V; }
118 int getSExtIdx() const { return SExtIdx; }
119
120 void setRenameReg(MCPhysReg R) { RenameReg = R; }
121 void clearRenameReg() { RenameReg = std::nullopt; }
122 std::optional<MCPhysReg> getRenameReg() const { return RenameReg; }
123};
124
125struct AArch64LoadStoreOpt : public MachineFunctionPass {
126 static char ID;
127
128 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
130 }
131
132 AliasAnalysis *AA;
133 const AArch64InstrInfo *TII;
134 const TargetRegisterInfo *TRI;
135 const AArch64Subtarget *Subtarget;
136
137 // Track which register units have been modified and used.
138 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
139 LiveRegUnits DefinedInBB;
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 }
145
146 // Scan the instructions looking for a load/store that can be combined
147 // with the current instruction into a load/store pair.
148 // Return the matching instruction if one is found, else MBB->end().
150 LdStPairFlags &Flags,
151 unsigned Limit,
152 bool FindNarrowMerge);
153
154 // Scan the instructions looking for a store that writes to the address from
155 // which the current load instruction reads. Return true if one is found.
156 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
158
159 // Merge the two instructions indicated into a wider narrow store instruction.
161 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
163 const LdStPairFlags &Flags);
164
165 // Merge the two instructions indicated into a single pair-wise instruction.
167 mergePairedInsns(MachineBasicBlock::iterator I,
169 const LdStPairFlags &Flags);
170
171 // Promote the load that reads directly from the address stored to.
173 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
175
176 // Scan the instruction list to find a base register update that can
177 // be combined with the current instruction (a load or store) using
178 // pre or post indexed addressing with writeback. Scan forwards.
180 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
181 int UnscaledOffset, unsigned Limit);
182
183 // Scan the instruction list to find a register assigned with a const
184 // value that can be combined with the current instruction (a load or store)
185 // using base addressing with writeback. Scan backwards.
187 findMatchingConstOffsetBackward(MachineBasicBlock::iterator I, unsigned Limit,
188 unsigned &Offset);
189
190 // Scan the instruction list to find a base register update that can
191 // be combined with the current instruction (a load or store) using
192 // pre or post indexed addressing with writeback. Scan backwards.
194 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
195
196 // Find an instruction that updates the base register of the ld/st
197 // instruction.
198 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
199 unsigned BaseReg, int Offset);
200
201 bool isMatchingMovConstInsn(MachineInstr &MemMI, MachineInstr &MI,
202 unsigned IndexReg, unsigned &Offset);
203
204 // Merge a pre- or post-index base register update into a ld/st instruction.
206 mergeUpdateInsn(MachineBasicBlock::iterator I,
207 MachineBasicBlock::iterator Update, bool IsPreIdx);
208
210 mergeConstOffsetInsn(MachineBasicBlock::iterator I,
211 MachineBasicBlock::iterator Update, unsigned Offset,
212 int Scale);
213
214 // Find and merge zero store instructions.
215 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
216
217 // Find and pair ldr/str instructions.
218 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
219
220 // Find and promote load instructions which read directly from store.
221 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
222
223 // Find and merge a base register updates before or after a ld/st instruction.
224 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
225
226 // Find and merge an index ldr/st instruction into a base ld/st instruction.
227 bool tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI, int Scale);
228
229 // Finds and collapses loads of symmetric constant value.
230 bool tryFoldSymmetryConstantLoad(MachineBasicBlock::iterator &I,
231 unsigned Limit);
233 doFoldSymmetryConstantLoad(MachineInstr &MI,
235 int UpperLoadIdx, int Accumulated);
236
237 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
238
239 bool runOnMachineFunction(MachineFunction &Fn) override;
240
243 MachineFunctionProperties::Property::NoVRegs);
244 }
245
246 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
247};
248
249char AArch64LoadStoreOpt::ID = 0;
250
251} // end anonymous namespace
252
253INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
254 AARCH64_LOAD_STORE_OPT_NAME, false, false)
255
256static bool isNarrowStore(unsigned Opc) {
257 switch (Opc) {
258 default:
259 return false;
260 case AArch64::STRBBui:
261 case AArch64::STURBBi:
262 case AArch64::STRHHui:
263 case AArch64::STURHHi:
264 return true;
265 }
266}
267
268// These instruction set memory tag and either keep memory contents unchanged or
269// set it to zero, ignoring the address part of the source register.
270static bool isTagStore(const MachineInstr &MI) {
271 switch (MI.getOpcode()) {
272 default:
273 return false;
274 case AArch64::STGi:
275 case AArch64::STZGi:
276 case AArch64::ST2Gi:
277 case AArch64::STZ2Gi:
278 return true;
279 }
280}
281
282static unsigned getMatchingNonSExtOpcode(unsigned Opc,
283 bool *IsValidLdStrOpc = nullptr) {
284 if (IsValidLdStrOpc)
285 *IsValidLdStrOpc = true;
286 switch (Opc) {
287 default:
288 if (IsValidLdStrOpc)
289 *IsValidLdStrOpc = false;
290 return std::numeric_limits<unsigned>::max();
291 case AArch64::STRDui:
292 case AArch64::STURDi:
293 case AArch64::STRDpre:
294 case AArch64::STRQui:
295 case AArch64::STURQi:
296 case AArch64::STRQpre:
297 case AArch64::STRBBui:
298 case AArch64::STURBBi:
299 case AArch64::STRHHui:
300 case AArch64::STURHHi:
301 case AArch64::STRWui:
302 case AArch64::STRWpre:
303 case AArch64::STURWi:
304 case AArch64::STRXui:
305 case AArch64::STRXpre:
306 case AArch64::STURXi:
307 case AArch64::LDRDui:
308 case AArch64::LDURDi:
309 case AArch64::LDRDpre:
310 case AArch64::LDRQui:
311 case AArch64::LDURQi:
312 case AArch64::LDRQpre:
313 case AArch64::LDRWui:
314 case AArch64::LDURWi:
315 case AArch64::LDRWpre:
316 case AArch64::LDRXui:
317 case AArch64::LDURXi:
318 case AArch64::LDRXpre:
319 case AArch64::STRSui:
320 case AArch64::STURSi:
321 case AArch64::STRSpre:
322 case AArch64::LDRSui:
323 case AArch64::LDURSi:
324 case AArch64::LDRSpre:
325 return Opc;
326 case AArch64::LDRSWui:
327 return AArch64::LDRWui;
328 case AArch64::LDURSWi:
329 return AArch64::LDURWi;
330 case AArch64::LDRSWpre:
331 return AArch64::LDRWpre;
332 }
333}
334
335static unsigned getMatchingWideOpcode(unsigned Opc) {
336 switch (Opc) {
337 default:
338 llvm_unreachable("Opcode has no wide equivalent!");
339 case AArch64::STRBBui:
340 return AArch64::STRHHui;
341 case AArch64::STRHHui:
342 return AArch64::STRWui;
343 case AArch64::STURBBi:
344 return AArch64::STURHHi;
345 case AArch64::STURHHi:
346 return AArch64::STURWi;
347 case AArch64::STURWi:
348 return AArch64::STURXi;
349 case AArch64::STRWui:
350 return AArch64::STRXui;
351 }
352}
353
354static unsigned getMatchingPairOpcode(unsigned Opc) {
355 switch (Opc) {
356 default:
357 llvm_unreachable("Opcode has no pairwise equivalent!");
358 case AArch64::STRSui:
359 case AArch64::STURSi:
360 return AArch64::STPSi;
361 case AArch64::STRSpre:
362 return AArch64::STPSpre;
363 case AArch64::STRDui:
364 case AArch64::STURDi:
365 return AArch64::STPDi;
366 case AArch64::STRDpre:
367 return AArch64::STPDpre;
368 case AArch64::STRQui:
369 case AArch64::STURQi:
370 return AArch64::STPQi;
371 case AArch64::STRQpre:
372 return AArch64::STPQpre;
373 case AArch64::STRWui:
374 case AArch64::STURWi:
375 return AArch64::STPWi;
376 case AArch64::STRWpre:
377 return AArch64::STPWpre;
378 case AArch64::STRXui:
379 case AArch64::STURXi:
380 return AArch64::STPXi;
381 case AArch64::STRXpre:
382 return AArch64::STPXpre;
383 case AArch64::LDRSui:
384 case AArch64::LDURSi:
385 return AArch64::LDPSi;
386 case AArch64::LDRSpre:
387 return AArch64::LDPSpre;
388 case AArch64::LDRDui:
389 case AArch64::LDURDi:
390 return AArch64::LDPDi;
391 case AArch64::LDRDpre:
392 return AArch64::LDPDpre;
393 case AArch64::LDRQui:
394 case AArch64::LDURQi:
395 return AArch64::LDPQi;
396 case AArch64::LDRQpre:
397 return AArch64::LDPQpre;
398 case AArch64::LDRWui:
399 case AArch64::LDURWi:
400 return AArch64::LDPWi;
401 case AArch64::LDRWpre:
402 return AArch64::LDPWpre;
403 case AArch64::LDRXui:
404 case AArch64::LDURXi:
405 return AArch64::LDPXi;
406 case AArch64::LDRXpre:
407 return AArch64::LDPXpre;
408 case AArch64::LDRSWui:
409 case AArch64::LDURSWi:
410 return AArch64::LDPSWi;
411 case AArch64::LDRSWpre:
412 return AArch64::LDPSWpre;
413 }
414}
415
418 unsigned LdOpc = LoadInst.getOpcode();
419 unsigned StOpc = StoreInst.getOpcode();
420 switch (LdOpc) {
421 default:
422 llvm_unreachable("Unsupported load instruction!");
423 case AArch64::LDRBBui:
424 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
425 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
426 case AArch64::LDURBBi:
427 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
428 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
429 case AArch64::LDRHHui:
430 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
431 StOpc == AArch64::STRXui;
432 case AArch64::LDURHHi:
433 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
434 StOpc == AArch64::STURXi;
435 case AArch64::LDRWui:
436 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
437 case AArch64::LDURWi:
438 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
439 case AArch64::LDRXui:
440 return StOpc == AArch64::STRXui;
441 case AArch64::LDURXi:
442 return StOpc == AArch64::STURXi;
443 }
444}
445
446static unsigned getPreIndexedOpcode(unsigned Opc) {
447 // FIXME: We don't currently support creating pre-indexed loads/stores when
448 // the load or store is the unscaled version. If we decide to perform such an
449 // optimization in the future the cases for the unscaled loads/stores will
450 // need to be added here.
451 switch (Opc) {
452 default:
453 llvm_unreachable("Opcode has no pre-indexed equivalent!");
454 case AArch64::STRSui:
455 return AArch64::STRSpre;
456 case AArch64::STRDui:
457 return AArch64::STRDpre;
458 case AArch64::STRQui:
459 return AArch64::STRQpre;
460 case AArch64::STRBBui:
461 return AArch64::STRBBpre;
462 case AArch64::STRHHui:
463 return AArch64::STRHHpre;
464 case AArch64::STRWui:
465 return AArch64::STRWpre;
466 case AArch64::STRXui:
467 return AArch64::STRXpre;
468 case AArch64::LDRSui:
469 return AArch64::LDRSpre;
470 case AArch64::LDRDui:
471 return AArch64::LDRDpre;
472 case AArch64::LDRQui:
473 return AArch64::LDRQpre;
474 case AArch64::LDRBBui:
475 return AArch64::LDRBBpre;
476 case AArch64::LDRHHui:
477 return AArch64::LDRHHpre;
478 case AArch64::LDRWui:
479 return AArch64::LDRWpre;
480 case AArch64::LDRXui:
481 return AArch64::LDRXpre;
482 case AArch64::LDRSWui:
483 return AArch64::LDRSWpre;
484 case AArch64::LDPSi:
485 return AArch64::LDPSpre;
486 case AArch64::LDPSWi:
487 return AArch64::LDPSWpre;
488 case AArch64::LDPDi:
489 return AArch64::LDPDpre;
490 case AArch64::LDPQi:
491 return AArch64::LDPQpre;
492 case AArch64::LDPWi:
493 return AArch64::LDPWpre;
494 case AArch64::LDPXi:
495 return AArch64::LDPXpre;
496 case AArch64::STPSi:
497 return AArch64::STPSpre;
498 case AArch64::STPDi:
499 return AArch64::STPDpre;
500 case AArch64::STPQi:
501 return AArch64::STPQpre;
502 case AArch64::STPWi:
503 return AArch64::STPWpre;
504 case AArch64::STPXi:
505 return AArch64::STPXpre;
506 case AArch64::STGi:
507 return AArch64::STGPreIndex;
508 case AArch64::STZGi:
509 return AArch64::STZGPreIndex;
510 case AArch64::ST2Gi:
511 return AArch64::ST2GPreIndex;
512 case AArch64::STZ2Gi:
513 return AArch64::STZ2GPreIndex;
514 case AArch64::STGPi:
515 return AArch64::STGPpre;
516 }
517}
518
519static unsigned getBaseAddressOpcode(unsigned Opc) {
520 // TODO: Add more index address loads/stores.
521 switch (Opc) {
522 default:
523 llvm_unreachable("Opcode has no base address equivalent!");
524 case AArch64::LDRBBroX:
525 return AArch64::LDRBBui;
526 }
527}
528
529static unsigned getPostIndexedOpcode(unsigned Opc) {
530 switch (Opc) {
531 default:
532 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
533 case AArch64::STRSui:
534 case AArch64::STURSi:
535 return AArch64::STRSpost;
536 case AArch64::STRDui:
537 case AArch64::STURDi:
538 return AArch64::STRDpost;
539 case AArch64::STRQui:
540 case AArch64::STURQi:
541 return AArch64::STRQpost;
542 case AArch64::STRBBui:
543 return AArch64::STRBBpost;
544 case AArch64::STRHHui:
545 return AArch64::STRHHpost;
546 case AArch64::STRWui:
547 case AArch64::STURWi:
548 return AArch64::STRWpost;
549 case AArch64::STRXui:
550 case AArch64::STURXi:
551 return AArch64::STRXpost;
552 case AArch64::LDRSui:
553 case AArch64::LDURSi:
554 return AArch64::LDRSpost;
555 case AArch64::LDRDui:
556 case AArch64::LDURDi:
557 return AArch64::LDRDpost;
558 case AArch64::LDRQui:
559 case AArch64::LDURQi:
560 return AArch64::LDRQpost;
561 case AArch64::LDRBBui:
562 return AArch64::LDRBBpost;
563 case AArch64::LDRHHui:
564 return AArch64::LDRHHpost;
565 case AArch64::LDRWui:
566 case AArch64::LDURWi:
567 return AArch64::LDRWpost;
568 case AArch64::LDRXui:
569 case AArch64::LDURXi:
570 return AArch64::LDRXpost;
571 case AArch64::LDRSWui:
572 return AArch64::LDRSWpost;
573 case AArch64::LDPSi:
574 return AArch64::LDPSpost;
575 case AArch64::LDPSWi:
576 return AArch64::LDPSWpost;
577 case AArch64::LDPDi:
578 return AArch64::LDPDpost;
579 case AArch64::LDPQi:
580 return AArch64::LDPQpost;
581 case AArch64::LDPWi:
582 return AArch64::LDPWpost;
583 case AArch64::LDPXi:
584 return AArch64::LDPXpost;
585 case AArch64::STPSi:
586 return AArch64::STPSpost;
587 case AArch64::STPDi:
588 return AArch64::STPDpost;
589 case AArch64::STPQi:
590 return AArch64::STPQpost;
591 case AArch64::STPWi:
592 return AArch64::STPWpost;
593 case AArch64::STPXi:
594 return AArch64::STPXpost;
595 case AArch64::STGi:
596 return AArch64::STGPostIndex;
597 case AArch64::STZGi:
598 return AArch64::STZGPostIndex;
599 case AArch64::ST2Gi:
600 return AArch64::ST2GPostIndex;
601 case AArch64::STZ2Gi:
602 return AArch64::STZ2GPostIndex;
603 case AArch64::STGPi:
604 return AArch64::STGPpost;
605 }
606}
607
609
610 unsigned OpcA = FirstMI.getOpcode();
611 unsigned OpcB = MI.getOpcode();
612
613 switch (OpcA) {
614 default:
615 return false;
616 case AArch64::STRSpre:
617 return (OpcB == AArch64::STRSui) || (OpcB == AArch64::STURSi);
618 case AArch64::STRDpre:
619 return (OpcB == AArch64::STRDui) || (OpcB == AArch64::STURDi);
620 case AArch64::STRQpre:
621 return (OpcB == AArch64::STRQui) || (OpcB == AArch64::STURQi);
622 case AArch64::STRWpre:
623 return (OpcB == AArch64::STRWui) || (OpcB == AArch64::STURWi);
624 case AArch64::STRXpre:
625 return (OpcB == AArch64::STRXui) || (OpcB == AArch64::STURXi);
626 case AArch64::LDRSpre:
627 return (OpcB == AArch64::LDRSui) || (OpcB == AArch64::LDURSi);
628 case AArch64::LDRDpre:
629 return (OpcB == AArch64::LDRDui) || (OpcB == AArch64::LDURDi);
630 case AArch64::LDRQpre:
631 return (OpcB == AArch64::LDRQui) || (OpcB == AArch64::LDURQi);
632 case AArch64::LDRWpre:
633 return (OpcB == AArch64::LDRWui) || (OpcB == AArch64::LDURWi);
634 case AArch64::LDRXpre:
635 return (OpcB == AArch64::LDRXui) || (OpcB == AArch64::LDURXi);
636 case AArch64::LDRSWpre:
637 return (OpcB == AArch64::LDRSWui) || (OpcB == AArch64::LDURSWi);
638 }
639}
640
641// Returns the scale and offset range of pre/post indexed variants of MI.
642static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
643 int &MinOffset, int &MaxOffset) {
644 bool IsPaired = AArch64InstrInfo::isPairedLdSt(MI);
645 bool IsTagStore = isTagStore(MI);
646 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
647 // as in the "unsigned offset" variant.
648 // All other pre/post indexed ldst instructions are unscaled.
649 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
650
651 if (IsPaired) {
652 MinOffset = -64;
653 MaxOffset = 63;
654 } else {
655 MinOffset = -256;
656 MaxOffset = 255;
657 }
658}
659
661 unsigned PairedRegOp = 0) {
662 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
663 bool IsPreLdSt = AArch64InstrInfo::isPreLdSt(MI);
664 if (IsPreLdSt)
665 PairedRegOp += 1;
666 unsigned Idx =
667 AArch64InstrInfo::isPairedLdSt(MI) || IsPreLdSt ? PairedRegOp : 0;
668 return MI.getOperand(Idx);
669}
670
673 const AArch64InstrInfo *TII) {
674 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
675 int LoadSize = TII->getMemScale(LoadInst);
676 int StoreSize = TII->getMemScale(StoreInst);
677 int UnscaledStOffset =
678 TII->hasUnscaledLdStOffset(StoreInst)
681 int UnscaledLdOffset =
682 TII->hasUnscaledLdStOffset(LoadInst)
685 return (UnscaledStOffset <= UnscaledLdOffset) &&
686 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
687}
688
690 unsigned Opc = MI.getOpcode();
691 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
692 isNarrowStore(Opc)) &&
693 getLdStRegOp(MI).getReg() == AArch64::WZR;
694}
695
697 switch (MI.getOpcode()) {
698 default:
699 return false;
700 // Scaled instructions.
701 case AArch64::LDRBBui:
702 case AArch64::LDRHHui:
703 case AArch64::LDRWui:
704 case AArch64::LDRXui:
705 // Unscaled instructions.
706 case AArch64::LDURBBi:
707 case AArch64::LDURHHi:
708 case AArch64::LDURWi:
709 case AArch64::LDURXi:
710 return true;
711 }
712}
713
715 unsigned Opc = MI.getOpcode();
716 switch (Opc) {
717 default:
718 return false;
719 // Scaled instructions.
720 case AArch64::STRSui:
721 case AArch64::STRDui:
722 case AArch64::STRQui:
723 case AArch64::STRXui:
724 case AArch64::STRWui:
725 case AArch64::STRHHui:
726 case AArch64::STRBBui:
727 case AArch64::LDRSui:
728 case AArch64::LDRDui:
729 case AArch64::LDRQui:
730 case AArch64::LDRXui:
731 case AArch64::LDRWui:
732 case AArch64::LDRHHui:
733 case AArch64::LDRBBui:
734 case AArch64::STGi:
735 case AArch64::STZGi:
736 case AArch64::ST2Gi:
737 case AArch64::STZ2Gi:
738 case AArch64::STGPi:
739 // Unscaled instructions.
740 case AArch64::STURSi:
741 case AArch64::STURDi:
742 case AArch64::STURQi:
743 case AArch64::STURWi:
744 case AArch64::STURXi:
745 case AArch64::LDURSi:
746 case AArch64::LDURDi:
747 case AArch64::LDURQi:
748 case AArch64::LDURWi:
749 case AArch64::LDURXi:
750 // Paired instructions.
751 case AArch64::LDPSi:
752 case AArch64::LDPSWi:
753 case AArch64::LDPDi:
754 case AArch64::LDPQi:
755 case AArch64::LDPWi:
756 case AArch64::LDPXi:
757 case AArch64::STPSi:
758 case AArch64::STPDi:
759 case AArch64::STPQi:
760 case AArch64::STPWi:
761 case AArch64::STPXi:
762 // Make sure this is a reg+imm (as opposed to an address reloc).
764 return false;
765
766 return true;
767 }
768}
769
770// Make sure this is a reg+reg Ld/St
771static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale) {
772 unsigned Opc = MI.getOpcode();
773 switch (Opc) {
774 default:
775 return false;
776 // Scaled instructions.
777 // TODO: Add more index address loads/stores.
778 case AArch64::LDRBBroX:
779 Scale = 1;
780 return true;
781 }
782}
783
784static bool isRewritableImplicitDef(unsigned Opc) {
785 switch (Opc) {
786 default:
787 return false;
788 case AArch64::ORRWrs:
789 case AArch64::ADDWri:
790 return true;
791 }
792}
793
795AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
797 const LdStPairFlags &Flags) {
799 "Expected promotable zero stores.");
800
801 MachineBasicBlock::iterator E = I->getParent()->end();
803 // If NextI is the second of the two instructions to be merged, we need
804 // to skip one further. Either way we merge will invalidate the iterator,
805 // and we don't need to scan the new instruction, as it's a pairwise
806 // instruction, which we're not considering for further action anyway.
807 if (NextI == MergeMI)
808 NextI = next_nodbg(NextI, E);
809
810 unsigned Opc = I->getOpcode();
811 unsigned MergeMIOpc = MergeMI->getOpcode();
812 bool IsScaled = !TII->hasUnscaledLdStOffset(Opc);
813 bool IsMergedMIScaled = !TII->hasUnscaledLdStOffset(MergeMIOpc);
814 int OffsetStride = IsScaled ? TII->getMemScale(*I) : 1;
815 int MergeMIOffsetStride = IsMergedMIScaled ? TII->getMemScale(*MergeMI) : 1;
816
817 bool MergeForward = Flags.getMergeForward();
818 // Insert our new paired instruction after whichever of the paired
819 // instructions MergeForward indicates.
820 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
821 // Also based on MergeForward is from where we copy the base register operand
822 // so we get the flags compatible with the input code.
823 const MachineOperand &BaseRegOp =
824 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*MergeMI)
825 : AArch64InstrInfo::getLdStBaseOp(*I);
826
827 // Which register is Rt and which is Rt2 depends on the offset order.
828 int64_t IOffsetInBytes =
829 AArch64InstrInfo::getLdStOffsetOp(*I).getImm() * OffsetStride;
830 int64_t MIOffsetInBytes =
832 MergeMIOffsetStride;
833 // Select final offset based on the offset order.
834 int64_t OffsetImm;
835 if (IOffsetInBytes > MIOffsetInBytes)
836 OffsetImm = MIOffsetInBytes;
837 else
838 OffsetImm = IOffsetInBytes;
839
840 int NewOpcode = getMatchingWideOpcode(Opc);
841 bool FinalIsScaled = !TII->hasUnscaledLdStOffset(NewOpcode);
842
843 // Adjust final offset if the result opcode is a scaled store.
844 if (FinalIsScaled) {
845 int NewOffsetStride = FinalIsScaled ? TII->getMemScale(NewOpcode) : 1;
846 assert(((OffsetImm % NewOffsetStride) == 0) &&
847 "Offset should be a multiple of the store memory scale");
848 OffsetImm = OffsetImm / NewOffsetStride;
849 }
850
851 // Construct the new instruction.
852 DebugLoc DL = I->getDebugLoc();
853 MachineBasicBlock *MBB = I->getParent();
855 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
856 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
857 .add(BaseRegOp)
858 .addImm(OffsetImm)
859 .cloneMergedMemRefs({&*I, &*MergeMI})
860 .setMIFlags(I->mergeFlagsWith(*MergeMI));
861 (void)MIB;
862
863 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
864 LLVM_DEBUG(I->print(dbgs()));
865 LLVM_DEBUG(dbgs() << " ");
866 LLVM_DEBUG(MergeMI->print(dbgs()));
867 LLVM_DEBUG(dbgs() << " with instruction:\n ");
868 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
869 LLVM_DEBUG(dbgs() << "\n");
870
871 // Erase the old instructions.
872 I->eraseFromParent();
873 MergeMI->eraseFromParent();
874 return NextI;
875}
876
877// Apply Fn to all instructions between MI and the beginning of the block, until
878// a def for DefReg is reached. Returns true, iff Fn returns true for all
879// visited instructions. Stop after visiting Limit iterations.
881 const TargetRegisterInfo *TRI, unsigned Limit,
882 std::function<bool(MachineInstr &, bool)> &Fn) {
883 auto MBB = MI.getParent();
884 for (MachineInstr &I :
885 instructionsWithoutDebug(MI.getReverseIterator(), MBB->instr_rend())) {
886 if (!Limit)
887 return false;
888 --Limit;
889
890 bool isDef = any_of(I.operands(), [DefReg, TRI](MachineOperand &MOP) {
891 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
892 TRI->regsOverlap(MOP.getReg(), DefReg);
893 });
894 if (!Fn(I, isDef))
895 return false;
896 if (isDef)
897 break;
898 }
899 return true;
900}
901
903 const TargetRegisterInfo *TRI) {
904
905 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
906 if (MOP.isReg() && MOP.isKill())
907 Units.removeReg(MOP.getReg());
908
909 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
910 if (MOP.isReg() && !MOP.isKill())
911 Units.addReg(MOP.getReg());
912}
913
915AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
917 const LdStPairFlags &Flags) {
918 MachineBasicBlock::iterator E = I->getParent()->end();
920 // If NextI is the second of the two instructions to be merged, we need
921 // to skip one further. Either way we merge will invalidate the iterator,
922 // and we don't need to scan the new instruction, as it's a pairwise
923 // instruction, which we're not considering for further action anyway.
924 if (NextI == Paired)
925 NextI = next_nodbg(NextI, E);
926
927 int SExtIdx = Flags.getSExtIdx();
928 unsigned Opc =
929 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
930 bool IsUnscaled = TII->hasUnscaledLdStOffset(Opc);
931 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
932
933 bool MergeForward = Flags.getMergeForward();
934
935 std::optional<MCPhysReg> RenameReg = Flags.getRenameReg();
936 if (RenameReg) {
937 MCRegister RegToRename = getLdStRegOp(*I).getReg();
938 DefinedInBB.addReg(*RenameReg);
939
940 // Return the sub/super register for RenameReg, matching the size of
941 // OriginalReg.
942 auto GetMatchingSubReg =
943 [this, RenameReg](const TargetRegisterClass *C) -> MCPhysReg {
944 for (MCPhysReg SubOrSuper :
945 TRI->sub_and_superregs_inclusive(*RenameReg)) {
946 if (C->contains(SubOrSuper))
947 return SubOrSuper;
948 }
949 llvm_unreachable("Should have found matching sub or super register!");
950 };
951
952 std::function<bool(MachineInstr &, bool)> UpdateMIs =
953 [this, RegToRename, GetMatchingSubReg, MergeForward](MachineInstr &MI,
954 bool IsDef) {
955 if (IsDef) {
956 bool SeenDef = false;
957 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
958 MachineOperand &MOP = MI.getOperand(OpIdx);
959 // Rename the first explicit definition and all implicit
960 // definitions matching RegToRename.
961 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
962 (!MergeForward || !SeenDef ||
963 (MOP.isDef() && MOP.isImplicit())) &&
964 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
965 assert((MOP.isImplicit() ||
966 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
967 "Need renamable operands");
968 Register MatchingReg;
969 if (const TargetRegisterClass *RC =
970 MI.getRegClassConstraint(OpIdx, TII, TRI))
971 MatchingReg = GetMatchingSubReg(RC);
972 else {
973 if (!isRewritableImplicitDef(MI.getOpcode()))
974 continue;
975 MatchingReg = GetMatchingSubReg(
976 TRI->getMinimalPhysRegClass(MOP.getReg()));
977 }
978 MOP.setReg(MatchingReg);
979 SeenDef = true;
980 }
981 }
982 } else {
983 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
984 MachineOperand &MOP = MI.getOperand(OpIdx);
985 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
986 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
987 assert((MOP.isImplicit() ||
988 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
989 "Need renamable operands");
990 Register MatchingReg;
991 if (const TargetRegisterClass *RC =
992 MI.getRegClassConstraint(OpIdx, TII, TRI))
993 MatchingReg = GetMatchingSubReg(RC);
994 else
995 MatchingReg = GetMatchingSubReg(
996 TRI->getMinimalPhysRegClass(MOP.getReg()));
997 assert(MatchingReg != AArch64::NoRegister &&
998 "Cannot find matching regs for renaming");
999 MOP.setReg(MatchingReg);
1000 }
1001 }
1002 }
1003 LLVM_DEBUG(dbgs() << "Renamed " << MI);
1004 return true;
1005 };
1006 forAllMIsUntilDef(MergeForward ? *I : *std::prev(Paired), RegToRename, TRI,
1007 UINT32_MAX, UpdateMIs);
1008
1009#if !defined(NDEBUG)
1010 // For forward merging store:
1011 // Make sure the register used for renaming is not used between the
1012 // paired instructions. That would trash the content before the new
1013 // paired instruction.
1014 MCPhysReg RegToCheck = *RenameReg;
1015 // For backward merging load:
1016 // Make sure the register being renamed is not used between the
1017 // paired instructions. That would trash the content after the new
1018 // paired instruction.
1019 if (!MergeForward)
1020 RegToCheck = RegToRename;
1021 for (auto &MI :
1023 MergeForward ? std::next(I) : I,
1024 MergeForward ? std::next(Paired) : Paired))
1025 assert(all_of(MI.operands(),
1026 [this, RegToCheck](const MachineOperand &MOP) {
1027 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1028 MOP.isUndef() ||
1029 !TRI->regsOverlap(MOP.getReg(), RegToCheck);
1030 }) &&
1031 "Rename register used between paired instruction, trashing the "
1032 "content");
1033#endif
1034 }
1035
1036 // Insert our new paired instruction after whichever of the paired
1037 // instructions MergeForward indicates.
1038 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
1039 // Also based on MergeForward is from where we copy the base register operand
1040 // so we get the flags compatible with the input code.
1041 const MachineOperand &BaseRegOp =
1042 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*Paired)
1043 : AArch64InstrInfo::getLdStBaseOp(*I);
1044
1046 int PairedOffset = AArch64InstrInfo::getLdStOffsetOp(*Paired).getImm();
1047 bool PairedIsUnscaled = TII->hasUnscaledLdStOffset(Paired->getOpcode());
1048 if (IsUnscaled != PairedIsUnscaled) {
1049 // We're trying to pair instructions that differ in how they are scaled. If
1050 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
1051 // the opposite (i.e., make Paired's offset unscaled).
1052 int MemSize = TII->getMemScale(*Paired);
1053 if (PairedIsUnscaled) {
1054 // If the unscaled offset isn't a multiple of the MemSize, we can't
1055 // pair the operations together.
1056 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
1057 "Offset should be a multiple of the stride!");
1058 PairedOffset /= MemSize;
1059 } else {
1060 PairedOffset *= MemSize;
1061 }
1062 }
1063
1064 // Which register is Rt and which is Rt2 depends on the offset order.
1065 // However, for pre load/stores the Rt should be the one of the pre
1066 // load/store.
1067 MachineInstr *RtMI, *Rt2MI;
1068 if (Offset == PairedOffset + OffsetStride &&
1070 RtMI = &*Paired;
1071 Rt2MI = &*I;
1072 // Here we swapped the assumption made for SExtIdx.
1073 // I.e., we turn ldp I, Paired into ldp Paired, I.
1074 // Update the index accordingly.
1075 if (SExtIdx != -1)
1076 SExtIdx = (SExtIdx + 1) % 2;
1077 } else {
1078 RtMI = &*I;
1079 Rt2MI = &*Paired;
1080 }
1081 int OffsetImm = AArch64InstrInfo::getLdStOffsetOp(*RtMI).getImm();
1082 // Scale the immediate offset, if necessary.
1083 if (TII->hasUnscaledLdStOffset(RtMI->getOpcode())) {
1084 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
1085 "Unscaled offset cannot be scaled.");
1086 OffsetImm /= TII->getMemScale(*RtMI);
1087 }
1088
1089 // Construct the new instruction.
1091 DebugLoc DL = I->getDebugLoc();
1092 MachineBasicBlock *MBB = I->getParent();
1093 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
1094 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
1095 MachineOperand &PairedRegOp = RtMI == &*Paired ? RegOp0 : RegOp1;
1096 // Kill flags may become invalid when moving stores for pairing.
1097 if (RegOp0.isUse()) {
1098 if (!MergeForward) {
1099 // Clear kill flags on store if moving upwards. Example:
1100 // STRWui kill %w0, ...
1101 // USE %w1
1102 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
1103 // We are about to move the store of w1, so its kill flag may become
1104 // invalid; not the case for w0.
1105 // Since w1 is used between the stores, the kill flag on w1 is cleared
1106 // after merging.
1107 // STPWi kill %w0, %w1, ...
1108 // USE %w1
1109 for (auto It = std::next(I); It != Paired && PairedRegOp.isKill(); ++It)
1110 if (It->readsRegister(PairedRegOp.getReg(), TRI))
1111 PairedRegOp.setIsKill(false);
1112 } else {
1113 // Clear kill flags of the first stores register. Example:
1114 // STRWui %w1, ...
1115 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
1116 // STRW %w0
1118 for (MachineInstr &MI : make_range(std::next(I), Paired))
1119 MI.clearRegisterKills(Reg, TRI);
1120 }
1121 }
1122
1123 unsigned int MatchPairOpcode = getMatchingPairOpcode(Opc);
1124 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(MatchPairOpcode));
1125
1126 // Adds the pre-index operand for pre-indexed ld/st pairs.
1127 if (AArch64InstrInfo::isPreLdSt(*RtMI))
1128 MIB.addReg(BaseRegOp.getReg(), RegState::Define);
1129
1130 MIB.add(RegOp0)
1131 .add(RegOp1)
1132 .add(BaseRegOp)
1133 .addImm(OffsetImm)
1134 .cloneMergedMemRefs({&*I, &*Paired})
1135 .setMIFlags(I->mergeFlagsWith(*Paired));
1136
1137 (void)MIB;
1138
1139 LLVM_DEBUG(
1140 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
1141 LLVM_DEBUG(I->print(dbgs()));
1142 LLVM_DEBUG(dbgs() << " ");
1143 LLVM_DEBUG(Paired->print(dbgs()));
1144 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1145 if (SExtIdx != -1) {
1146 // Generate the sign extension for the proper result of the ldp.
1147 // I.e., with X1, that would be:
1148 // %w1 = KILL %w1, implicit-def %x1
1149 // %x1 = SBFMXri killed %x1, 0, 31
1150 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
1151 // Right now, DstMO has the extended register, since it comes from an
1152 // extended opcode.
1153 Register DstRegX = DstMO.getReg();
1154 // Get the W variant of that register.
1155 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
1156 // Update the result of LDP to use the W instead of the X variant.
1157 DstMO.setReg(DstRegW);
1158 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1159 LLVM_DEBUG(dbgs() << "\n");
1160 // Make the machine verifier happy by providing a definition for
1161 // the X register.
1162 // Insert this definition right after the generated LDP, i.e., before
1163 // InsertionPoint.
1164 MachineInstrBuilder MIBKill =
1165 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
1166 .addReg(DstRegW)
1167 .addReg(DstRegX, RegState::Define);
1168 MIBKill->getOperand(2).setImplicit();
1169 // Create the sign extension.
1170 MachineInstrBuilder MIBSXTW =
1171 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
1172 .addReg(DstRegX)
1173 .addImm(0)
1174 .addImm(31);
1175 (void)MIBSXTW;
1176 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
1177 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
1178 } else {
1179 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1180 }
1181 LLVM_DEBUG(dbgs() << "\n");
1182
1183 if (MergeForward)
1184 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
1185 if (MOP.isReg() && MOP.isKill())
1186 DefinedInBB.addReg(MOP.getReg());
1187
1188 // Erase the old instructions.
1189 I->eraseFromParent();
1190 Paired->eraseFromParent();
1191
1192 return NextI;
1193}
1194
1196AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1199 next_nodbg(LoadI, LoadI->getParent()->end());
1200
1201 int LoadSize = TII->getMemScale(*LoadI);
1202 int StoreSize = TII->getMemScale(*StoreI);
1203 Register LdRt = getLdStRegOp(*LoadI).getReg();
1204 const MachineOperand &StMO = getLdStRegOp(*StoreI);
1205 Register StRt = getLdStRegOp(*StoreI).getReg();
1206 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1207
1208 assert((IsStoreXReg ||
1209 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1210 "Unexpected RegClass");
1211
1212 MachineInstr *BitExtMI;
1213 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1214 // Remove the load, if the destination register of the loads is the same
1215 // register for stored value.
1216 if (StRt == LdRt && LoadSize == 8) {
1217 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1218 LoadI->getIterator())) {
1219 if (MI.killsRegister(StRt, TRI)) {
1220 MI.clearRegisterKills(StRt, TRI);
1221 break;
1222 }
1223 }
1224 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1225 LLVM_DEBUG(LoadI->print(dbgs()));
1226 LLVM_DEBUG(dbgs() << "\n");
1227 LoadI->eraseFromParent();
1228 return NextI;
1229 }
1230 // Replace the load with a mov if the load and store are in the same size.
1231 BitExtMI =
1232 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1233 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1234 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
1235 .add(StMO)
1237 .setMIFlags(LoadI->getFlags());
1238 } else {
1239 // FIXME: Currently we disable this transformation in big-endian targets as
1240 // performance and correctness are verified only in little-endian.
1241 if (!Subtarget->isLittleEndian())
1242 return NextI;
1243 bool IsUnscaled = TII->hasUnscaledLdStOffset(*LoadI);
1244 assert(IsUnscaled == TII->hasUnscaledLdStOffset(*StoreI) &&
1245 "Unsupported ld/st match");
1246 assert(LoadSize <= StoreSize && "Invalid load size");
1247 int UnscaledLdOffset =
1248 IsUnscaled
1250 : AArch64InstrInfo::getLdStOffsetOp(*LoadI).getImm() * LoadSize;
1251 int UnscaledStOffset =
1252 IsUnscaled
1254 : AArch64InstrInfo::getLdStOffsetOp(*StoreI).getImm() * StoreSize;
1255 int Width = LoadSize * 8;
1256 Register DestReg =
1257 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1258 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1259 : LdRt;
1260
1261 assert((UnscaledLdOffset >= UnscaledStOffset &&
1262 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1263 "Invalid offset");
1264
1265 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1266 int Imms = Immr + Width - 1;
1267 if (UnscaledLdOffset == UnscaledStOffset) {
1268 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1269 | ((Immr) << 6) // immr
1270 | ((Imms) << 0) // imms
1271 ;
1272
1273 BitExtMI =
1274 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1275 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1276 DestReg)
1277 .add(StMO)
1278 .addImm(AndMaskEncoded)
1279 .setMIFlags(LoadI->getFlags());
1280 } else {
1281 BitExtMI =
1282 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1283 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1284 DestReg)
1285 .add(StMO)
1286 .addImm(Immr)
1287 .addImm(Imms)
1288 .setMIFlags(LoadI->getFlags());
1289 }
1290 }
1291
1292 // Clear kill flags between store and load.
1293 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1294 BitExtMI->getIterator()))
1295 if (MI.killsRegister(StRt, TRI)) {
1296 MI.clearRegisterKills(StRt, TRI);
1297 break;
1298 }
1299
1300 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1301 LLVM_DEBUG(StoreI->print(dbgs()));
1302 LLVM_DEBUG(dbgs() << " ");
1303 LLVM_DEBUG(LoadI->print(dbgs()));
1304 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1305 LLVM_DEBUG(StoreI->print(dbgs()));
1306 LLVM_DEBUG(dbgs() << " ");
1307 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1308 LLVM_DEBUG(dbgs() << "\n");
1309
1310 // Erase the old instructions.
1311 LoadI->eraseFromParent();
1312 return NextI;
1313}
1314
1315static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1316 // Convert the byte-offset used by unscaled into an "element" offset used
1317 // by the scaled pair load/store instructions.
1318 if (IsUnscaled) {
1319 // If the byte-offset isn't a multiple of the stride, there's no point
1320 // trying to match it.
1321 if (Offset % OffsetStride)
1322 return false;
1323 Offset /= OffsetStride;
1324 }
1325 return Offset <= 63 && Offset >= -64;
1326}
1327
1328// Do alignment, specialized to power of 2 and for signed ints,
1329// avoiding having to do a C-style cast from uint_64t to int when
1330// using alignTo from include/llvm/Support/MathExtras.h.
1331// FIXME: Move this function to include/MathExtras.h?
1332static int alignTo(int Num, int PowOf2) {
1333 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1334}
1335
1336static bool mayAlias(MachineInstr &MIa,
1338 AliasAnalysis *AA) {
1339 for (MachineInstr *MIb : MemInsns) {
1340 if (MIa.mayAlias(AA, *MIb, /*UseTBAA*/ false)) {
1341 LLVM_DEBUG(dbgs() << "Aliasing with: "; MIb->dump());
1342 return true;
1343 }
1344 }
1345
1346 LLVM_DEBUG(dbgs() << "No aliases found\n");
1347 return false;
1348}
1349
1350bool AArch64LoadStoreOpt::findMatchingStore(
1351 MachineBasicBlock::iterator I, unsigned Limit,
1353 MachineBasicBlock::iterator B = I->getParent()->begin();
1355 MachineInstr &LoadMI = *I;
1357
1358 // If the load is the first instruction in the block, there's obviously
1359 // not any matching store.
1360 if (MBBI == B)
1361 return false;
1362
1363 // Track which register units have been modified and used between the first
1364 // insn and the second insn.
1365 ModifiedRegUnits.clear();
1366 UsedRegUnits.clear();
1367
1368 unsigned Count = 0;
1369 do {
1370 MBBI = prev_nodbg(MBBI, B);
1371 MachineInstr &MI = *MBBI;
1372
1373 // Don't count transient instructions towards the search limit since there
1374 // may be different numbers of them if e.g. debug information is present.
1375 if (!MI.isTransient())
1376 ++Count;
1377
1378 // If the load instruction reads directly from the address to which the
1379 // store instruction writes and the stored value is not modified, we can
1380 // promote the load. Since we do not handle stores with pre-/post-index,
1381 // it's unnecessary to check if BaseReg is modified by the store itself.
1382 // Also we can't handle stores without an immediate offset operand,
1383 // while the operand might be the address for a global variable.
1384 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1387 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1388 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1389 StoreI = MBBI;
1390 return true;
1391 }
1392
1393 if (MI.isCall())
1394 return false;
1395
1396 // Update modified / uses register units.
1397 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1398
1399 // Otherwise, if the base register is modified, we have no match, so
1400 // return early.
1401 if (!ModifiedRegUnits.available(BaseReg))
1402 return false;
1403
1404 // If we encounter a store aliased with the load, return early.
1405 if (MI.mayStore() && LoadMI.mayAlias(AA, MI, /*UseTBAA*/ false))
1406 return false;
1407 } while (MBBI != B && Count < Limit);
1408 return false;
1409}
1410
1411static bool needsWinCFI(const MachineFunction *MF) {
1412 return MF->getTarget().getMCAsmInfo()->usesWindowsCFI() &&
1414}
1415
1416// Returns true if FirstMI and MI are candidates for merging or pairing.
1417// Otherwise, returns false.
1419 LdStPairFlags &Flags,
1420 const AArch64InstrInfo *TII) {
1421 // If this is volatile or if pairing is suppressed, not a candidate.
1422 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1423 return false;
1424
1425 // We should have already checked FirstMI for pair suppression and volatility.
1426 assert(!FirstMI.hasOrderedMemoryRef() &&
1427 !TII->isLdStPairSuppressed(FirstMI) &&
1428 "FirstMI shouldn't get here if either of these checks are true.");
1429
1430 if (needsWinCFI(MI.getMF()) && (MI.getFlag(MachineInstr::FrameSetup) ||
1432 return false;
1433
1434 unsigned OpcA = FirstMI.getOpcode();
1435 unsigned OpcB = MI.getOpcode();
1436
1437 // Opcodes match: If the opcodes are pre ld/st there is nothing more to check.
1438 if (OpcA == OpcB)
1439 return !AArch64InstrInfo::isPreLdSt(FirstMI);
1440
1441 // Two pre ld/st of different opcodes cannot be merged either
1443 return false;
1444
1445 // Try to match a sign-extended load/store with a zero-extended load/store.
1446 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1447 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1448 assert(IsValidLdStrOpc &&
1449 "Given Opc should be a Load or Store with an immediate");
1450 // OpcA will be the first instruction in the pair.
1451 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1452 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1453 return true;
1454 }
1455
1456 // If the second instruction isn't even a mergable/pairable load/store, bail
1457 // out.
1458 if (!PairIsValidLdStrOpc)
1459 return false;
1460
1461 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1462 // offsets.
1463 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1464 return false;
1465
1466 // The STR<S,D,Q,W,X>pre - STR<S,D,Q,W,X>ui and
1467 // LDR<S,D,Q,W,X,SW>pre-LDR<S,D,Q,W,X,SW>ui
1468 // are candidate pairs that can be merged.
1469 if (isPreLdStPairCandidate(FirstMI, MI))
1470 return true;
1471
1472 // Try to match an unscaled load/store with a scaled load/store.
1473 return TII->hasUnscaledLdStOffset(OpcA) != TII->hasUnscaledLdStOffset(OpcB) &&
1475
1476 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1477}
1478
1479static bool canRenameMOP(const MachineOperand &MOP,
1480 const TargetRegisterInfo *TRI) {
1481 if (MOP.isReg()) {
1482 auto *RegClass = TRI->getMinimalPhysRegClass(MOP.getReg());
1483 // Renaming registers with multiple disjunct sub-registers (e.g. the
1484 // result of a LD3) means that all sub-registers are renamed, potentially
1485 // impacting other instructions we did not check. Bail out.
1486 // Note that this relies on the structure of the AArch64 register file. In
1487 // particular, a subregister cannot be written without overwriting the
1488 // whole register.
1489 if (RegClass->HasDisjunctSubRegs) {
1490 LLVM_DEBUG(
1491 dbgs()
1492 << " Cannot rename operands with multiple disjunct subregisters ("
1493 << MOP << ")\n");
1494 return false;
1495 }
1496
1497 // We cannot rename arbitrary implicit-defs, the specific rule to rewrite
1498 // them must be known. For example, in ORRWrs the implicit-def
1499 // corresponds to the result register.
1500 if (MOP.isImplicit() && MOP.isDef()) {
1502 return false;
1503 return TRI->isSuperOrSubRegisterEq(
1504 MOP.getParent()->getOperand(0).getReg(), MOP.getReg());
1505 }
1506 }
1507 return MOP.isImplicit() ||
1508 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1509}
1510
1511static bool
1514 const TargetRegisterInfo *TRI) {
1515 if (!FirstMI.mayStore())
1516 return false;
1517
1518 // Check if we can find an unused register which we can use to rename
1519 // the register used by the first load/store.
1520
1521 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1522 // For now, we only rename if the store operand gets killed at the store.
1523 if (!getLdStRegOp(FirstMI).isKill() &&
1524 !any_of(FirstMI.operands(),
1525 [TRI, RegToRename](const MachineOperand &MOP) {
1526 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1527 MOP.isImplicit() && MOP.isKill() &&
1528 TRI->regsOverlap(RegToRename, MOP.getReg());
1529 })) {
1530 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI);
1531 return false;
1532 }
1533
1534 bool FoundDef = false;
1535
1536 // For each instruction between FirstMI and the previous def for RegToRename,
1537 // we
1538 // * check if we can rename RegToRename in this instruction
1539 // * collect the registers used and required register classes for RegToRename.
1540 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1541 bool IsDef) {
1542 LLVM_DEBUG(dbgs() << "Checking " << MI);
1543 // Currently we do not try to rename across frame-setup instructions.
1544 if (MI.getFlag(MachineInstr::FrameSetup)) {
1545 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1546 << "currently\n");
1547 return false;
1548 }
1549
1550 UsedInBetween.accumulate(MI);
1551
1552 // For a definition, check that we can rename the definition and exit the
1553 // loop.
1554 FoundDef = IsDef;
1555
1556 // For defs, check if we can rename the first def of RegToRename.
1557 if (FoundDef) {
1558 // For some pseudo instructions, we might not generate code in the end
1559 // (e.g. KILL) and we would end up without a correct def for the rename
1560 // register.
1561 // TODO: This might be overly conservative and we could handle those cases
1562 // in multiple ways:
1563 // 1. Insert an extra copy, to materialize the def.
1564 // 2. Skip pseudo-defs until we find an non-pseudo def.
1565 if (MI.isPseudo()) {
1566 LLVM_DEBUG(dbgs() << " Cannot rename pseudo/bundle instruction\n");
1567 return false;
1568 }
1569
1570 for (auto &MOP : MI.operands()) {
1571 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1572 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1573 continue;
1574 if (!canRenameMOP(MOP, TRI)) {
1575 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1576 return false;
1577 }
1578 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1579 }
1580 return true;
1581 } else {
1582 for (auto &MOP : MI.operands()) {
1583 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1584 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1585 continue;
1586
1587 if (!canRenameMOP(MOP, TRI)) {
1588 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1589 return false;
1590 }
1591 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1592 }
1593 }
1594 return true;
1595 };
1596
1597 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1598 return false;
1599
1600 if (!FoundDef) {
1601 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1602 return false;
1603 }
1604 return true;
1605}
1606
1607// We want to merge the second load into the first by rewriting the usages of
1608// the same reg between first (incl.) and second (excl.). We don't need to care
1609// about any insns before FirstLoad or after SecondLoad.
1610// 1. The second load writes new value into the same reg.
1611// - The renaming is impossible to impact later use of the reg.
1612// - The second load always trash the value written by the first load which
1613// means the reg must be killed before the second load.
1614// 2. The first load must be a def for the same reg so we don't need to look
1615// into anything before it.
1617 MachineInstr &FirstLoad, MachineInstr &SecondLoad,
1618 LiveRegUnits &UsedInBetween,
1620 const TargetRegisterInfo *TRI) {
1621 if (FirstLoad.isPseudo())
1622 return false;
1623
1624 UsedInBetween.accumulate(FirstLoad);
1625 auto RegToRename = getLdStRegOp(FirstLoad).getReg();
1626 bool Success = std::all_of(
1627 FirstLoad.getIterator(), SecondLoad.getIterator(),
1628 [&](MachineInstr &MI) {
1629 LLVM_DEBUG(dbgs() << "Checking " << MI);
1630 // Currently we do not try to rename across frame-setup instructions.
1631 if (MI.getFlag(MachineInstr::FrameSetup)) {
1632 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1633 << "currently\n");
1634 return false;
1635 }
1636
1637 for (auto &MOP : MI.operands()) {
1638 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1639 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1640 continue;
1641 if (!canRenameMOP(MOP, TRI)) {
1642 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1643 return false;
1644 }
1645 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1646 }
1647
1648 return true;
1649 });
1650 return Success;
1651}
1652
1653// Check if we can find a physical register for renaming \p Reg. This register
1654// must:
1655// * not be defined already in \p DefinedInBB; DefinedInBB must contain all
1656// defined registers up to the point where the renamed register will be used,
1657// * not used in \p UsedInBetween; UsedInBetween must contain all accessed
1658// registers in the range the rename register will be used,
1659// * is available in all used register classes (checked using RequiredClasses).
1660static std::optional<MCPhysReg> tryToFindRegisterToRename(
1661 const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB,
1662 LiveRegUnits &UsedInBetween,
1664 const TargetRegisterInfo *TRI) {
1666
1667 // Checks if any sub- or super-register of PR is callee saved.
1668 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1669 return any_of(TRI->sub_and_superregs_inclusive(PR),
1670 [&MF, TRI](MCPhysReg SubOrSuper) {
1671 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1672 });
1673 };
1674
1675 // Check if PR or one of its sub- or super-registers can be used for all
1676 // required register classes.
1677 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1678 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1679 return any_of(
1680 TRI->sub_and_superregs_inclusive(PR),
1681 [C](MCPhysReg SubOrSuper) { return C->contains(SubOrSuper); });
1682 });
1683 };
1684
1685 auto *RegClass = TRI->getMinimalPhysRegClass(Reg);
1686 for (const MCPhysReg &PR : *RegClass) {
1687 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1688 !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1689 CanBeUsedForAllClasses(PR)) {
1690 DefinedInBB.addReg(PR);
1691 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1692 << "\n");
1693 return {PR};
1694 }
1695 }
1696 LLVM_DEBUG(dbgs() << "No rename register found from "
1697 << TRI->getRegClassName(RegClass) << "\n");
1698 return std::nullopt;
1699}
1700
1701// For store pairs: returns a register from FirstMI to the beginning of the
1702// block that can be renamed.
1703// For load pairs: returns a register from FirstMI to MI that can be renamed.
1704static std::optional<MCPhysReg> findRenameRegForSameLdStRegPair(
1705 std::optional<bool> MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI,
1706 Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween,
1708 const TargetRegisterInfo *TRI) {
1709 std::optional<MCPhysReg> RenameReg;
1710 if (!DebugCounter::shouldExecute(RegRenamingCounter))
1711 return RenameReg;
1712
1713 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1714 MachineFunction &MF = *FirstMI.getParent()->getParent();
1715 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1716 return RenameReg;
1717
1718 const bool IsLoad = FirstMI.mayLoad();
1719
1720 if (!MaybeCanRename) {
1721 if (IsLoad)
1722 MaybeCanRename = {canRenameUntilSecondLoad(FirstMI, MI, UsedInBetween,
1723 RequiredClasses, TRI)};
1724 else
1725 MaybeCanRename = {
1726 canRenameUpToDef(FirstMI, UsedInBetween, RequiredClasses, TRI)};
1727 }
1728
1729 if (*MaybeCanRename) {
1730 RenameReg = tryToFindRegisterToRename(MF, Reg, DefinedInBB, UsedInBetween,
1731 RequiredClasses, TRI);
1732 }
1733 return RenameReg;
1734}
1735
1736/// Scan the instructions looking for a load/store that can be combined with the
1737/// current instruction into a wider equivalent or a load/store pair.
1739AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1740 LdStPairFlags &Flags, unsigned Limit,
1741 bool FindNarrowMerge) {
1742 MachineBasicBlock::iterator E = I->getParent()->end();
1744 MachineBasicBlock::iterator MBBIWithRenameReg;
1745 MachineInstr &FirstMI = *I;
1746 MBBI = next_nodbg(MBBI, E);
1747
1748 bool MayLoad = FirstMI.mayLoad();
1749 bool IsUnscaled = TII->hasUnscaledLdStOffset(FirstMI);
1750 Register Reg = getLdStRegOp(FirstMI).getReg();
1751 Register BaseReg = AArch64InstrInfo::getLdStBaseOp(FirstMI).getReg();
1753 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1754 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1755
1756 std::optional<bool> MaybeCanRename;
1757 if (!EnableRenaming)
1758 MaybeCanRename = {false};
1759
1761 LiveRegUnits UsedInBetween;
1762 UsedInBetween.init(*TRI);
1763
1764 Flags.clearRenameReg();
1765
1766 // Track which register units have been modified and used between the first
1767 // insn (inclusive) and the second insn.
1768 ModifiedRegUnits.clear();
1769 UsedRegUnits.clear();
1770
1771 // Remember any instructions that read/write memory between FirstMI and MI.
1773
1774 LLVM_DEBUG(dbgs() << "Find match for: "; FirstMI.dump());
1775 for (unsigned Count = 0; MBBI != E && Count < Limit;
1776 MBBI = next_nodbg(MBBI, E)) {
1777 MachineInstr &MI = *MBBI;
1778 LLVM_DEBUG(dbgs() << "Analysing 2nd insn: "; MI.dump());
1779
1780 UsedInBetween.accumulate(MI);
1781
1782 // Don't count transient instructions towards the search limit since there
1783 // may be different numbers of them if e.g. debug information is present.
1784 if (!MI.isTransient())
1785 ++Count;
1786
1787 Flags.setSExtIdx(-1);
1788 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1790 assert(MI.mayLoadOrStore() && "Expected memory operation.");
1791 // If we've found another instruction with the same opcode, check to see
1792 // if the base and offset are compatible with our starting instruction.
1793 // These instructions all have scaled immediate operands, so we just
1794 // check for +1/-1. Make sure to check the new instruction offset is
1795 // actually an immediate and not a symbolic reference destined for
1796 // a relocation.
1799 bool MIIsUnscaled = TII->hasUnscaledLdStOffset(MI);
1800 if (IsUnscaled != MIIsUnscaled) {
1801 // We're trying to pair instructions that differ in how they are scaled.
1802 // If FirstMI is scaled then scale the offset of MI accordingly.
1803 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1804 int MemSize = TII->getMemScale(MI);
1805 if (MIIsUnscaled) {
1806 // If the unscaled offset isn't a multiple of the MemSize, we can't
1807 // pair the operations together: bail and keep looking.
1808 if (MIOffset % MemSize) {
1809 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1810 UsedRegUnits, TRI);
1811 MemInsns.push_back(&MI);
1812 continue;
1813 }
1814 MIOffset /= MemSize;
1815 } else {
1816 MIOffset *= MemSize;
1817 }
1818 }
1819
1820 bool IsPreLdSt = isPreLdStPairCandidate(FirstMI, MI);
1821
1822 if (BaseReg == MIBaseReg) {
1823 // If the offset of the second ld/st is not equal to the size of the
1824 // destination register it can’t be paired with a pre-index ld/st
1825 // pair. Additionally if the base reg is used or modified the operations
1826 // can't be paired: bail and keep looking.
1827 if (IsPreLdSt) {
1828 bool IsOutOfBounds = MIOffset != TII->getMemScale(MI);
1829 bool IsBaseRegUsed = !UsedRegUnits.available(
1831 bool IsBaseRegModified = !ModifiedRegUnits.available(
1833 // If the stored value and the address of the second instruction is
1834 // the same, it needs to be using the updated register and therefore
1835 // it must not be folded.
1836 bool IsMIRegTheSame =
1837 TRI->regsOverlap(getLdStRegOp(MI).getReg(),
1839 if (IsOutOfBounds || IsBaseRegUsed || IsBaseRegModified ||
1840 IsMIRegTheSame) {
1841 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1842 UsedRegUnits, TRI);
1843 MemInsns.push_back(&MI);
1844 continue;
1845 }
1846 } else {
1847 if ((Offset != MIOffset + OffsetStride) &&
1848 (Offset + OffsetStride != MIOffset)) {
1849 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1850 UsedRegUnits, TRI);
1851 MemInsns.push_back(&MI);
1852 continue;
1853 }
1854 }
1855
1856 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1857 if (FindNarrowMerge) {
1858 // If the alignment requirements of the scaled wide load/store
1859 // instruction can't express the offset of the scaled narrow input,
1860 // bail and keep looking. For promotable zero stores, allow only when
1861 // the stored value is the same (i.e., WZR).
1862 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1863 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1864 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1865 UsedRegUnits, TRI);
1866 MemInsns.push_back(&MI);
1867 continue;
1868 }
1869 } else {
1870 // Pairwise instructions have a 7-bit signed offset field. Single
1871 // insns have a 12-bit unsigned offset field. If the resultant
1872 // immediate offset of merging these instructions is out of range for
1873 // a pairwise instruction, bail and keep looking.
1874 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1875 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1876 UsedRegUnits, TRI);
1877 MemInsns.push_back(&MI);
1878 LLVM_DEBUG(dbgs() << "Offset doesn't fit in immediate, "
1879 << "keep looking.\n");
1880 continue;
1881 }
1882 // If the alignment requirements of the paired (scaled) instruction
1883 // can't express the offset of the unscaled input, bail and keep
1884 // looking.
1885 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1886 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1887 UsedRegUnits, TRI);
1888 MemInsns.push_back(&MI);
1890 << "Offset doesn't fit due to alignment requirements, "
1891 << "keep looking.\n");
1892 continue;
1893 }
1894 }
1895
1896 // If the BaseReg has been modified, then we cannot do the optimization.
1897 // For example, in the following pattern
1898 // ldr x1 [x2]
1899 // ldr x2 [x3]
1900 // ldr x4 [x2, #8],
1901 // the first and third ldr cannot be converted to ldp x1, x4, [x2]
1902 if (!ModifiedRegUnits.available(BaseReg))
1903 return E;
1904
1905 const bool SameLoadReg = MayLoad && TRI->isSuperOrSubRegisterEq(
1906 Reg, getLdStRegOp(MI).getReg());
1907
1908 // If the Rt of the second instruction (destination register of the
1909 // load) was not modified or used between the two instructions and none
1910 // of the instructions between the second and first alias with the
1911 // second, we can combine the second into the first.
1912 bool RtNotModified =
1913 ModifiedRegUnits.available(getLdStRegOp(MI).getReg());
1914 bool RtNotUsed = !(MI.mayLoad() && !SameLoadReg &&
1915 !UsedRegUnits.available(getLdStRegOp(MI).getReg()));
1916
1917 LLVM_DEBUG(dbgs() << "Checking, can combine 2nd into 1st insn:\n"
1918 << "Reg '" << getLdStRegOp(MI) << "' not modified: "
1919 << (RtNotModified ? "true" : "false") << "\n"
1920 << "Reg '" << getLdStRegOp(MI) << "' not used: "
1921 << (RtNotUsed ? "true" : "false") << "\n");
1922
1923 if (RtNotModified && RtNotUsed && !mayAlias(MI, MemInsns, AA)) {
1924 // For pairs loading into the same reg, try to find a renaming
1925 // opportunity to allow the renaming of Reg between FirstMI and MI
1926 // and combine MI into FirstMI; otherwise bail and keep looking.
1927 if (SameLoadReg) {
1928 std::optional<MCPhysReg> RenameReg =
1929 findRenameRegForSameLdStRegPair(MaybeCanRename, FirstMI, MI,
1930 Reg, DefinedInBB, UsedInBetween,
1931 RequiredClasses, TRI);
1932 if (!RenameReg) {
1933 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1934 UsedRegUnits, TRI);
1935 MemInsns.push_back(&MI);
1936 LLVM_DEBUG(dbgs() << "Can't find reg for renaming, "
1937 << "keep looking.\n");
1938 continue;
1939 }
1940 Flags.setRenameReg(*RenameReg);
1941 }
1942
1943 Flags.setMergeForward(false);
1944 if (!SameLoadReg)
1945 Flags.clearRenameReg();
1946 return MBBI;
1947 }
1948
1949 // Likewise, if the Rt of the first instruction is not modified or used
1950 // between the two instructions and none of the instructions between the
1951 // first and the second alias with the first, we can combine the first
1952 // into the second.
1953 RtNotModified = !(
1954 MayLoad && !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg()));
1955
1956 LLVM_DEBUG(dbgs() << "Checking, can combine 1st into 2nd insn:\n"
1957 << "Reg '" << getLdStRegOp(FirstMI)
1958 << "' not modified: "
1959 << (RtNotModified ? "true" : "false") << "\n");
1960
1961 if (RtNotModified && !mayAlias(FirstMI, MemInsns, AA)) {
1962 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1963 Flags.setMergeForward(true);
1964 Flags.clearRenameReg();
1965 return MBBI;
1966 }
1967
1968 std::optional<MCPhysReg> RenameReg = findRenameRegForSameLdStRegPair(
1969 MaybeCanRename, FirstMI, MI, Reg, DefinedInBB, UsedInBetween,
1970 RequiredClasses, TRI);
1971 if (RenameReg) {
1972 Flags.setMergeForward(true);
1973 Flags.setRenameReg(*RenameReg);
1974 MBBIWithRenameReg = MBBI;
1975 }
1976 }
1977 LLVM_DEBUG(dbgs() << "Unable to combine these instructions due to "
1978 << "interference in between, keep looking.\n");
1979 }
1980 }
1981
1982 if (Flags.getRenameReg())
1983 return MBBIWithRenameReg;
1984
1985 // If the instruction wasn't a matching load or store. Stop searching if we
1986 // encounter a call instruction that might modify memory.
1987 if (MI.isCall()) {
1988 LLVM_DEBUG(dbgs() << "Found a call, stop looking.\n");
1989 return E;
1990 }
1991
1992 // Update modified / uses register units.
1993 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1994
1995 // Otherwise, if the base register is modified, we have no match, so
1996 // return early.
1997 if (!ModifiedRegUnits.available(BaseReg)) {
1998 LLVM_DEBUG(dbgs() << "Base reg is modified, stop looking.\n");
1999 return E;
2000 }
2001
2002 // Update list of instructions that read/write memory.
2003 if (MI.mayLoadOrStore())
2004 MemInsns.push_back(&MI);
2005 }
2006 return E;
2007}
2008
2011 assert((MI.getOpcode() == AArch64::SUBXri ||
2012 MI.getOpcode() == AArch64::ADDXri) &&
2013 "Expected a register update instruction");
2014 auto End = MI.getParent()->end();
2015 if (MaybeCFI == End ||
2016 MaybeCFI->getOpcode() != TargetOpcode::CFI_INSTRUCTION ||
2017 !(MI.getFlag(MachineInstr::FrameSetup) ||
2018 MI.getFlag(MachineInstr::FrameDestroy)) ||
2019 MI.getOperand(0).getReg() != AArch64::SP)
2020 return End;
2021
2022 const MachineFunction &MF = *MI.getParent()->getParent();
2023 unsigned CFIIndex = MaybeCFI->getOperand(0).getCFIIndex();
2024 const MCCFIInstruction &CFI = MF.getFrameInstructions()[CFIIndex];
2025 switch (CFI.getOperation()) {
2028 return MaybeCFI;
2029 default:
2030 return End;
2031 }
2032}
2033
2035AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
2037 bool IsPreIdx) {
2038 assert((Update->getOpcode() == AArch64::ADDXri ||
2039 Update->getOpcode() == AArch64::SUBXri) &&
2040 "Unexpected base register update instruction to merge!");
2041 MachineBasicBlock::iterator E = I->getParent()->end();
2043
2044 // If updating the SP and the following instruction is CFA offset related CFI
2045 // instruction move it after the merged instruction.
2047 IsPreIdx ? maybeMoveCFI(*Update, next_nodbg(Update, E)) : E;
2048
2049 // Return the instruction following the merged instruction, which is
2050 // the instruction following our unmerged load. Unless that's the add/sub
2051 // instruction we're merging, in which case it's the one after that.
2052 if (NextI == Update)
2053 NextI = next_nodbg(NextI, E);
2054
2055 int Value = Update->getOperand(2).getImm();
2056 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
2057 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
2058 if (Update->getOpcode() == AArch64::SUBXri)
2059 Value = -Value;
2060
2061 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
2064 int Scale, MinOffset, MaxOffset;
2065 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
2067 // Non-paired instruction.
2068 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2069 .add(Update->getOperand(0))
2070 .add(getLdStRegOp(*I))
2072 .addImm(Value / Scale)
2073 .setMemRefs(I->memoperands())
2074 .setMIFlags(I->mergeFlagsWith(*Update));
2075 } else {
2076 // Paired instruction.
2077 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2078 .add(Update->getOperand(0))
2079 .add(getLdStRegOp(*I, 0))
2080 .add(getLdStRegOp(*I, 1))
2082 .addImm(Value / Scale)
2083 .setMemRefs(I->memoperands())
2084 .setMIFlags(I->mergeFlagsWith(*Update));
2085 }
2086 if (CFI != E) {
2087 MachineBasicBlock *MBB = I->getParent();
2088 MBB->splice(std::next(MIB.getInstr()->getIterator()), MBB, CFI);
2089 }
2090
2091 if (IsPreIdx) {
2092 ++NumPreFolded;
2093 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
2094 } else {
2095 ++NumPostFolded;
2096 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
2097 }
2098 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2099 LLVM_DEBUG(I->print(dbgs()));
2100 LLVM_DEBUG(dbgs() << " ");
2101 LLVM_DEBUG(Update->print(dbgs()));
2102 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2103 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
2104 LLVM_DEBUG(dbgs() << "\n");
2105
2106 // Erase the old instructions for the block.
2107 I->eraseFromParent();
2108 Update->eraseFromParent();
2109
2110 return NextI;
2111}
2112
2114AArch64LoadStoreOpt::mergeConstOffsetInsn(MachineBasicBlock::iterator I,
2116 unsigned Offset, int Scale) {
2117 assert((Update->getOpcode() == AArch64::MOVKWi) &&
2118 "Unexpected const mov instruction to merge!");
2119 MachineBasicBlock::iterator E = I->getParent()->end();
2121 MachineBasicBlock::iterator PrevI = prev_nodbg(Update, E);
2122 MachineInstr &MemMI = *I;
2123 unsigned Mask = (1 << 12) * Scale - 1;
2124 unsigned Low = Offset & Mask;
2125 unsigned High = Offset - Low;
2128 MachineInstrBuilder AddMIB, MemMIB;
2129
2130 // Add IndexReg, BaseReg, High (the BaseReg may be SP)
2131 AddMIB =
2132 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(AArch64::ADDXri))
2133 .addDef(IndexReg)
2134 .addUse(BaseReg)
2135 .addImm(High >> 12) // shifted value
2136 .addImm(12); // shift 12
2137 (void)AddMIB;
2138 // Ld/St DestReg, IndexReg, Imm12
2139 unsigned NewOpc = getBaseAddressOpcode(I->getOpcode());
2140 MemMIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2141 .add(getLdStRegOp(MemMI))
2143 .addImm(Low / Scale)
2144 .setMemRefs(I->memoperands())
2145 .setMIFlags(I->mergeFlagsWith(*Update));
2146 (void)MemMIB;
2147
2148 ++NumConstOffsetFolded;
2149 LLVM_DEBUG(dbgs() << "Creating base address load/store.\n");
2150 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2151 LLVM_DEBUG(PrevI->print(dbgs()));
2152 LLVM_DEBUG(dbgs() << " ");
2153 LLVM_DEBUG(Update->print(dbgs()));
2154 LLVM_DEBUG(dbgs() << " ");
2155 LLVM_DEBUG(I->print(dbgs()));
2156 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2157 LLVM_DEBUG(((MachineInstr *)AddMIB)->print(dbgs()));
2158 LLVM_DEBUG(dbgs() << " ");
2159 LLVM_DEBUG(((MachineInstr *)MemMIB)->print(dbgs()));
2160 LLVM_DEBUG(dbgs() << "\n");
2161
2162 // Erase the old instructions for the block.
2163 I->eraseFromParent();
2164 PrevI->eraseFromParent();
2165 Update->eraseFromParent();
2166
2167 return NextI;
2168}
2169
2170bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
2172 unsigned BaseReg, int Offset) {
2173 switch (MI.getOpcode()) {
2174 default:
2175 break;
2176 case AArch64::SUBXri:
2177 case AArch64::ADDXri:
2178 // Make sure it's a vanilla immediate operand, not a relocation or
2179 // anything else we can't handle.
2180 if (!MI.getOperand(2).isImm())
2181 break;
2182 // Watch out for 1 << 12 shifted value.
2183 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
2184 break;
2185
2186 // The update instruction source and destination register must be the
2187 // same as the load/store base register.
2188 if (MI.getOperand(0).getReg() != BaseReg ||
2189 MI.getOperand(1).getReg() != BaseReg)
2190 break;
2191
2192 int UpdateOffset = MI.getOperand(2).getImm();
2193 if (MI.getOpcode() == AArch64::SUBXri)
2194 UpdateOffset = -UpdateOffset;
2195
2196 // The immediate must be a multiple of the scaling factor of the pre/post
2197 // indexed instruction.
2198 int Scale, MinOffset, MaxOffset;
2199 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
2200 if (UpdateOffset % Scale != 0)
2201 break;
2202
2203 // Scaled offset must fit in the instruction immediate.
2204 int ScaledOffset = UpdateOffset / Scale;
2205 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
2206 break;
2207
2208 // If we have a non-zero Offset, we check that it matches the amount
2209 // we're adding to the register.
2210 if (!Offset || Offset == UpdateOffset)
2211 return true;
2212 break;
2213 }
2214 return false;
2215}
2216
2217bool AArch64LoadStoreOpt::isMatchingMovConstInsn(MachineInstr &MemMI,
2219 unsigned IndexReg,
2220 unsigned &Offset) {
2221 // The update instruction source and destination register must be the
2222 // same as the load/store index register.
2223 if (MI.getOpcode() == AArch64::MOVKWi &&
2224 TRI->isSuperOrSubRegisterEq(IndexReg, MI.getOperand(1).getReg())) {
2225
2226 // movz + movk hold a large offset of a Ld/St instruction.
2227 MachineBasicBlock::iterator B = MI.getParent()->begin();
2229 // Skip the scene when the MI is the first instruction of a block.
2230 if (MBBI == B)
2231 return false;
2232 MBBI = prev_nodbg(MBBI, B);
2233 MachineInstr &MovzMI = *MBBI;
2234 if (MovzMI.getOpcode() == AArch64::MOVZWi) {
2235 unsigned Low = MovzMI.getOperand(1).getImm();
2236 unsigned High = MI.getOperand(2).getImm() << MI.getOperand(3).getImm();
2237 Offset = High + Low;
2238 // 12-bit optionally shifted immediates are legal for adds.
2239 return Offset >> 24 == 0;
2240 }
2241 }
2242 return false;
2243}
2244
2245MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
2246 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
2247 MachineBasicBlock::iterator E = I->getParent()->end();
2248 MachineInstr &MemMI = *I;
2250
2252 int MIUnscaledOffset = AArch64InstrInfo::getLdStOffsetOp(MemMI).getImm() *
2253 TII->getMemScale(MemMI);
2254
2255 // Scan forward looking for post-index opportunities. Updating instructions
2256 // can't be formed if the memory instruction doesn't have the offset we're
2257 // looking for.
2258 if (MIUnscaledOffset != UnscaledOffset)
2259 return E;
2260
2261 // If the base register overlaps a source/destination register, we can't
2262 // merge the update. This does not apply to tag store instructions which
2263 // ignore the address part of the source register.
2264 // This does not apply to STGPi as well, which does not have unpredictable
2265 // behavior in this case unlike normal stores, and always performs writeback
2266 // after reading the source register value.
2267 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
2268 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2269 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2270 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2271 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2272 return E;
2273 }
2274 }
2275
2276 // Track which register units have been modified and used between the first
2277 // insn (inclusive) and the second insn.
2278 ModifiedRegUnits.clear();
2279 UsedRegUnits.clear();
2280 MBBI = next_nodbg(MBBI, E);
2281
2282 // We can't post-increment the stack pointer if any instruction between
2283 // the memory access (I) and the increment (MBBI) can access the memory
2284 // region defined by [SP, MBBI].
2285 const bool BaseRegSP = BaseReg == AArch64::SP;
2286 if (BaseRegSP && needsWinCFI(I->getMF())) {
2287 // FIXME: For now, we always block the optimization over SP in windows
2288 // targets as it requires to adjust the unwind/debug info, messing up
2289 // the unwind info can actually cause a miscompile.
2290 return E;
2291 }
2292
2293 for (unsigned Count = 0; MBBI != E && Count < Limit;
2294 MBBI = next_nodbg(MBBI, E)) {
2295 MachineInstr &MI = *MBBI;
2296
2297 // Don't count transient instructions towards the search limit since there
2298 // may be different numbers of them if e.g. debug information is present.
2299 if (!MI.isTransient())
2300 ++Count;
2301
2302 // If we found a match, return it.
2303 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
2304 return MBBI;
2305
2306 // Update the status of what the instruction clobbered and used.
2307 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2308
2309 // Otherwise, if the base register is used or modified, we have no match, so
2310 // return early.
2311 // If we are optimizing SP, do not allow instructions that may load or store
2312 // in between the load and the optimized value update.
2313 if (!ModifiedRegUnits.available(BaseReg) ||
2314 !UsedRegUnits.available(BaseReg) ||
2315 (BaseRegSP && MBBI->mayLoadOrStore()))
2316 return E;
2317 }
2318 return E;
2319}
2320
2321MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
2322 MachineBasicBlock::iterator I, unsigned Limit) {
2323 MachineBasicBlock::iterator B = I->getParent()->begin();
2324 MachineBasicBlock::iterator E = I->getParent()->end();
2325 MachineInstr &MemMI = *I;
2327 MachineFunction &MF = *MemMI.getMF();
2328
2331
2332 // If the load/store is the first instruction in the block, there's obviously
2333 // not any matching update. Ditto if the memory offset isn't zero.
2334 if (MBBI == B || Offset != 0)
2335 return E;
2336 // If the base register overlaps a destination register, we can't
2337 // merge the update.
2338 if (!isTagStore(MemMI)) {
2339 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2340 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2341 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2342 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2343 return E;
2344 }
2345 }
2346
2347 const bool BaseRegSP = BaseReg == AArch64::SP;
2348 if (BaseRegSP && needsWinCFI(I->getMF())) {
2349 // FIXME: For now, we always block the optimization over SP in windows
2350 // targets as it requires to adjust the unwind/debug info, messing up
2351 // the unwind info can actually cause a miscompile.
2352 return E;
2353 }
2354
2355 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2356 unsigned RedZoneSize =
2357 Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
2358
2359 // Track which register units have been modified and used between the first
2360 // insn (inclusive) and the second insn.
2361 ModifiedRegUnits.clear();
2362 UsedRegUnits.clear();
2363 unsigned Count = 0;
2364 bool MemAcessBeforeSPPreInc = false;
2365 do {
2366 MBBI = prev_nodbg(MBBI, B);
2367 MachineInstr &MI = *MBBI;
2368
2369 // Don't count transient instructions towards the search limit since there
2370 // may be different numbers of them if e.g. debug information is present.
2371 if (!MI.isTransient())
2372 ++Count;
2373
2374 // If we found a match, return it.
2375 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset)) {
2376 // Check that the update value is within our red zone limit (which may be
2377 // zero).
2378 if (MemAcessBeforeSPPreInc && MBBI->getOperand(2).getImm() > RedZoneSize)
2379 return E;
2380 return MBBI;
2381 }
2382
2383 // Update the status of what the instruction clobbered and used.
2384 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2385
2386 // Otherwise, if the base register is used or modified, we have no match, so
2387 // return early.
2388 if (!ModifiedRegUnits.available(BaseReg) ||
2389 !UsedRegUnits.available(BaseReg))
2390 return E;
2391 // Keep track if we have a memory access before an SP pre-increment, in this
2392 // case we need to validate later that the update amount respects the red
2393 // zone.
2394 if (BaseRegSP && MBBI->mayLoadOrStore())
2395 MemAcessBeforeSPPreInc = true;
2396 } while (MBBI != B && Count < Limit);
2397 return E;
2398}
2399
2401AArch64LoadStoreOpt::findMatchingConstOffsetBackward(
2402 MachineBasicBlock::iterator I, unsigned Limit, unsigned &Offset) {
2403 MachineBasicBlock::iterator B = I->getParent()->begin();
2404 MachineBasicBlock::iterator E = I->getParent()->end();
2405 MachineInstr &MemMI = *I;
2407
2408 // If the load is the first instruction in the block, there's obviously
2409 // not any matching load or store.
2410 if (MBBI == B)
2411 return E;
2412
2413 // Make sure the IndexReg is killed and the shift amount is zero.
2414 // TODO: Relex this restriction to extend, simplify processing now.
2415 if (!AArch64InstrInfo::getLdStOffsetOp(MemMI).isKill() ||
2417 (AArch64InstrInfo::getLdStAmountOp(MemMI).getImm() != 0))
2418 return E;
2419
2421
2422 // Track which register units have been modified and used between the first
2423 // insn (inclusive) and the second insn.
2424 ModifiedRegUnits.clear();
2425 UsedRegUnits.clear();
2426 unsigned Count = 0;
2427 do {
2428 MBBI = prev_nodbg(MBBI, B);
2429 MachineInstr &MI = *MBBI;
2430
2431 // Don't count transient instructions towards the search limit since there
2432 // may be different numbers of them if e.g. debug information is present.
2433 if (!MI.isTransient())
2434 ++Count;
2435
2436 // If we found a match, return it.
2437 if (isMatchingMovConstInsn(*I, MI, IndexReg, Offset)) {
2438 return MBBI;
2439 }
2440
2441 // Update the status of what the instruction clobbered and used.
2442 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2443
2444 // Otherwise, if the index register is used or modified, we have no match,
2445 // so return early.
2446 if (!ModifiedRegUnits.available(IndexReg) ||
2447 !UsedRegUnits.available(IndexReg))
2448 return E;
2449
2450 } while (MBBI != B && Count < Limit);
2451 return E;
2452}
2453
2455 auto MatchBaseReg = [&](unsigned Count) {
2456 for (unsigned I = 0; I < Count; I++) {
2457 auto OpI = MI.getOperand(I);
2458 if (OpI.isReg() && OpI.getReg() != BaseReg)
2459 return false;
2460 }
2461 return true;
2462 };
2463
2464 unsigned Opc = MI.getOpcode();
2465 switch (Opc) {
2466 default:
2467 return false;
2468 case AArch64::MOVZXi:
2469 return MatchBaseReg(1);
2470 case AArch64::MOVKXi:
2471 return MatchBaseReg(2);
2472 case AArch64::ORRXrs:
2473 MachineOperand &Imm = MI.getOperand(3);
2474 // Fourth operand of ORR must be 32 which mean
2475 // 32bit symmetric constant load.
2476 // ex) renamable $x8 = ORRXrs $x8, $x8, 32
2477 if (MatchBaseReg(3) && Imm.isImm() && Imm.getImm() == 32)
2478 return true;
2479 }
2480
2481 return false;
2482}
2483
2484MachineBasicBlock::iterator AArch64LoadStoreOpt::doFoldSymmetryConstantLoad(
2486 int UpperLoadIdx, int Accumulated) {
2487 MachineBasicBlock::iterator I = MI.getIterator();
2488 MachineBasicBlock::iterator E = I->getParent()->end();
2490 MachineBasicBlock *MBB = MI.getParent();
2491
2492 if (!UpperLoadIdx) {
2493 // ORR ensures that previous instructions load lower 32-bit constants.
2494 // Remove ORR only.
2495 (*MIs.begin())->eraseFromParent();
2496 } else {
2497 // We need to remove MOV for upper of 32bit because we know these instrs
2498 // is part of symmetric constant.
2499 int Index = 0;
2500 for (auto MI = MIs.begin(); Index < UpperLoadIdx; ++MI, Index++) {
2501 (*MI)->eraseFromParent();
2502 }
2503 }
2504
2505 Register BaseReg = getLdStRegOp(MI).getReg();
2507 Register DstRegW = TRI->getSubReg(BaseReg, AArch64::sub_32);
2508 unsigned DstRegState = getRegState(MI.getOperand(0));
2510 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(AArch64::STPWi))
2511 .addReg(DstRegW, DstRegState)
2512 .addReg(DstRegW, DstRegState)
2513 .addReg(MO.getReg(), getRegState(MO))
2514 .addImm(Offset * 2)
2515 .setMemRefs(MI.memoperands())
2516 .setMIFlags(MI.getFlags());
2517 I->eraseFromParent();
2518 return NextI;
2519}
2520
2521bool AArch64LoadStoreOpt::tryFoldSymmetryConstantLoad(
2522 MachineBasicBlock::iterator &I, unsigned Limit) {
2523 MachineInstr &MI = *I;
2524 if (MI.getOpcode() != AArch64::STRXui)
2525 return false;
2526
2528 MachineBasicBlock::iterator B = I->getParent()->begin();
2529 if (MBBI == B)
2530 return false;
2531
2532 TypeSize Scale(0U, false), Width(0U, false);
2533 int64_t MinOffset, MaxOffset;
2534 if (!AArch64InstrInfo::getMemOpInfo(AArch64::STPWi, Scale, Width, MinOffset,
2535 MaxOffset))
2536 return false;
2537
2538 // We replace the STRX instruction, which stores 64 bits, with the STPW
2539 // instruction, which stores two consecutive 32 bits. Therefore, we compare
2540 // the offset range with multiplied by two.
2542 if (Offset * 2 < MinOffset || Offset * 2 > MaxOffset)
2543 return false;
2544
2545 Register BaseReg = getLdStRegOp(MI).getReg();
2546 unsigned Count = 0, UpperLoadIdx = 0;
2547 uint64_t Accumulated = 0, Mask = 0xFFFFUL;
2548 bool hasORR = false, Found = false;
2550 ModifiedRegUnits.clear();
2551 UsedRegUnits.clear();
2552 do {
2553 MBBI = prev_nodbg(MBBI, B);
2554 MachineInstr &MI = *MBBI;
2555 if (!MI.isTransient())
2556 ++Count;
2557 if (!isSymmetricLoadCandidate(MI, BaseReg)) {
2558 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2559 TRI);
2560 if (!ModifiedRegUnits.available(BaseReg) ||
2561 !UsedRegUnits.available(BaseReg))
2562 return false;
2563 continue;
2564 }
2565
2566 unsigned Opc = MI.getOpcode();
2567 if (Opc == AArch64::ORRXrs) {
2568 hasORR = true;
2569 MIs.push_back(MBBI);
2570 continue;
2571 }
2572 unsigned ValueOrder = Opc == AArch64::MOVZXi ? 1 : 2;
2573 MachineOperand Value = MI.getOperand(ValueOrder);
2574 MachineOperand Shift = MI.getOperand(ValueOrder + 1);
2575 if (!Value.isImm() || !Shift.isImm())
2576 return false;
2577
2578 uint64_t IValue = Value.getImm();
2579 uint64_t IShift = Shift.getImm();
2580 uint64_t Adder = IValue << IShift;
2581 MIs.push_back(MBBI);
2582 if (Adder >> 32)
2583 UpperLoadIdx = MIs.size();
2584
2585 Accumulated -= Accumulated & (Mask << IShift);
2586 Accumulated += Adder;
2587 if (Accumulated != 0 &&
2588 (((Accumulated >> 32) == (Accumulated & 0xffffffffULL)) ||
2589 (hasORR && (Accumulated >> 32 == 0)))) {
2590 Found = true;
2591 break;
2592 }
2593 } while (MBBI != B && Count < Limit);
2594
2595 if (Found) {
2596 I = doFoldSymmetryConstantLoad(MI, MIs, UpperLoadIdx, Accumulated);
2597 return true;
2598 }
2599
2600 return false;
2601}
2602
2603bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
2605 MachineInstr &MI = *MBBI;
2606 // If this is a volatile load, don't mess with it.
2607 if (MI.hasOrderedMemoryRef())
2608 return false;
2609
2610 if (needsWinCFI(MI.getMF()) && MI.getFlag(MachineInstr::FrameDestroy))
2611 return false;
2612
2613 // Make sure this is a reg+imm.
2614 // FIXME: It is possible to extend it to handle reg+reg cases.
2616 return false;
2617
2618 // Look backward up to LdStLimit instructions.
2620 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
2621 ++NumLoadsFromStoresPromoted;
2622 // Promote the load. Keeping the iterator straight is a
2623 // pain, so we let the merge routine tell us what the next instruction
2624 // is after it's done mucking about.
2625 MBBI = promoteLoadFromStore(MBBI, StoreI);
2626 return true;
2627 }
2628 return false;
2629}
2630
2631// Merge adjacent zero stores into a wider store.
2632bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
2634 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
2635 MachineInstr &MI = *MBBI;
2636 MachineBasicBlock::iterator E = MI.getParent()->end();
2637
2638 if (!TII->isCandidateToMergeOrPair(MI))
2639 return false;
2640
2641 // Look ahead up to LdStLimit instructions for a mergable instruction.
2642 LdStPairFlags Flags;
2644 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
2645 if (MergeMI != E) {
2646 ++NumZeroStoresPromoted;
2647
2648 // Keeping the iterator straight is a pain, so we let the merge routine tell
2649 // us what the next instruction is after it's done mucking about.
2650 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
2651 return true;
2652 }
2653 return false;
2654}
2655
2656// Find loads and stores that can be merged into a single load or store pair
2657// instruction.
2658bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
2659 MachineInstr &MI = *MBBI;
2660 MachineBasicBlock::iterator E = MI.getParent()->end();
2661
2662 if (!TII->isCandidateToMergeOrPair(MI))
2663 return false;
2664
2665 // If disable-ldp feature is opted, do not emit ldp.
2666 if (MI.mayLoad() && Subtarget->hasDisableLdp())
2667 return false;
2668
2669 // If disable-stp feature is opted, do not emit stp.
2670 if (MI.mayStore() && Subtarget->hasDisableStp())
2671 return false;
2672
2673 // Early exit if the offset is not possible to match. (6 bits of positive
2674 // range, plus allow an extra one in case we find a later insn that matches
2675 // with Offset-1)
2676 bool IsUnscaled = TII->hasUnscaledLdStOffset(MI);
2678 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
2679 // Allow one more for offset.
2680 if (Offset > 0)
2681 Offset -= OffsetStride;
2682 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
2683 return false;
2684
2685 // Look ahead up to LdStLimit instructions for a pairable instruction.
2686 LdStPairFlags Flags;
2688 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
2689 if (Paired != E) {
2690 // Keeping the iterator straight is a pain, so we let the merge routine tell
2691 // us what the next instruction is after it's done mucking about.
2692 auto Prev = std::prev(MBBI);
2693
2694 // Fetch the memoperand of the load/store that is a candidate for
2695 // combination.
2697 MI.memoperands_empty() ? nullptr : MI.memoperands().front();
2698
2699 // If a load/store arrives and ldp/stp-aligned-only feature is opted, check
2700 // that the alignment of the source pointer is at least double the alignment
2701 // of the type.
2702 if ((MI.mayLoad() && Subtarget->hasLdpAlignedOnly()) ||
2703 (MI.mayStore() && Subtarget->hasStpAlignedOnly())) {
2704 // If there is no size/align information, cancel the transformation.
2705 if (!MemOp || !MemOp->getMemoryType().isValid()) {
2706 NumFailedAlignmentCheck++;
2707 return false;
2708 }
2709
2710 // Get the needed alignments to check them if
2711 // ldp-aligned-only/stp-aligned-only features are opted.
2712 uint64_t MemAlignment = MemOp->getAlign().value();
2713 uint64_t TypeAlignment = Align(MemOp->getSize().getValue()).value();
2714
2715 if (MemAlignment < 2 * TypeAlignment) {
2716 NumFailedAlignmentCheck++;
2717 return false;
2718 }
2719 }
2720
2721 ++NumPairCreated;
2722 if (TII->hasUnscaledLdStOffset(MI))
2723 ++NumUnscaledPairCreated;
2724
2725 MBBI = mergePairedInsns(MBBI, Paired, Flags);
2726 // Collect liveness info for instructions between Prev and the new position
2727 // MBBI.
2728 for (auto I = std::next(Prev); I != MBBI; I++)
2729 updateDefinedRegisters(*I, DefinedInBB, TRI);
2730
2731 return true;
2732 }
2733 return false;
2734}
2735
2736bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
2738 MachineInstr &MI = *MBBI;
2739 MachineBasicBlock::iterator E = MI.getParent()->end();
2741
2742 // Look forward to try to form a post-index instruction. For example,
2743 // ldr x0, [x20]
2744 // add x20, x20, #32
2745 // merged into:
2746 // ldr x0, [x20], #32
2747 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
2748 if (Update != E) {
2749 // Merge the update into the ld/st.
2750 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
2751 return true;
2752 }
2753
2754 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2755 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2756 return false;
2757
2758 // Look back to try to find a pre-index instruction. For example,
2759 // add x0, x0, #8
2760 // ldr x1, [x0]
2761 // merged into:
2762 // ldr x1, [x0, #8]!
2763 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
2764 if (Update != E) {
2765 // Merge the update into the ld/st.
2766 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2767 return true;
2768 }
2769
2770 // The immediate in the load/store is scaled by the size of the memory
2771 // operation. The immediate in the add we're looking for,
2772 // however, is not, so adjust here.
2773 int UnscaledOffset =
2775
2776 // Look forward to try to find a pre-index instruction. For example,
2777 // ldr x1, [x0, #64]
2778 // add x0, x0, #64
2779 // merged into:
2780 // ldr x1, [x0, #64]!
2781 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2782 if (Update != E) {
2783 // Merge the update into the ld/st.
2784 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2785 return true;
2786 }
2787
2788 return false;
2789}
2790
2791bool AArch64LoadStoreOpt::tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI,
2792 int Scale) {
2793 MachineInstr &MI = *MBBI;
2794 MachineBasicBlock::iterator E = MI.getParent()->end();
2796
2797 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2798 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2799 return false;
2800
2801 // Look back to try to find a const offset for index LdSt instruction. For
2802 // example,
2803 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2804 // ldr x1, [x0, x8]
2805 // merged into:
2806 // add x8, x0, a * (1<<12)
2807 // ldr x1, [x8, imm12]
2808 unsigned Offset;
2809 Update = findMatchingConstOffsetBackward(MBBI, LdStConstLimit, Offset);
2810 if (Update != E && (Offset & (Scale - 1)) == 0) {
2811 // Merge the imm12 into the ld/st.
2812 MBBI = mergeConstOffsetInsn(MBBI, Update, Offset, Scale);
2813 return true;
2814 }
2815
2816 return false;
2817}
2818
2819bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
2820 bool EnableNarrowZeroStOpt) {
2821
2822 bool Modified = false;
2823 // Four tranformations to do here:
2824 // 1) Find loads that directly read from stores and promote them by
2825 // replacing with mov instructions. If the store is wider than the load,
2826 // the load will be replaced with a bitfield extract.
2827 // e.g.,
2828 // str w1, [x0, #4]
2829 // ldrh w2, [x0, #6]
2830 // ; becomes
2831 // str w1, [x0, #4]
2832 // lsr w2, w1, #16
2834 MBBI != E;) {
2835 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2836 Modified = true;
2837 else
2838 ++MBBI;
2839 }
2840 // 2) Merge adjacent zero stores into a wider store.
2841 // e.g.,
2842 // strh wzr, [x0]
2843 // strh wzr, [x0, #2]
2844 // ; becomes
2845 // str wzr, [x0]
2846 // e.g.,
2847 // str wzr, [x0]
2848 // str wzr, [x0, #4]
2849 // ; becomes
2850 // str xzr, [x0]
2851 if (EnableNarrowZeroStOpt)
2853 MBBI != E;) {
2854 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2855 Modified = true;
2856 else
2857 ++MBBI;
2858 }
2859 // 3) Find loads and stores that can be merged into a single load or store
2860 // pair instruction.
2861 // e.g.,
2862 // ldr x0, [x2]
2863 // ldr x1, [x2, #8]
2864 // ; becomes
2865 // ldp x0, x1, [x2]
2866
2868 DefinedInBB.clear();
2869 DefinedInBB.addLiveIns(MBB);
2870 }
2871
2873 MBBI != E;) {
2874 // Track currently live registers up to this point, to help with
2875 // searching for a rename register on demand.
2876 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2877 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2878 Modified = true;
2879 else
2880 ++MBBI;
2881 }
2882 // 4) Find base register updates that can be merged into the load or store
2883 // as a base-reg writeback.
2884 // e.g.,
2885 // ldr x0, [x2]
2886 // add x2, x2, #4
2887 // ; becomes
2888 // ldr x0, [x2], #4
2890 MBBI != E;) {
2891 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2892 Modified = true;
2893 else
2894 ++MBBI;
2895 }
2896
2897 // 5) Find a register assigned with a const value that can be combined with
2898 // into the load or store. e.g.,
2899 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2900 // ldr x1, [x0, x8]
2901 // ; becomes
2902 // add x8, x0, a * (1<<12)
2903 // ldr x1, [x8, imm12]
2905 MBBI != E;) {
2906 int Scale;
2907 if (isMergeableIndexLdSt(*MBBI, Scale) && tryToMergeIndexLdSt(MBBI, Scale))
2908 Modified = true;
2909 else
2910 ++MBBI;
2911 }
2912
2913 // We have an opportunity to optimize the `STRXui` instruction, which loads
2914 // the same 32-bit value into a register twice. The `STPXi` instruction allows
2915 // us to load a 32-bit value only once.
2916 // Considering :
2917 // renamable $x8 = MOVZXi 49370, 0
2918 // renamable $x8 = MOVKXi $x8, 320, 16
2919 // renamable $x8 = ORRXrs $x8, $x8, 32
2920 // STRXui killed renamable $x8, killed renamable $x0, 0
2921 // Transform :
2922 // $w8 = MOVZWi 49370, 0
2923 // $w8 = MOVKWi $w8, 320, 16
2924 // STPWi killed renamable $w8, killed renamable $w8, killed renamable $x0, 0
2926 MBBI != E;) {
2928 tryFoldSymmetryConstantLoad(MBBI, UpdateLimit))
2929 Modified = true;
2930 else
2931 ++MBBI;
2932 }
2933
2934 return Modified;
2935}
2936
2937bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2938 if (skipFunction(Fn.getFunction()))
2939 return false;
2940
2941 Subtarget = &Fn.getSubtarget<AArch64Subtarget>();
2942 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2943 TRI = Subtarget->getRegisterInfo();
2944 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2945
2946 // Resize the modified and used register unit trackers. We do this once
2947 // per function and then clear the register units each time we optimize a load
2948 // or store.
2949 ModifiedRegUnits.init(*TRI);
2950 UsedRegUnits.init(*TRI);
2951 DefinedInBB.init(*TRI);
2952
2953 bool Modified = false;
2954 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2955 for (auto &MBB : Fn) {
2956 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2957 Modified |= M;
2958 }
2959
2960 return Modified;
2961}
2962
2963// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2964// stores near one another? Note: The pre-RA instruction scheduler already has
2965// hooks to try and schedule pairable loads/stores together to improve pairing
2966// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
2967
2968// FIXME: When pairing store instructions it's very possible for this pass to
2969// hoist a store with a KILL marker above another use (without a KILL marker).
2970// The resulting IR is invalid, but nothing uses the KILL markers after this
2971// pass, so it's never caused a problem in practice.
2972
2973/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2974/// load / store optimization pass.
2976 return new AArch64LoadStoreOpt();
2977}
#define Success
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static cl::opt< bool > EnableRenaming("aarch64-load-store-renaming", cl::init(true), cl::Hidden)
static MachineOperand & getLdStRegOp(MachineInstr &MI, unsigned PairedRegOp=0)
static bool isPromotableLoadFromStore(MachineInstr &MI)
static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale, int &MinOffset, int &MaxOffset)
static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride)
static unsigned getMatchingPairOpcode(unsigned Opc)
static bool isMergeableLdStUpdate(MachineInstr &MI)
static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI, LdStPairFlags &Flags, const AArch64InstrInfo *TII)
static std::optional< MCPhysReg > tryToFindRegisterToRename(const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool needsWinCFI(const MachineFunction *MF)
static bool isSymmetricLoadCandidate(MachineInstr &MI, Register BaseReg)
static bool canRenameUntilSecondLoad(MachineInstr &FirstLoad, MachineInstr &SecondLoad, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static std::optional< MCPhysReg > findRenameRegForSameLdStRegPair(std::optional< bool > MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool mayAlias(MachineInstr &MIa, SmallVectorImpl< MachineInstr * > &MemInsns, AliasAnalysis *AA)
static cl::opt< unsigned > LdStLimit("aarch64-load-store-scan-limit", cl::init(20), cl::Hidden)
static bool canRenameMOP(const MachineOperand &MOP, const TargetRegisterInfo *TRI)
static unsigned getPreIndexedOpcode(unsigned Opc)
#define AARCH64_LOAD_STORE_OPT_NAME
static cl::opt< unsigned > UpdateLimit("aarch64-update-scan-limit", cl::init(100), cl::Hidden)
static bool isPromotableZeroStoreInst(MachineInstr &MI)
static unsigned getMatchingWideOpcode(unsigned Opc)
static unsigned getMatchingNonSExtOpcode(unsigned Opc, bool *IsValidLdStrOpc=nullptr)
static MachineBasicBlock::iterator maybeMoveCFI(MachineInstr &MI, MachineBasicBlock::iterator MaybeCFI)
static int alignTo(int Num, int PowOf2)
static bool isTagStore(const MachineInstr &MI)
static unsigned isMatchingStore(MachineInstr &LoadInst, MachineInstr &StoreInst)
static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg, const TargetRegisterInfo *TRI, unsigned Limit, std::function< bool(MachineInstr &, bool)> &Fn)
static bool isRewritableImplicitDef(unsigned Opc)
static unsigned getPostIndexedOpcode(unsigned Opc)
#define DEBUG_TYPE
static cl::opt< unsigned > LdStConstLimit("aarch64-load-store-const-scan-limit", cl::init(10), cl::Hidden)
static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst, MachineInstr &StoreInst, const AArch64InstrInfo *TII)
static bool isPreLdStPairCandidate(MachineInstr &FirstMI, MachineInstr &MI)
static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale)
static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units, const TargetRegisterInfo *TRI)
static bool canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static unsigned getBaseAddressOpcode(unsigned Opc)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:480
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t High
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, DomTreeUpdater *DTU)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static bool getMemOpInfo(unsigned Opcode, TypeSize &Scale, TypeSize &Width, int64_t &MinOffset, int64_t &MaxOffset)
Returns true if opcode Opc is a memory operation.
static const MachineOperand & getLdStOffsetOp(const MachineInstr &MI)
Returns the immediate offset operator of a load/store.
static const MachineOperand & getLdStAmountOp(const MachineInstr &MI)
Returns the shift amount operator of a load/store.
static bool isPreLdSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load/store.
static bool isPairedLdSt(const MachineInstr &MI)
Returns whether the instruction is a paired load/store.
static int getMemScale(unsigned Opc)
Scaling factor for (scaled or unscaled) load or store.
static const MachineOperand & getLdStBaseOp(const MachineInstr &MI)
Returns the base register operator of a load/store.
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
const AArch64TargetLowering * getTargetLowering() const override
unsigned getRedZoneSize(const Function &F) const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:680
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:30
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
Definition: LiveRegUnits.h:47
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
Definition: LiveRegUnits.h:116
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
Definition: LiveRegUnits.h:73
void addReg(MCPhysReg Reg)
Adds register units covered by physical register Reg.
Definition: LiveRegUnits.h:86
void removeReg(MCPhysReg Reg)
Removes all register units covered by physical register Reg.
Definition: LiveRegUnits.h:102
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
An instruction for reading from memory.
Definition: Instructions.h:174
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:759
OpType getOperation() const
Definition: MCDwarf.h:680
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
reverse_instr_iterator instr_rend()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:346
bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:685
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
Definition: MachineInstr.h:930
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setImplicit(bool Val=true)
int64_t getImm() const
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dump() const
Definition: Pass.cpp:136
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:346
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition: Value.h:74
self_iterator getIterator()
Definition: ilist_node.h:132
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Define
Register definition.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
constexpr double e
Definition: MathExtras.h:47
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< filter_iterator< ConstMIBundleOperands, bool(*)(const MachineOperand &)> > phys_regs_and_masks(const MachineInstr &MI)
Returns an iterator range over all physical register and mask operands for MI and bundled instruction...
Definition: LiveRegUnits.h:166
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createAArch64LoadStoreOptimizationPass()
createAArch64LoadStoreOptimizationPass - returns an instance of the load / store optimization pass.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
void initializeAArch64LoadStoreOptPass(PassRegistry &)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85