1 //===- X86AvoidStoreForwardingBlockis.cpp - Avoid HW Store Forward Block --===//
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 // If a load follows a store and reloads data that the store has written to
10 // memory, Intel microarchitectures can in many cases forward the data directly
11 // from the store to the load, This "store forwarding" saves cycles by enabling
12 // the load to directly obtain the data instead of accessing the data from
13 // cache or memory.
14 // A "store forward block" occurs in cases that a store cannot be forwarded to
15 // the load. The most typical case of store forward block on Intel Core
16 // microarchitecture that a small store cannot be forwarded to a large load.
17 // The estimated penalty for a store forward block is ~13 cycles.
18 //
19 // This pass tries to recognize and handle cases where "store forward block"
20 // is created by the compiler when lowering memcpy calls to a sequence
21 // of a load and a store.
22 //
23 // The pass currently only handles cases where memcpy is lowered to
24 // XMM/YMM registers, it tries to break the memcpy into smaller copies.
25 // breaking the memcpy should be possible since there is no atomicity
26 // guarantee for loads and stores to XMM/YMM.
27 //
28 // It could be better for performance to solve the problem by loading
29 // to XMM/YMM then inserting the partial store before storing back from XMM/YMM
30 // to memory, but this will result in a more conservative optimization since it
31 // requires we prove that all memory accesses between the blocking store and the
32 // load must alias/don't alias before we can move the store, whereas the
33 // transformation done here is correct regardless to other memory accesses.
34 //===----------------------------------------------------------------------===//
35 
36 #include "X86InstrInfo.h"
37 #include "X86Subtarget.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineOperand.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/MC/MCInstrDesc.h"
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "x86-avoid-SFB"
53 
54 static cl::opt<bool> DisableX86AvoidStoreForwardBlocks(
55     "x86-disable-avoid-SFB", cl::Hidden,
56     cl::desc("X86: Disable Store Forwarding Blocks fixup."), cl::init(false));
57 
58 static cl::opt<unsigned> X86AvoidSFBInspectionLimit(
59     "x86-sfb-inspection-limit",
60     cl::desc("X86: Number of instructions backward to "
61              "inspect for store forwarding blocks."),
62     cl::init(20), cl::Hidden);
63 
64 namespace {
65 
66 using DisplacementSizeMap = std::map<int64_t, unsigned>;
67 
68 class X86AvoidSFBPass : public MachineFunctionPass {
69 public:
70   static char ID;
71   X86AvoidSFBPass() : MachineFunctionPass(ID) {
72     initializeX86AvoidSFBPassPass(*PassRegistry::getPassRegistry());
73   }
74 
75   StringRef getPassName() const override {
76     return "X86 Avoid Store Forwarding Blocks";
77   }
78 
79   bool runOnMachineFunction(MachineFunction &MF) override;
80 
81   void getAnalysisUsage(AnalysisUsage &AU) const override {
82     MachineFunctionPass::getAnalysisUsage(AU);
83     AU.addRequired<AAResultsWrapperPass>();
84   }
85 
86 private:
87   MachineRegisterInfo *MRI;
88   const X86InstrInfo *TII;
89   const X86RegisterInfo *TRI;
90   SmallVector<std::pair<MachineInstr *, MachineInstr *>, 2>
91       BlockedLoadsStoresPairs;
92   SmallVector<MachineInstr *, 2> ForRemoval;
93   AliasAnalysis *AA;
94 
95   /// Returns couples of Load then Store to memory which look
96   ///  like a memcpy.
97   void findPotentiallylBlockedCopies(MachineFunction &MF);
98   /// Break the memcpy's load and store into smaller copies
99   /// such that each memory load that was blocked by a smaller store
100   /// would now be copied separately.
101   void breakBlockedCopies(MachineInstr *LoadInst, MachineInstr *StoreInst,
102                           const DisplacementSizeMap &BlockingStoresDispSizeMap);
103   /// Break a copy of size Size to smaller copies.
104   void buildCopies(int Size, MachineInstr *LoadInst, int64_t LdDispImm,
105                    MachineInstr *StoreInst, int64_t StDispImm,
106                    int64_t LMMOffset, int64_t SMMOffset);
107 
108   void buildCopy(MachineInstr *LoadInst, unsigned NLoadOpcode, int64_t LoadDisp,
109                  MachineInstr *StoreInst, unsigned NStoreOpcode,
110                  int64_t StoreDisp, unsigned Size, int64_t LMMOffset,
111                  int64_t SMMOffset);
112 
113   bool alias(const MachineMemOperand &Op1, const MachineMemOperand &Op2) const;
114 
115   unsigned getRegSizeInBytes(MachineInstr *Inst);
116 };
117 
118 } // end anonymous namespace
119 
120 char X86AvoidSFBPass::ID = 0;
121 
122 INITIALIZE_PASS_BEGIN(X86AvoidSFBPass, DEBUG_TYPE, "Machine code sinking",
123                       false, false)
124 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
125 INITIALIZE_PASS_END(X86AvoidSFBPass, DEBUG_TYPE, "Machine code sinking", false,
126                     false)
127 
128 FunctionPass *llvm::createX86AvoidStoreForwardingBlocks() {
129   return new X86AvoidSFBPass();
130 }
131 
132 static bool isXMMLoadOpcode(unsigned Opcode) {
133   return Opcode == X86::MOVUPSrm || Opcode == X86::MOVAPSrm ||
134          Opcode == X86::VMOVUPSrm || Opcode == X86::VMOVAPSrm ||
135          Opcode == X86::VMOVUPDrm || Opcode == X86::VMOVAPDrm ||
136          Opcode == X86::VMOVDQUrm || Opcode == X86::VMOVDQArm ||
137          Opcode == X86::VMOVUPSZ128rm || Opcode == X86::VMOVAPSZ128rm ||
138          Opcode == X86::VMOVUPDZ128rm || Opcode == X86::VMOVAPDZ128rm ||
139          Opcode == X86::VMOVDQU64Z128rm || Opcode == X86::VMOVDQA64Z128rm ||
140          Opcode == X86::VMOVDQU32Z128rm || Opcode == X86::VMOVDQA32Z128rm;
141 }
142 static bool isYMMLoadOpcode(unsigned Opcode) {
143   return Opcode == X86::VMOVUPSYrm || Opcode == X86::VMOVAPSYrm ||
144          Opcode == X86::VMOVUPDYrm || Opcode == X86::VMOVAPDYrm ||
145          Opcode == X86::VMOVDQUYrm || Opcode == X86::VMOVDQAYrm ||
146          Opcode == X86::VMOVUPSZ256rm || Opcode == X86::VMOVAPSZ256rm ||
147          Opcode == X86::VMOVUPDZ256rm || Opcode == X86::VMOVAPDZ256rm ||
148          Opcode == X86::VMOVDQU64Z256rm || Opcode == X86::VMOVDQA64Z256rm ||
149          Opcode == X86::VMOVDQU32Z256rm || Opcode == X86::VMOVDQA32Z256rm;
150 }
151 
152 static bool isPotentialBlockedMemCpyLd(unsigned Opcode) {
153   return isXMMLoadOpcode(Opcode) || isYMMLoadOpcode(Opcode);
154 }
155 
156 static bool isPotentialBlockedMemCpyPair(int LdOpcode, int StOpcode) {
157   switch (LdOpcode) {
158   case X86::MOVUPSrm:
159   case X86::MOVAPSrm:
160     return StOpcode == X86::MOVUPSmr || StOpcode == X86::MOVAPSmr;
161   case X86::VMOVUPSrm:
162   case X86::VMOVAPSrm:
163     return StOpcode == X86::VMOVUPSmr || StOpcode == X86::VMOVAPSmr;
164   case X86::VMOVUPDrm:
165   case X86::VMOVAPDrm:
166     return StOpcode == X86::VMOVUPDmr || StOpcode == X86::VMOVAPDmr;
167   case X86::VMOVDQUrm:
168   case X86::VMOVDQArm:
169     return StOpcode == X86::VMOVDQUmr || StOpcode == X86::VMOVDQAmr;
170   case X86::VMOVUPSZ128rm:
171   case X86::VMOVAPSZ128rm:
172     return StOpcode == X86::VMOVUPSZ128mr || StOpcode == X86::VMOVAPSZ128mr;
173   case X86::VMOVUPDZ128rm:
174   case X86::VMOVAPDZ128rm:
175     return StOpcode == X86::VMOVUPDZ128mr || StOpcode == X86::VMOVAPDZ128mr;
176   case X86::VMOVUPSYrm:
177   case X86::VMOVAPSYrm:
178     return StOpcode == X86::VMOVUPSYmr || StOpcode == X86::VMOVAPSYmr;
179   case X86::VMOVUPDYrm:
180   case X86::VMOVAPDYrm:
181     return StOpcode == X86::VMOVUPDYmr || StOpcode == X86::VMOVAPDYmr;
182   case X86::VMOVDQUYrm:
183   case X86::VMOVDQAYrm:
184     return StOpcode == X86::VMOVDQUYmr || StOpcode == X86::VMOVDQAYmr;
185   case X86::VMOVUPSZ256rm:
186   case X86::VMOVAPSZ256rm:
187     return StOpcode == X86::VMOVUPSZ256mr || StOpcode == X86::VMOVAPSZ256mr;
188   case X86::VMOVUPDZ256rm:
189   case X86::VMOVAPDZ256rm:
190     return StOpcode == X86::VMOVUPDZ256mr || StOpcode == X86::VMOVAPDZ256mr;
191   case X86::VMOVDQU64Z128rm:
192   case X86::VMOVDQA64Z128rm:
193     return StOpcode == X86::VMOVDQU64Z128mr || StOpcode == X86::VMOVDQA64Z128mr;
194   case X86::VMOVDQU32Z128rm:
195   case X86::VMOVDQA32Z128rm:
196     return StOpcode == X86::VMOVDQU32Z128mr || StOpcode == X86::VMOVDQA32Z128mr;
197   case X86::VMOVDQU64Z256rm:
198   case X86::VMOVDQA64Z256rm:
199     return StOpcode == X86::VMOVDQU64Z256mr || StOpcode == X86::VMOVDQA64Z256mr;
200   case X86::VMOVDQU32Z256rm:
201   case X86::VMOVDQA32Z256rm:
202     return StOpcode == X86::VMOVDQU32Z256mr || StOpcode == X86::VMOVDQA32Z256mr;
203   default:
204     return false;
205   }
206 }
207 
208 static bool isPotentialBlockingStoreInst(int Opcode, int LoadOpcode) {
209   bool PBlock = false;
210   PBlock |= Opcode == X86::MOV64mr || Opcode == X86::MOV64mi32 ||
211             Opcode == X86::MOV32mr || Opcode == X86::MOV32mi ||
212             Opcode == X86::MOV16mr || Opcode == X86::MOV16mi ||
213             Opcode == X86::MOV8mr || Opcode == X86::MOV8mi;
214   if (isYMMLoadOpcode(LoadOpcode))
215     PBlock |= Opcode == X86::VMOVUPSmr || Opcode == X86::VMOVAPSmr ||
216               Opcode == X86::VMOVUPDmr || Opcode == X86::VMOVAPDmr ||
217               Opcode == X86::VMOVDQUmr || Opcode == X86::VMOVDQAmr ||
218               Opcode == X86::VMOVUPSZ128mr || Opcode == X86::VMOVAPSZ128mr ||
219               Opcode == X86::VMOVUPDZ128mr || Opcode == X86::VMOVAPDZ128mr ||
220               Opcode == X86::VMOVDQU64Z128mr ||
221               Opcode == X86::VMOVDQA64Z128mr ||
222               Opcode == X86::VMOVDQU32Z128mr || Opcode == X86::VMOVDQA32Z128mr;
223   return PBlock;
224 }
225 
226 static const int MOV128SZ = 16;
227 static const int MOV64SZ = 8;
228 static const int MOV32SZ = 4;
229 static const int MOV16SZ = 2;
230 static const int MOV8SZ = 1;
231 
232 static unsigned getYMMtoXMMLoadOpcode(unsigned LoadOpcode) {
233   switch (LoadOpcode) {
234   case X86::VMOVUPSYrm:
235   case X86::VMOVAPSYrm:
236     return X86::VMOVUPSrm;
237   case X86::VMOVUPDYrm:
238   case X86::VMOVAPDYrm:
239     return X86::VMOVUPDrm;
240   case X86::VMOVDQUYrm:
241   case X86::VMOVDQAYrm:
242     return X86::VMOVDQUrm;
243   case X86::VMOVUPSZ256rm:
244   case X86::VMOVAPSZ256rm:
245     return X86::VMOVUPSZ128rm;
246   case X86::VMOVUPDZ256rm:
247   case X86::VMOVAPDZ256rm:
248     return X86::VMOVUPDZ128rm;
249   case X86::VMOVDQU64Z256rm:
250   case X86::VMOVDQA64Z256rm:
251     return X86::VMOVDQU64Z128rm;
252   case X86::VMOVDQU32Z256rm:
253   case X86::VMOVDQA32Z256rm:
254     return X86::VMOVDQU32Z128rm;
255   default:
256     llvm_unreachable("Unexpected Load Instruction Opcode");
257   }
258   return 0;
259 }
260 
261 static unsigned getYMMtoXMMStoreOpcode(unsigned StoreOpcode) {
262   switch (StoreOpcode) {
263   case X86::VMOVUPSYmr:
264   case X86::VMOVAPSYmr:
265     return X86::VMOVUPSmr;
266   case X86::VMOVUPDYmr:
267   case X86::VMOVAPDYmr:
268     return X86::VMOVUPDmr;
269   case X86::VMOVDQUYmr:
270   case X86::VMOVDQAYmr:
271     return X86::VMOVDQUmr;
272   case X86::VMOVUPSZ256mr:
273   case X86::VMOVAPSZ256mr:
274     return X86::VMOVUPSZ128mr;
275   case X86::VMOVUPDZ256mr:
276   case X86::VMOVAPDZ256mr:
277     return X86::VMOVUPDZ128mr;
278   case X86::VMOVDQU64Z256mr:
279   case X86::VMOVDQA64Z256mr:
280     return X86::VMOVDQU64Z128mr;
281   case X86::VMOVDQU32Z256mr:
282   case X86::VMOVDQA32Z256mr:
283     return X86::VMOVDQU32Z128mr;
284   default:
285     llvm_unreachable("Unexpected Load Instruction Opcode");
286   }
287   return 0;
288 }
289 
290 static int getAddrOffset(MachineInstr *MI) {
291   const MCInstrDesc &Descl = MI->getDesc();
292   int AddrOffset = X86II::getMemoryOperandNo(Descl.TSFlags);
293   assert(AddrOffset != -1 && "Expected Memory Operand");
294   AddrOffset += X86II::getOperandBias(Descl);
295   return AddrOffset;
296 }
297 
298 static MachineOperand &getBaseOperand(MachineInstr *MI) {
299   int AddrOffset = getAddrOffset(MI);
300   return MI->getOperand(AddrOffset + X86::AddrBaseReg);
301 }
302 
303 static MachineOperand &getDispOperand(MachineInstr *MI) {
304   int AddrOffset = getAddrOffset(MI);
305   return MI->getOperand(AddrOffset + X86::AddrDisp);
306 }
307 
308 // Relevant addressing modes contain only base register and immediate
309 // displacement or frameindex and immediate displacement.
310 // TODO: Consider expanding to other addressing modes in the future
311 static bool isRelevantAddressingMode(MachineInstr *MI) {
312   int AddrOffset = getAddrOffset(MI);
313   MachineOperand &Base = getBaseOperand(MI);
314   MachineOperand &Disp = getDispOperand(MI);
315   MachineOperand &Scale = MI->getOperand(AddrOffset + X86::AddrScaleAmt);
316   MachineOperand &Index = MI->getOperand(AddrOffset + X86::AddrIndexReg);
317   MachineOperand &Segment = MI->getOperand(AddrOffset + X86::AddrSegmentReg);
318 
319   if (!((Base.isReg() && Base.getReg() != X86::NoRegister) || Base.isFI()))
320     return false;
321   if (!Disp.isImm())
322     return false;
323   if (Scale.getImm() != 1)
324     return false;
325   if (!(Index.isReg() && Index.getReg() == X86::NoRegister))
326     return false;
327   if (!(Segment.isReg() && Segment.getReg() == X86::NoRegister))
328     return false;
329   return true;
330 }
331 
332 // Collect potentially blocking stores.
333 // Limit the number of instructions backwards we want to inspect
334 // since the effect of store block won't be visible if the store
335 // and load instructions have enough instructions in between to
336 // keep the core busy.
337 static SmallVector<MachineInstr *, 2>
338 findPotentialBlockers(MachineInstr *LoadInst) {
339   SmallVector<MachineInstr *, 2> PotentialBlockers;
340   unsigned BlockCount = 0;
341   const unsigned InspectionLimit = X86AvoidSFBInspectionLimit;
342   for (auto PBInst = std::next(MachineBasicBlock::reverse_iterator(LoadInst)),
343             E = LoadInst->getParent()->rend();
344        PBInst != E; ++PBInst) {
345     BlockCount++;
346     if (BlockCount >= InspectionLimit)
347       break;
348     MachineInstr &MI = *PBInst;
349     if (MI.getDesc().isCall())
350       return PotentialBlockers;
351     PotentialBlockers.push_back(&MI);
352   }
353   // If we didn't get to the instructions limit try predecessing blocks.
354   // Ideally we should traverse the predecessor blocks in depth with some
355   // coloring algorithm, but for now let's just look at the first order
356   // predecessors.
357   if (BlockCount < InspectionLimit) {
358     MachineBasicBlock *MBB = LoadInst->getParent();
359     int LimitLeft = InspectionLimit - BlockCount;
360     for (MachineBasicBlock::pred_iterator PB = MBB->pred_begin(),
361                                           PE = MBB->pred_end();
362          PB != PE; ++PB) {
363       MachineBasicBlock *PMBB = *PB;
364       int PredCount = 0;
365       for (MachineBasicBlock::reverse_iterator PBInst = PMBB->rbegin(),
366                                                PME = PMBB->rend();
367            PBInst != PME; ++PBInst) {
368         PredCount++;
369         if (PredCount >= LimitLeft)
370           break;
371         if (PBInst->getDesc().isCall())
372           break;
373         PotentialBlockers.push_back(&*PBInst);
374       }
375     }
376   }
377   return PotentialBlockers;
378 }
379 
380 void X86AvoidSFBPass::buildCopy(MachineInstr *LoadInst, unsigned NLoadOpcode,
381                                 int64_t LoadDisp, MachineInstr *StoreInst,
382                                 unsigned NStoreOpcode, int64_t StoreDisp,
383                                 unsigned Size, int64_t LMMOffset,
384                                 int64_t SMMOffset) {
385   MachineOperand &LoadBase = getBaseOperand(LoadInst);
386   MachineOperand &StoreBase = getBaseOperand(StoreInst);
387   MachineBasicBlock *MBB = LoadInst->getParent();
388   MachineMemOperand *LMMO = *LoadInst->memoperands_begin();
389   MachineMemOperand *SMMO = *StoreInst->memoperands_begin();
390 
391   unsigned Reg1 = MRI->createVirtualRegister(
392       TII->getRegClass(TII->get(NLoadOpcode), 0, TRI, *(MBB->getParent())));
393   MachineInstr *NewLoad =
394       BuildMI(*MBB, LoadInst, LoadInst->getDebugLoc(), TII->get(NLoadOpcode),
395               Reg1)
396           .add(LoadBase)
397           .addImm(1)
398           .addReg(X86::NoRegister)
399           .addImm(LoadDisp)
400           .addReg(X86::NoRegister)
401           .addMemOperand(
402               MBB->getParent()->getMachineMemOperand(LMMO, LMMOffset, Size));
403   if (LoadBase.isReg())
404     getBaseOperand(NewLoad).setIsKill(false);
405   LLVM_DEBUG(NewLoad->dump());
406   // If the load and store are consecutive, use the loadInst location to
407   // reduce register pressure.
408   MachineInstr *StInst = StoreInst;
409   if (StoreInst->getPrevNode() == LoadInst)
410     StInst = LoadInst;
411   MachineInstr *NewStore =
412       BuildMI(*MBB, StInst, StInst->getDebugLoc(), TII->get(NStoreOpcode))
413           .add(StoreBase)
414           .addImm(1)
415           .addReg(X86::NoRegister)
416           .addImm(StoreDisp)
417           .addReg(X86::NoRegister)
418           .addReg(Reg1)
419           .addMemOperand(
420               MBB->getParent()->getMachineMemOperand(SMMO, SMMOffset, Size));
421   if (StoreBase.isReg())
422     getBaseOperand(NewStore).setIsKill(false);
423   MachineOperand &StoreSrcVReg = StoreInst->getOperand(X86::AddrNumOperands);
424   assert(StoreSrcVReg.isReg() && "Expected virtual register");
425   NewStore->getOperand(X86::AddrNumOperands).setIsKill(StoreSrcVReg.isKill());
426   LLVM_DEBUG(NewStore->dump());
427 }
428 
429 void X86AvoidSFBPass::buildCopies(int Size, MachineInstr *LoadInst,
430                                   int64_t LdDispImm, MachineInstr *StoreInst,
431                                   int64_t StDispImm, int64_t LMMOffset,
432                                   int64_t SMMOffset) {
433   int LdDisp = LdDispImm;
434   int StDisp = StDispImm;
435   while (Size > 0) {
436     if ((Size - MOV128SZ >= 0) && isYMMLoadOpcode(LoadInst->getOpcode())) {
437       Size = Size - MOV128SZ;
438       buildCopy(LoadInst, getYMMtoXMMLoadOpcode(LoadInst->getOpcode()), LdDisp,
439                 StoreInst, getYMMtoXMMStoreOpcode(StoreInst->getOpcode()),
440                 StDisp, MOV128SZ, LMMOffset, SMMOffset);
441       LdDisp += MOV128SZ;
442       StDisp += MOV128SZ;
443       LMMOffset += MOV128SZ;
444       SMMOffset += MOV128SZ;
445       continue;
446     }
447     if (Size - MOV64SZ >= 0) {
448       Size = Size - MOV64SZ;
449       buildCopy(LoadInst, X86::MOV64rm, LdDisp, StoreInst, X86::MOV64mr, StDisp,
450                 MOV64SZ, LMMOffset, SMMOffset);
451       LdDisp += MOV64SZ;
452       StDisp += MOV64SZ;
453       LMMOffset += MOV64SZ;
454       SMMOffset += MOV64SZ;
455       continue;
456     }
457     if (Size - MOV32SZ >= 0) {
458       Size = Size - MOV32SZ;
459       buildCopy(LoadInst, X86::MOV32rm, LdDisp, StoreInst, X86::MOV32mr, StDisp,
460                 MOV32SZ, LMMOffset, SMMOffset);
461       LdDisp += MOV32SZ;
462       StDisp += MOV32SZ;
463       LMMOffset += MOV32SZ;
464       SMMOffset += MOV32SZ;
465       continue;
466     }
467     if (Size - MOV16SZ >= 0) {
468       Size = Size - MOV16SZ;
469       buildCopy(LoadInst, X86::MOV16rm, LdDisp, StoreInst, X86::MOV16mr, StDisp,
470                 MOV16SZ, LMMOffset, SMMOffset);
471       LdDisp += MOV16SZ;
472       StDisp += MOV16SZ;
473       LMMOffset += MOV16SZ;
474       SMMOffset += MOV16SZ;
475       continue;
476     }
477     if (Size - MOV8SZ >= 0) {
478       Size = Size - MOV8SZ;
479       buildCopy(LoadInst, X86::MOV8rm, LdDisp, StoreInst, X86::MOV8mr, StDisp,
480                 MOV8SZ, LMMOffset, SMMOffset);
481       LdDisp += MOV8SZ;
482       StDisp += MOV8SZ;
483       LMMOffset += MOV8SZ;
484       SMMOffset += MOV8SZ;
485       continue;
486     }
487   }
488   assert(Size == 0 && "Wrong size division");
489 }
490 
491 static void updateKillStatus(MachineInstr *LoadInst, MachineInstr *StoreInst) {
492   MachineOperand &LoadBase = getBaseOperand(LoadInst);
493   MachineOperand &StoreBase = getBaseOperand(StoreInst);
494   if (LoadBase.isReg()) {
495     MachineInstr *LastLoad = LoadInst->getPrevNode();
496     // If the original load and store to xmm/ymm were consecutive
497     // then the partial copies were also created in
498     // a consecutive order to reduce register pressure,
499     // and the location of the last load is before the last store.
500     if (StoreInst->getPrevNode() == LoadInst)
501       LastLoad = LoadInst->getPrevNode()->getPrevNode();
502     getBaseOperand(LastLoad).setIsKill(LoadBase.isKill());
503   }
504   if (StoreBase.isReg()) {
505     MachineInstr *StInst = StoreInst;
506     if (StoreInst->getPrevNode() == LoadInst)
507       StInst = LoadInst;
508     getBaseOperand(StInst->getPrevNode()).setIsKill(StoreBase.isKill());
509   }
510 }
511 
512 bool X86AvoidSFBPass::alias(const MachineMemOperand &Op1,
513                             const MachineMemOperand &Op2) const {
514   if (!Op1.getValue() || !Op2.getValue())
515     return true;
516 
517   int64_t MinOffset = std::min(Op1.getOffset(), Op2.getOffset());
518   int64_t Overlapa = Op1.getSize() + Op1.getOffset() - MinOffset;
519   int64_t Overlapb = Op2.getSize() + Op2.getOffset() - MinOffset;
520 
521   AliasResult AAResult =
522       AA->alias(MemoryLocation(Op1.getValue(), Overlapa, Op1.getAAInfo()),
523                 MemoryLocation(Op2.getValue(), Overlapb, Op2.getAAInfo()));
524   return AAResult != NoAlias;
525 }
526 
527 void X86AvoidSFBPass::findPotentiallylBlockedCopies(MachineFunction &MF) {
528   for (auto &MBB : MF)
529     for (auto &MI : MBB) {
530       if (!isPotentialBlockedMemCpyLd(MI.getOpcode()))
531         continue;
532       int DefVR = MI.getOperand(0).getReg();
533       if (!MRI->hasOneUse(DefVR))
534         continue;
535       for (auto UI = MRI->use_nodbg_begin(DefVR), UE = MRI->use_nodbg_end();
536            UI != UE;) {
537         MachineOperand &StoreMO = *UI++;
538         MachineInstr &StoreMI = *StoreMO.getParent();
539         // Skip cases where the memcpy may overlap.
540         if (StoreMI.getParent() == MI.getParent() &&
541             isPotentialBlockedMemCpyPair(MI.getOpcode(), StoreMI.getOpcode()) &&
542             isRelevantAddressingMode(&MI) &&
543             isRelevantAddressingMode(&StoreMI)) {
544           assert(MI.hasOneMemOperand() &&
545                  "Expected one memory operand for load instruction");
546           assert(StoreMI.hasOneMemOperand() &&
547                  "Expected one memory operand for store instruction");
548           if (!alias(**MI.memoperands_begin(), **StoreMI.memoperands_begin()))
549             BlockedLoadsStoresPairs.push_back(std::make_pair(&MI, &StoreMI));
550         }
551       }
552     }
553 }
554 
555 unsigned X86AvoidSFBPass::getRegSizeInBytes(MachineInstr *LoadInst) {
556   auto TRC = TII->getRegClass(TII->get(LoadInst->getOpcode()), 0, TRI,
557                               *LoadInst->getParent()->getParent());
558   return TRI->getRegSizeInBits(*TRC) / 8;
559 }
560 
561 void X86AvoidSFBPass::breakBlockedCopies(
562     MachineInstr *LoadInst, MachineInstr *StoreInst,
563     const DisplacementSizeMap &BlockingStoresDispSizeMap) {
564   int64_t LdDispImm = getDispOperand(LoadInst).getImm();
565   int64_t StDispImm = getDispOperand(StoreInst).getImm();
566   int64_t LMMOffset = 0;
567   int64_t SMMOffset = 0;
568 
569   int64_t LdDisp1 = LdDispImm;
570   int64_t LdDisp2 = 0;
571   int64_t StDisp1 = StDispImm;
572   int64_t StDisp2 = 0;
573   unsigned Size1 = 0;
574   unsigned Size2 = 0;
575   int64_t LdStDelta = StDispImm - LdDispImm;
576 
577   for (auto DispSizePair : BlockingStoresDispSizeMap) {
578     LdDisp2 = DispSizePair.first;
579     StDisp2 = DispSizePair.first + LdStDelta;
580     Size2 = DispSizePair.second;
581     // Avoid copying overlapping areas.
582     if (LdDisp2 < LdDisp1) {
583       int OverlapDelta = LdDisp1 - LdDisp2;
584       LdDisp2 += OverlapDelta;
585       StDisp2 += OverlapDelta;
586       Size2 -= OverlapDelta;
587     }
588     Size1 = LdDisp2 - LdDisp1;
589 
590     // Build a copy for the point until the current blocking store's
591     // displacement.
592     buildCopies(Size1, LoadInst, LdDisp1, StoreInst, StDisp1, LMMOffset,
593                 SMMOffset);
594     // Build a copy for the current blocking store.
595     buildCopies(Size2, LoadInst, LdDisp2, StoreInst, StDisp2, LMMOffset + Size1,
596                 SMMOffset + Size1);
597     LdDisp1 = LdDisp2 + Size2;
598     StDisp1 = StDisp2 + Size2;
599     LMMOffset += Size1 + Size2;
600     SMMOffset += Size1 + Size2;
601   }
602   unsigned Size3 = (LdDispImm + getRegSizeInBytes(LoadInst)) - LdDisp1;
603   buildCopies(Size3, LoadInst, LdDisp1, StoreInst, StDisp1, LMMOffset,
604               LMMOffset);
605 }
606 
607 static bool hasSameBaseOpValue(MachineInstr *LoadInst,
608                                MachineInstr *StoreInst) {
609   MachineOperand &LoadBase = getBaseOperand(LoadInst);
610   MachineOperand &StoreBase = getBaseOperand(StoreInst);
611   if (LoadBase.isReg() != StoreBase.isReg())
612     return false;
613   if (LoadBase.isReg())
614     return LoadBase.getReg() == StoreBase.getReg();
615   return LoadBase.getIndex() == StoreBase.getIndex();
616 }
617 
618 static bool isBlockingStore(int64_t LoadDispImm, unsigned LoadSize,
619                             int64_t StoreDispImm, unsigned StoreSize) {
620   return ((StoreDispImm >= LoadDispImm) &&
621           (StoreDispImm <= LoadDispImm + (LoadSize - StoreSize)));
622 }
623 
624 // Keep track of all stores blocking a load
625 static void
626 updateBlockingStoresDispSizeMap(DisplacementSizeMap &BlockingStoresDispSizeMap,
627                                 int64_t DispImm, unsigned Size) {
628   if (BlockingStoresDispSizeMap.count(DispImm)) {
629     // Choose the smallest blocking store starting at this displacement.
630     if (BlockingStoresDispSizeMap[DispImm] > Size)
631       BlockingStoresDispSizeMap[DispImm] = Size;
632 
633   } else
634     BlockingStoresDispSizeMap[DispImm] = Size;
635 }
636 
637 // Remove blocking stores contained in each other.
638 static void
639 removeRedundantBlockingStores(DisplacementSizeMap &BlockingStoresDispSizeMap) {
640   if (BlockingStoresDispSizeMap.size() <= 1)
641     return;
642 
643   SmallVector<std::pair<int64_t, unsigned>, 0> DispSizeStack;
644   for (auto DispSizePair : BlockingStoresDispSizeMap) {
645     int64_t CurrDisp = DispSizePair.first;
646     unsigned CurrSize = DispSizePair.second;
647     while (DispSizeStack.size()) {
648       int64_t PrevDisp = DispSizeStack.back().first;
649       unsigned PrevSize = DispSizeStack.back().second;
650       if (CurrDisp + CurrSize > PrevDisp + PrevSize)
651         break;
652       DispSizeStack.pop_back();
653     }
654     DispSizeStack.push_back(DispSizePair);
655   }
656   BlockingStoresDispSizeMap.clear();
657   for (auto Disp : DispSizeStack)
658     BlockingStoresDispSizeMap.insert(Disp);
659 }
660 
661 bool X86AvoidSFBPass::runOnMachineFunction(MachineFunction &MF) {
662   bool Changed = false;
663 
664   if (DisableX86AvoidStoreForwardBlocks || skipFunction(MF.getFunction()) ||
665       !MF.getSubtarget<X86Subtarget>().is64Bit())
666     return false;
667 
668   MRI = &MF.getRegInfo();
669   assert(MRI->isSSA() && "Expected MIR to be in SSA form");
670   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
671   TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
672   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
673   LLVM_DEBUG(dbgs() << "Start X86AvoidStoreForwardBlocks\n";);
674   // Look for a load then a store to XMM/YMM which look like a memcpy
675   findPotentiallylBlockedCopies(MF);
676 
677   for (auto LoadStoreInstPair : BlockedLoadsStoresPairs) {
678     MachineInstr *LoadInst = LoadStoreInstPair.first;
679     int64_t LdDispImm = getDispOperand(LoadInst).getImm();
680     DisplacementSizeMap BlockingStoresDispSizeMap;
681 
682     SmallVector<MachineInstr *, 2> PotentialBlockers =
683         findPotentialBlockers(LoadInst);
684     for (auto PBInst : PotentialBlockers) {
685       if (!isPotentialBlockingStoreInst(PBInst->getOpcode(),
686                                         LoadInst->getOpcode()) ||
687           !isRelevantAddressingMode(PBInst))
688         continue;
689       int64_t PBstDispImm = getDispOperand(PBInst).getImm();
690       assert(PBInst->hasOneMemOperand() && "Expected One Memory Operand");
691       unsigned PBstSize = (*PBInst->memoperands_begin())->getSize();
692       // This check doesn't cover all cases, but it will suffice for now.
693       // TODO: take branch probability into consideration, if the blocking
694       // store is in an unreached block, breaking the memcopy could lose
695       // performance.
696       if (hasSameBaseOpValue(LoadInst, PBInst) &&
697           isBlockingStore(LdDispImm, getRegSizeInBytes(LoadInst), PBstDispImm,
698                           PBstSize))
699         updateBlockingStoresDispSizeMap(BlockingStoresDispSizeMap, PBstDispImm,
700                                         PBstSize);
701     }
702 
703     if (BlockingStoresDispSizeMap.empty())
704       continue;
705 
706     // We found a store forward block, break the memcpy's load and store
707     // into smaller copies such that each smaller store that was causing
708     // a store block would now be copied separately.
709     MachineInstr *StoreInst = LoadStoreInstPair.second;
710     LLVM_DEBUG(dbgs() << "Blocked load and store instructions: \n");
711     LLVM_DEBUG(LoadInst->dump());
712     LLVM_DEBUG(StoreInst->dump());
713     LLVM_DEBUG(dbgs() << "Replaced with:\n");
714     removeRedundantBlockingStores(BlockingStoresDispSizeMap);
715     breakBlockedCopies(LoadInst, StoreInst, BlockingStoresDispSizeMap);
716     updateKillStatus(LoadInst, StoreInst);
717     ForRemoval.push_back(LoadInst);
718     ForRemoval.push_back(StoreInst);
719   }
720   for (auto RemovedInst : ForRemoval) {
721     RemovedInst->eraseFromParent();
722   }
723   ForRemoval.clear();
724   BlockedLoadsStoresPairs.clear();
725   LLVM_DEBUG(dbgs() << "End X86AvoidStoreForwardBlocks\n";);
726 
727   return Changed;
728 }
729