1 //===- SIMemoryLegalizer.cpp ----------------------------------------------===//
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 /// \file
10 /// Memory legalizer - implements memory model. More information can be
11 /// found here:
12 ///   http://llvm.org/docs/AMDGPUUsage.html#memory-model
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPU.h"
17 #include "AMDGPUMachineModuleInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "llvm/ADT/BitmaskEnum.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/IR/DebugLoc.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/MC/MCInstrDesc.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/AtomicOrdering.h"
40 #include "llvm/Support/MathExtras.h"
41 #include <cassert>
42 #include <list>
43 
44 using namespace llvm;
45 using namespace llvm::AMDGPU;
46 
47 #define DEBUG_TYPE "si-memory-legalizer"
48 #define PASS_NAME "SI Memory Legalizer"
49 
50 static cl::opt<bool> AmdgcnSkipCacheInvalidations(
51     "amdgcn-skip-cache-invalidations", cl::init(false), cl::Hidden,
52     cl::desc("Use this to skip inserting cache invalidating instructions."));
53 
54 namespace {
55 
56 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
57 
58 /// Memory operation flags. Can be ORed together.
59 enum class SIMemOp {
60   NONE = 0u,
61   LOAD = 1u << 0,
62   STORE = 1u << 1,
63   LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ STORE)
64 };
65 
66 /// Position to insert a new instruction relative to an existing
67 /// instruction.
68 enum class Position {
69   BEFORE,
70   AFTER
71 };
72 
73 /// The atomic synchronization scopes supported by the AMDGPU target.
74 enum class SIAtomicScope {
75   NONE,
76   SINGLETHREAD,
77   WAVEFRONT,
78   WORKGROUP,
79   AGENT,
80   SYSTEM
81 };
82 
83 /// The distinct address spaces supported by the AMDGPU target for
84 /// atomic memory operation. Can be ORed toether.
85 enum class SIAtomicAddrSpace {
86   NONE = 0u,
87   GLOBAL = 1u << 0,
88   LDS = 1u << 1,
89   SCRATCH = 1u << 2,
90   GDS = 1u << 3,
91   OTHER = 1u << 4,
92 
93   /// The address spaces that can be accessed by a FLAT instruction.
94   FLAT = GLOBAL | LDS | SCRATCH,
95 
96   /// The address spaces that support atomic instructions.
97   ATOMIC = GLOBAL | LDS | SCRATCH | GDS,
98 
99   /// All address spaces.
100   ALL = GLOBAL | LDS | SCRATCH | GDS | OTHER,
101 
102   LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ ALL)
103 };
104 
105 /// Sets named bit \p BitName to "true" if present in instruction \p MI.
106 /// \returns Returns true if \p MI is modified, false otherwise.
107 template <uint16_t BitName>
108 bool enableNamedBit(const MachineBasicBlock::iterator &MI) {
109   int BitIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(), BitName);
110   if (BitIdx == -1)
111     return false;
112 
113   MachineOperand &Bit = MI->getOperand(BitIdx);
114   if (Bit.getImm() != 0)
115     return false;
116 
117   Bit.setImm(1);
118   return true;
119 }
120 
121 class SIMemOpInfo final {
122 private:
123 
124   friend class SIMemOpAccess;
125 
126   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
127   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
128   SIAtomicScope Scope = SIAtomicScope::SYSTEM;
129   SIAtomicAddrSpace OrderingAddrSpace = SIAtomicAddrSpace::NONE;
130   SIAtomicAddrSpace InstrAddrSpace = SIAtomicAddrSpace::NONE;
131   bool IsCrossAddressSpaceOrdering = false;
132   bool IsNonTemporal = false;
133 
134   SIMemOpInfo(AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent,
135               SIAtomicScope Scope = SIAtomicScope::SYSTEM,
136               SIAtomicAddrSpace OrderingAddrSpace = SIAtomicAddrSpace::ATOMIC,
137               SIAtomicAddrSpace InstrAddrSpace = SIAtomicAddrSpace::ALL,
138               bool IsCrossAddressSpaceOrdering = true,
139               AtomicOrdering FailureOrdering =
140                 AtomicOrdering::SequentiallyConsistent,
141               bool IsNonTemporal = false)
142     : Ordering(Ordering), FailureOrdering(FailureOrdering),
143       Scope(Scope), OrderingAddrSpace(OrderingAddrSpace),
144       InstrAddrSpace(InstrAddrSpace),
145       IsCrossAddressSpaceOrdering(IsCrossAddressSpaceOrdering),
146       IsNonTemporal(IsNonTemporal) {
147     // There is also no cross address space ordering if the ordering
148     // address space is the same as the instruction address space and
149     // only contains a single address space.
150     if ((OrderingAddrSpace == InstrAddrSpace) &&
151         isPowerOf2_32(uint32_t(InstrAddrSpace)))
152       this->IsCrossAddressSpaceOrdering = false;
153   }
154 
155 public:
156   /// \returns Atomic synchronization scope of the machine instruction used to
157   /// create this SIMemOpInfo.
158   SIAtomicScope getScope() const {
159     return Scope;
160   }
161 
162   /// \returns Ordering constraint of the machine instruction used to
163   /// create this SIMemOpInfo.
164   AtomicOrdering getOrdering() const {
165     return Ordering;
166   }
167 
168   /// \returns Failure ordering constraint of the machine instruction used to
169   /// create this SIMemOpInfo.
170   AtomicOrdering getFailureOrdering() const {
171     return FailureOrdering;
172   }
173 
174   /// \returns The address spaces be accessed by the machine
175   /// instruction used to create this SiMemOpInfo.
176   SIAtomicAddrSpace getInstrAddrSpace() const {
177     return InstrAddrSpace;
178   }
179 
180   /// \returns The address spaces that must be ordered by the machine
181   /// instruction used to create this SiMemOpInfo.
182   SIAtomicAddrSpace getOrderingAddrSpace() const {
183     return OrderingAddrSpace;
184   }
185 
186   /// \returns Return true iff memory ordering of operations on
187   /// different address spaces is required.
188   bool getIsCrossAddressSpaceOrdering() const {
189     return IsCrossAddressSpaceOrdering;
190   }
191 
192   /// \returns True if memory access of the machine instruction used to
193   /// create this SIMemOpInfo is non-temporal, false otherwise.
194   bool isNonTemporal() const {
195     return IsNonTemporal;
196   }
197 
198   /// \returns True if ordering constraint of the machine instruction used to
199   /// create this SIMemOpInfo is unordered or higher, false otherwise.
200   bool isAtomic() const {
201     return Ordering != AtomicOrdering::NotAtomic;
202   }
203 
204 };
205 
206 class SIMemOpAccess final {
207 private:
208   AMDGPUMachineModuleInfo *MMI = nullptr;
209 
210   /// Reports unsupported message \p Msg for \p MI to LLVM context.
211   void reportUnsupported(const MachineBasicBlock::iterator &MI,
212                          const char *Msg) const;
213 
214   /// Inspects the target synchonization scope \p SSID and determines
215   /// the SI atomic scope it corresponds to, the address spaces it
216   /// covers, and whether the memory ordering applies between address
217   /// spaces.
218   Optional<std::tuple<SIAtomicScope, SIAtomicAddrSpace, bool>>
219   toSIAtomicScope(SyncScope::ID SSID, SIAtomicAddrSpace InstrScope) const;
220 
221   /// \return Return a bit set of the address spaces accessed by \p AS.
222   SIAtomicAddrSpace toSIAtomicAddrSpace(unsigned AS) const;
223 
224   /// \returns Info constructed from \p MI, which has at least machine memory
225   /// operand.
226   Optional<SIMemOpInfo> constructFromMIWithMMO(
227       const MachineBasicBlock::iterator &MI) const;
228 
229 public:
230   /// Construct class to support accessing the machine memory operands
231   /// of instructions in the machine function \p MF.
232   SIMemOpAccess(MachineFunction &MF);
233 
234   /// \returns Load info if \p MI is a load operation, "None" otherwise.
235   Optional<SIMemOpInfo> getLoadInfo(
236       const MachineBasicBlock::iterator &MI) const;
237 
238   /// \returns Store info if \p MI is a store operation, "None" otherwise.
239   Optional<SIMemOpInfo> getStoreInfo(
240       const MachineBasicBlock::iterator &MI) const;
241 
242   /// \returns Atomic fence info if \p MI is an atomic fence operation,
243   /// "None" otherwise.
244   Optional<SIMemOpInfo> getAtomicFenceInfo(
245       const MachineBasicBlock::iterator &MI) const;
246 
247   /// \returns Atomic cmpxchg/rmw info if \p MI is an atomic cmpxchg or
248   /// rmw operation, "None" otherwise.
249   Optional<SIMemOpInfo> getAtomicCmpxchgOrRmwInfo(
250       const MachineBasicBlock::iterator &MI) const;
251 };
252 
253 class SICacheControl {
254 protected:
255 
256   /// AMDGPU subtarget info.
257   const GCNSubtarget &ST;
258 
259   /// Instruction info.
260   const SIInstrInfo *TII = nullptr;
261 
262   IsaVersion IV;
263 
264   /// Whether to insert cache invalidating instructions.
265   bool InsertCacheInv;
266 
267   SICacheControl(const GCNSubtarget &ST);
268 
269 public:
270 
271   /// Create a cache control for the subtarget \p ST.
272   static std::unique_ptr<SICacheControl> create(const GCNSubtarget &ST);
273 
274   /// Update \p MI memory load instruction to bypass any caches up to
275   /// the \p Scope memory scope for address spaces \p
276   /// AddrSpace. Return true iff the instruction was modified.
277   virtual bool enableLoadCacheBypass(const MachineBasicBlock::iterator &MI,
278                                      SIAtomicScope Scope,
279                                      SIAtomicAddrSpace AddrSpace) const = 0;
280 
281   /// Update \p MI memory instruction to indicate it is
282   /// nontemporal. Return true iff the instruction was modified.
283   virtual bool enableNonTemporal(const MachineBasicBlock::iterator &MI)
284     const = 0;
285 
286   /// Inserts any necessary instructions at position \p Pos relative
287   /// to instruction \p MI to ensure memory instructions before \p Pos of kind
288   /// \p Op associated with address spaces \p AddrSpace have completed. Used
289   /// between memory instructions to enforce the order they become visible as
290   /// observed by other memory instructions executing in memory scope \p Scope.
291   /// \p IsCrossAddrSpaceOrdering indicates if the memory ordering is between
292   /// address spaces. Returns true iff any instructions inserted.
293   virtual bool insertWait(MachineBasicBlock::iterator &MI,
294                           SIAtomicScope Scope,
295                           SIAtomicAddrSpace AddrSpace,
296                           SIMemOp Op,
297                           bool IsCrossAddrSpaceOrdering,
298                           Position Pos) const = 0;
299 
300   /// Inserts any necessary instructions at position \p Pos relative to
301   /// instruction \p MI to ensure any subsequent memory instructions of this
302   /// thread with address spaces \p AddrSpace will observe the previous memory
303   /// operations by any thread for memory scopes up to memory scope \p Scope .
304   /// Returns true iff any instructions inserted.
305   virtual bool insertAcquire(MachineBasicBlock::iterator &MI,
306                              SIAtomicScope Scope,
307                              SIAtomicAddrSpace AddrSpace,
308                              Position Pos) const = 0;
309 
310   /// Inserts any necessary instructions at position \p Pos relative to
311   /// instruction \p MI to ensure previous memory instructions by this thread
312   /// with address spaces \p AddrSpace have completed and can be observed by
313   /// subsequent memory instructions by any thread executing in memory scope \p
314   /// Scope. \p IsCrossAddrSpaceOrdering indicates if the memory ordering is
315   /// between address spaces. Returns true iff any instructions inserted.
316   virtual bool insertRelease(MachineBasicBlock::iterator &MI,
317                              SIAtomicScope Scope,
318                              SIAtomicAddrSpace AddrSpace,
319                              bool IsCrossAddrSpaceOrdering,
320                              Position Pos) const = 0;
321 
322   /// Virtual destructor to allow derivations to be deleted.
323   virtual ~SICacheControl() = default;
324 
325 };
326 
327 class SIGfx6CacheControl : public SICacheControl {
328 protected:
329 
330   /// Sets GLC bit to "true" if present in \p MI. Returns true if \p MI
331   /// is modified, false otherwise.
332   bool enableGLCBit(const MachineBasicBlock::iterator &MI) const {
333     return enableNamedBit<AMDGPU::OpName::glc>(MI);
334   }
335 
336   /// Sets SLC bit to "true" if present in \p MI. Returns true if \p MI
337   /// is modified, false otherwise.
338   bool enableSLCBit(const MachineBasicBlock::iterator &MI) const {
339     return enableNamedBit<AMDGPU::OpName::slc>(MI);
340   }
341 
342 public:
343 
344   SIGfx6CacheControl(const GCNSubtarget &ST) : SICacheControl(ST) {};
345 
346   bool enableLoadCacheBypass(const MachineBasicBlock::iterator &MI,
347                              SIAtomicScope Scope,
348                              SIAtomicAddrSpace AddrSpace) const override;
349 
350   bool enableNonTemporal(const MachineBasicBlock::iterator &MI) const override;
351 
352   bool insertWait(MachineBasicBlock::iterator &MI,
353                   SIAtomicScope Scope,
354                   SIAtomicAddrSpace AddrSpace,
355                   SIMemOp Op,
356                   bool IsCrossAddrSpaceOrdering,
357                   Position Pos) const override;
358 
359   bool insertAcquire(MachineBasicBlock::iterator &MI,
360                      SIAtomicScope Scope,
361                      SIAtomicAddrSpace AddrSpace,
362                      Position Pos) const override;
363 
364   bool insertRelease(MachineBasicBlock::iterator &MI,
365                      SIAtomicScope Scope,
366                      SIAtomicAddrSpace AddrSpace,
367                      bool IsCrossAddrSpaceOrdering,
368                      Position Pos) const override;
369 };
370 
371 class SIGfx7CacheControl : public SIGfx6CacheControl {
372 public:
373 
374   SIGfx7CacheControl(const GCNSubtarget &ST) : SIGfx6CacheControl(ST) {};
375 
376   bool insertAcquire(MachineBasicBlock::iterator &MI,
377                      SIAtomicScope Scope,
378                      SIAtomicAddrSpace AddrSpace,
379                      Position Pos) const override;
380 
381 };
382 
383 class SIGfx10CacheControl : public SIGfx7CacheControl {
384 protected:
385 
386   /// Sets DLC bit to "true" if present in \p MI. Returns true if \p MI
387   /// is modified, false otherwise.
388   bool enableDLCBit(const MachineBasicBlock::iterator &MI) const {
389     return enableNamedBit<AMDGPU::OpName::dlc>(MI);
390   }
391 
392 public:
393 
394   SIGfx10CacheControl(const GCNSubtarget &ST) : SIGfx7CacheControl(ST) {};
395 
396   bool enableLoadCacheBypass(const MachineBasicBlock::iterator &MI,
397                              SIAtomicScope Scope,
398                              SIAtomicAddrSpace AddrSpace) const override;
399 
400   bool enableNonTemporal(const MachineBasicBlock::iterator &MI) const override;
401 
402   bool insertWait(MachineBasicBlock::iterator &MI,
403                   SIAtomicScope Scope,
404                   SIAtomicAddrSpace AddrSpace,
405                   SIMemOp Op,
406                   bool IsCrossAddrSpaceOrdering,
407                   Position Pos) const override;
408 
409   bool insertAcquire(MachineBasicBlock::iterator &MI,
410                      SIAtomicScope Scope,
411                      SIAtomicAddrSpace AddrSpace,
412                      Position Pos) const override;
413 };
414 
415 class SIMemoryLegalizer final : public MachineFunctionPass {
416 private:
417 
418   /// Cache Control.
419   std::unique_ptr<SICacheControl> CC = nullptr;
420 
421   /// List of atomic pseudo instructions.
422   std::list<MachineBasicBlock::iterator> AtomicPseudoMIs;
423 
424   /// Return true iff instruction \p MI is a atomic instruction that
425   /// returns a result.
426   bool isAtomicRet(const MachineInstr &MI) const {
427     return AMDGPU::getAtomicNoRetOp(MI.getOpcode()) != -1;
428   }
429 
430   /// Removes all processed atomic pseudo instructions from the current
431   /// function. Returns true if current function is modified, false otherwise.
432   bool removeAtomicPseudoMIs();
433 
434   /// Expands load operation \p MI. Returns true if instructions are
435   /// added/deleted or \p MI is modified, false otherwise.
436   bool expandLoad(const SIMemOpInfo &MOI,
437                   MachineBasicBlock::iterator &MI);
438   /// Expands store operation \p MI. Returns true if instructions are
439   /// added/deleted or \p MI is modified, false otherwise.
440   bool expandStore(const SIMemOpInfo &MOI,
441                    MachineBasicBlock::iterator &MI);
442   /// Expands atomic fence operation \p MI. Returns true if
443   /// instructions are added/deleted or \p MI is modified, false otherwise.
444   bool expandAtomicFence(const SIMemOpInfo &MOI,
445                          MachineBasicBlock::iterator &MI);
446   /// Expands atomic cmpxchg or rmw operation \p MI. Returns true if
447   /// instructions are added/deleted or \p MI is modified, false otherwise.
448   bool expandAtomicCmpxchgOrRmw(const SIMemOpInfo &MOI,
449                                 MachineBasicBlock::iterator &MI);
450 
451 public:
452   static char ID;
453 
454   SIMemoryLegalizer() : MachineFunctionPass(ID) {}
455 
456   void getAnalysisUsage(AnalysisUsage &AU) const override {
457     AU.setPreservesCFG();
458     MachineFunctionPass::getAnalysisUsage(AU);
459   }
460 
461   StringRef getPassName() const override {
462     return PASS_NAME;
463   }
464 
465   bool runOnMachineFunction(MachineFunction &MF) override;
466 };
467 
468 } // end namespace anonymous
469 
470 void SIMemOpAccess::reportUnsupported(const MachineBasicBlock::iterator &MI,
471                                       const char *Msg) const {
472   const Function &Func = MI->getParent()->getParent()->getFunction();
473   DiagnosticInfoUnsupported Diag(Func, Msg, MI->getDebugLoc());
474   Func.getContext().diagnose(Diag);
475 }
476 
477 Optional<std::tuple<SIAtomicScope, SIAtomicAddrSpace, bool>>
478 SIMemOpAccess::toSIAtomicScope(SyncScope::ID SSID,
479                                SIAtomicAddrSpace InstrScope) const {
480   if (SSID == SyncScope::System)
481     return std::make_tuple(SIAtomicScope::SYSTEM,
482                            SIAtomicAddrSpace::ATOMIC,
483                            true);
484   if (SSID == MMI->getAgentSSID())
485     return std::make_tuple(SIAtomicScope::AGENT,
486                            SIAtomicAddrSpace::ATOMIC,
487                            true);
488   if (SSID == MMI->getWorkgroupSSID())
489     return std::make_tuple(SIAtomicScope::WORKGROUP,
490                            SIAtomicAddrSpace::ATOMIC,
491                            true);
492   if (SSID == MMI->getWavefrontSSID())
493     return std::make_tuple(SIAtomicScope::WAVEFRONT,
494                            SIAtomicAddrSpace::ATOMIC,
495                            true);
496   if (SSID == SyncScope::SingleThread)
497     return std::make_tuple(SIAtomicScope::SINGLETHREAD,
498                            SIAtomicAddrSpace::ATOMIC,
499                            true);
500   if (SSID == MMI->getSystemOneAddressSpaceSSID())
501     return std::make_tuple(SIAtomicScope::SYSTEM,
502                            SIAtomicAddrSpace::ATOMIC & InstrScope,
503                            false);
504   if (SSID == MMI->getAgentOneAddressSpaceSSID())
505     return std::make_tuple(SIAtomicScope::AGENT,
506                            SIAtomicAddrSpace::ATOMIC & InstrScope,
507                            false);
508   if (SSID == MMI->getWorkgroupOneAddressSpaceSSID())
509     return std::make_tuple(SIAtomicScope::WORKGROUP,
510                            SIAtomicAddrSpace::ATOMIC & InstrScope,
511                            false);
512   if (SSID == MMI->getWavefrontOneAddressSpaceSSID())
513     return std::make_tuple(SIAtomicScope::WAVEFRONT,
514                            SIAtomicAddrSpace::ATOMIC & InstrScope,
515                            false);
516   if (SSID == MMI->getSingleThreadOneAddressSpaceSSID())
517     return std::make_tuple(SIAtomicScope::SINGLETHREAD,
518                            SIAtomicAddrSpace::ATOMIC & InstrScope,
519                            false);
520   return None;
521 }
522 
523 SIAtomicAddrSpace SIMemOpAccess::toSIAtomicAddrSpace(unsigned AS) const {
524   if (AS == AMDGPUAS::FLAT_ADDRESS)
525     return SIAtomicAddrSpace::FLAT;
526   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
527     return SIAtomicAddrSpace::GLOBAL;
528   if (AS == AMDGPUAS::LOCAL_ADDRESS)
529     return SIAtomicAddrSpace::LDS;
530   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
531     return SIAtomicAddrSpace::SCRATCH;
532   if (AS == AMDGPUAS::REGION_ADDRESS)
533     return SIAtomicAddrSpace::GDS;
534 
535   return SIAtomicAddrSpace::OTHER;
536 }
537 
538 SIMemOpAccess::SIMemOpAccess(MachineFunction &MF) {
539   MMI = &MF.getMMI().getObjFileInfo<AMDGPUMachineModuleInfo>();
540 }
541 
542 Optional<SIMemOpInfo> SIMemOpAccess::constructFromMIWithMMO(
543     const MachineBasicBlock::iterator &MI) const {
544   assert(MI->getNumMemOperands() > 0);
545 
546   SyncScope::ID SSID = SyncScope::SingleThread;
547   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
548   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
549   SIAtomicAddrSpace InstrAddrSpace = SIAtomicAddrSpace::NONE;
550   bool IsNonTemporal = true;
551 
552   // Validator should check whether or not MMOs cover the entire set of
553   // locations accessed by the memory instruction.
554   for (const auto &MMO : MI->memoperands()) {
555     IsNonTemporal &= MMO->isNonTemporal();
556     InstrAddrSpace |=
557       toSIAtomicAddrSpace(MMO->getPointerInfo().getAddrSpace());
558     AtomicOrdering OpOrdering = MMO->getOrdering();
559     if (OpOrdering != AtomicOrdering::NotAtomic) {
560       const auto &IsSyncScopeInclusion =
561           MMI->isSyncScopeInclusion(SSID, MMO->getSyncScopeID());
562       if (!IsSyncScopeInclusion) {
563         reportUnsupported(MI,
564           "Unsupported non-inclusive atomic synchronization scope");
565         return None;
566       }
567 
568       SSID = IsSyncScopeInclusion.getValue() ? SSID : MMO->getSyncScopeID();
569       Ordering =
570           isStrongerThan(Ordering, OpOrdering) ?
571               Ordering : MMO->getOrdering();
572       assert(MMO->getFailureOrdering() != AtomicOrdering::Release &&
573              MMO->getFailureOrdering() != AtomicOrdering::AcquireRelease);
574       FailureOrdering =
575           isStrongerThan(FailureOrdering, MMO->getFailureOrdering()) ?
576               FailureOrdering : MMO->getFailureOrdering();
577     }
578   }
579 
580   SIAtomicScope Scope = SIAtomicScope::NONE;
581   SIAtomicAddrSpace OrderingAddrSpace = SIAtomicAddrSpace::NONE;
582   bool IsCrossAddressSpaceOrdering = false;
583   if (Ordering != AtomicOrdering::NotAtomic) {
584     auto ScopeOrNone = toSIAtomicScope(SSID, InstrAddrSpace);
585     if (!ScopeOrNone) {
586       reportUnsupported(MI, "Unsupported atomic synchronization scope");
587       return None;
588     }
589     std::tie(Scope, OrderingAddrSpace, IsCrossAddressSpaceOrdering) =
590       ScopeOrNone.getValue();
591     if ((OrderingAddrSpace == SIAtomicAddrSpace::NONE) ||
592         ((OrderingAddrSpace & SIAtomicAddrSpace::ATOMIC) != OrderingAddrSpace)) {
593       reportUnsupported(MI, "Unsupported atomic address space");
594       return None;
595     }
596   }
597   return SIMemOpInfo(Ordering, Scope, OrderingAddrSpace, InstrAddrSpace,
598                      IsCrossAddressSpaceOrdering, FailureOrdering, IsNonTemporal);
599 }
600 
601 Optional<SIMemOpInfo> SIMemOpAccess::getLoadInfo(
602     const MachineBasicBlock::iterator &MI) const {
603   assert(MI->getDesc().TSFlags & SIInstrFlags::maybeAtomic);
604 
605   if (!(MI->mayLoad() && !MI->mayStore()))
606     return None;
607 
608   // Be conservative if there are no memory operands.
609   if (MI->getNumMemOperands() == 0)
610     return SIMemOpInfo();
611 
612   return constructFromMIWithMMO(MI);
613 }
614 
615 Optional<SIMemOpInfo> SIMemOpAccess::getStoreInfo(
616     const MachineBasicBlock::iterator &MI) const {
617   assert(MI->getDesc().TSFlags & SIInstrFlags::maybeAtomic);
618 
619   if (!(!MI->mayLoad() && MI->mayStore()))
620     return None;
621 
622   // Be conservative if there are no memory operands.
623   if (MI->getNumMemOperands() == 0)
624     return SIMemOpInfo();
625 
626   return constructFromMIWithMMO(MI);
627 }
628 
629 Optional<SIMemOpInfo> SIMemOpAccess::getAtomicFenceInfo(
630     const MachineBasicBlock::iterator &MI) const {
631   assert(MI->getDesc().TSFlags & SIInstrFlags::maybeAtomic);
632 
633   if (MI->getOpcode() != AMDGPU::ATOMIC_FENCE)
634     return None;
635 
636   AtomicOrdering Ordering =
637     static_cast<AtomicOrdering>(MI->getOperand(0).getImm());
638 
639   SyncScope::ID SSID = static_cast<SyncScope::ID>(MI->getOperand(1).getImm());
640   auto ScopeOrNone = toSIAtomicScope(SSID, SIAtomicAddrSpace::ATOMIC);
641   if (!ScopeOrNone) {
642     reportUnsupported(MI, "Unsupported atomic synchronization scope");
643     return None;
644   }
645 
646   SIAtomicScope Scope = SIAtomicScope::NONE;
647   SIAtomicAddrSpace OrderingAddrSpace = SIAtomicAddrSpace::NONE;
648   bool IsCrossAddressSpaceOrdering = false;
649   std::tie(Scope, OrderingAddrSpace, IsCrossAddressSpaceOrdering) =
650     ScopeOrNone.getValue();
651 
652   if ((OrderingAddrSpace == SIAtomicAddrSpace::NONE) ||
653       ((OrderingAddrSpace & SIAtomicAddrSpace::ATOMIC) != OrderingAddrSpace)) {
654     reportUnsupported(MI, "Unsupported atomic address space");
655     return None;
656   }
657 
658   return SIMemOpInfo(Ordering, Scope, OrderingAddrSpace, SIAtomicAddrSpace::ATOMIC,
659                      IsCrossAddressSpaceOrdering);
660 }
661 
662 Optional<SIMemOpInfo> SIMemOpAccess::getAtomicCmpxchgOrRmwInfo(
663     const MachineBasicBlock::iterator &MI) const {
664   assert(MI->getDesc().TSFlags & SIInstrFlags::maybeAtomic);
665 
666   if (!(MI->mayLoad() && MI->mayStore()))
667     return None;
668 
669   // Be conservative if there are no memory operands.
670   if (MI->getNumMemOperands() == 0)
671     return SIMemOpInfo();
672 
673   return constructFromMIWithMMO(MI);
674 }
675 
676 SICacheControl::SICacheControl(const GCNSubtarget &ST) : ST(ST) {
677   TII = ST.getInstrInfo();
678   IV = getIsaVersion(ST.getCPU());
679   InsertCacheInv = !AmdgcnSkipCacheInvalidations;
680 }
681 
682 /* static */
683 std::unique_ptr<SICacheControl> SICacheControl::create(const GCNSubtarget &ST) {
684   GCNSubtarget::Generation Generation = ST.getGeneration();
685   if (Generation <= AMDGPUSubtarget::SOUTHERN_ISLANDS)
686     return std::make_unique<SIGfx6CacheControl>(ST);
687   if (Generation < AMDGPUSubtarget::GFX10)
688     return std::make_unique<SIGfx7CacheControl>(ST);
689   return std::make_unique<SIGfx10CacheControl>(ST);
690 }
691 
692 bool SIGfx6CacheControl::enableLoadCacheBypass(
693     const MachineBasicBlock::iterator &MI,
694     SIAtomicScope Scope,
695     SIAtomicAddrSpace AddrSpace) const {
696   assert(MI->mayLoad() && !MI->mayStore());
697   bool Changed = false;
698 
699   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
700     switch (Scope) {
701     case SIAtomicScope::SYSTEM:
702     case SIAtomicScope::AGENT:
703       Changed |= enableGLCBit(MI);
704       break;
705     case SIAtomicScope::WORKGROUP:
706     case SIAtomicScope::WAVEFRONT:
707     case SIAtomicScope::SINGLETHREAD:
708       // No cache to bypass.
709       break;
710     default:
711       llvm_unreachable("Unsupported synchronization scope");
712     }
713   }
714 
715   /// The scratch address space does not need the global memory caches
716   /// to be bypassed as all memory operations by the same thread are
717   /// sequentially consistent, and no other thread can access scratch
718   /// memory.
719 
720   /// Other address spaces do not have a cache.
721 
722   return Changed;
723 }
724 
725 bool SIGfx6CacheControl::enableNonTemporal(
726     const MachineBasicBlock::iterator &MI) const {
727   assert(MI->mayLoad() ^ MI->mayStore());
728   bool Changed = false;
729 
730   /// TODO: Do not enableGLCBit if rmw atomic.
731   Changed |= enableGLCBit(MI);
732   Changed |= enableSLCBit(MI);
733 
734   return Changed;
735 }
736 
737 bool SIGfx6CacheControl::insertWait(MachineBasicBlock::iterator &MI,
738                                     SIAtomicScope Scope,
739                                     SIAtomicAddrSpace AddrSpace,
740                                     SIMemOp Op,
741                                     bool IsCrossAddrSpaceOrdering,
742                                     Position Pos) const {
743   bool Changed = false;
744 
745   MachineBasicBlock &MBB = *MI->getParent();
746   DebugLoc DL = MI->getDebugLoc();
747 
748   if (Pos == Position::AFTER)
749     ++MI;
750 
751   bool VMCnt = false;
752   bool LGKMCnt = false;
753 
754   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
755     switch (Scope) {
756     case SIAtomicScope::SYSTEM:
757     case SIAtomicScope::AGENT:
758       VMCnt |= true;
759       break;
760     case SIAtomicScope::WORKGROUP:
761     case SIAtomicScope::WAVEFRONT:
762     case SIAtomicScope::SINGLETHREAD:
763       // The L1 cache keeps all memory operations in order for
764       // wavefronts in the same work-group.
765       break;
766     default:
767       llvm_unreachable("Unsupported synchronization scope");
768     }
769   }
770 
771   if ((AddrSpace & SIAtomicAddrSpace::LDS) != SIAtomicAddrSpace::NONE) {
772     switch (Scope) {
773     case SIAtomicScope::SYSTEM:
774     case SIAtomicScope::AGENT:
775     case SIAtomicScope::WORKGROUP:
776       // If no cross address space ordering then an "S_WAITCNT lgkmcnt(0)" is
777       // not needed as LDS operations for all waves are executed in a total
778       // global ordering as observed by all waves. Required if also
779       // synchronizing with global/GDS memory as LDS operations could be
780       // reordered with respect to later global/GDS memory operations of the
781       // same wave.
782       LGKMCnt |= IsCrossAddrSpaceOrdering;
783       break;
784     case SIAtomicScope::WAVEFRONT:
785     case SIAtomicScope::SINGLETHREAD:
786       // The LDS keeps all memory operations in order for
787       // the same wavesfront.
788       break;
789     default:
790       llvm_unreachable("Unsupported synchronization scope");
791     }
792   }
793 
794   if ((AddrSpace & SIAtomicAddrSpace::GDS) != SIAtomicAddrSpace::NONE) {
795     switch (Scope) {
796     case SIAtomicScope::SYSTEM:
797     case SIAtomicScope::AGENT:
798       // If no cross address space ordering then an GDS "S_WAITCNT lgkmcnt(0)"
799       // is not needed as GDS operations for all waves are executed in a total
800       // global ordering as observed by all waves. Required if also
801       // synchronizing with global/LDS memory as GDS operations could be
802       // reordered with respect to later global/LDS memory operations of the
803       // same wave.
804       LGKMCnt |= IsCrossAddrSpaceOrdering;
805       break;
806     case SIAtomicScope::WORKGROUP:
807     case SIAtomicScope::WAVEFRONT:
808     case SIAtomicScope::SINGLETHREAD:
809       // The GDS keeps all memory operations in order for
810       // the same work-group.
811       break;
812     default:
813       llvm_unreachable("Unsupported synchronization scope");
814     }
815   }
816 
817   if (VMCnt || LGKMCnt) {
818     unsigned WaitCntImmediate =
819       AMDGPU::encodeWaitcnt(IV,
820                             VMCnt ? 0 : getVmcntBitMask(IV),
821                             getExpcntBitMask(IV),
822                             LGKMCnt ? 0 : getLgkmcntBitMask(IV));
823     BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_WAITCNT)).addImm(WaitCntImmediate);
824     Changed = true;
825   }
826 
827   if (Pos == Position::AFTER)
828     --MI;
829 
830   return Changed;
831 }
832 
833 bool SIGfx6CacheControl::insertAcquire(MachineBasicBlock::iterator &MI,
834                                        SIAtomicScope Scope,
835                                        SIAtomicAddrSpace AddrSpace,
836                                        Position Pos) const {
837   if (!InsertCacheInv)
838     return false;
839 
840   bool Changed = false;
841 
842   MachineBasicBlock &MBB = *MI->getParent();
843   DebugLoc DL = MI->getDebugLoc();
844 
845   if (Pos == Position::AFTER)
846     ++MI;
847 
848   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
849     switch (Scope) {
850     case SIAtomicScope::SYSTEM:
851     case SIAtomicScope::AGENT:
852       BuildMI(MBB, MI, DL, TII->get(AMDGPU::BUFFER_WBINVL1));
853       Changed = true;
854       break;
855     case SIAtomicScope::WORKGROUP:
856     case SIAtomicScope::WAVEFRONT:
857     case SIAtomicScope::SINGLETHREAD:
858       // No cache to invalidate.
859       break;
860     default:
861       llvm_unreachable("Unsupported synchronization scope");
862     }
863   }
864 
865   /// The scratch address space does not need the global memory cache
866   /// to be flushed as all memory operations by the same thread are
867   /// sequentially consistent, and no other thread can access scratch
868   /// memory.
869 
870   /// Other address spaces do not have a cache.
871 
872   if (Pos == Position::AFTER)
873     --MI;
874 
875   return Changed;
876 }
877 
878 bool SIGfx6CacheControl::insertRelease(MachineBasicBlock::iterator &MI,
879                                        SIAtomicScope Scope,
880                                        SIAtomicAddrSpace AddrSpace,
881                                        bool IsCrossAddrSpaceOrdering,
882                                        Position Pos) const {
883     return insertWait(MI, Scope, AddrSpace, SIMemOp::LOAD | SIMemOp::STORE,
884                       IsCrossAddrSpaceOrdering, Pos);
885 }
886 
887 bool SIGfx7CacheControl::insertAcquire(MachineBasicBlock::iterator &MI,
888                                        SIAtomicScope Scope,
889                                        SIAtomicAddrSpace AddrSpace,
890                                        Position Pos) const {
891   if (!InsertCacheInv)
892     return false;
893 
894   bool Changed = false;
895 
896   MachineBasicBlock &MBB = *MI->getParent();
897   DebugLoc DL = MI->getDebugLoc();
898 
899   const GCNSubtarget &STM = MBB.getParent()->getSubtarget<GCNSubtarget>();
900 
901   const unsigned InvalidateL1 = STM.isAmdPalOS() || STM.isMesa3DOS()
902                                     ? AMDGPU::BUFFER_WBINVL1
903                                     : AMDGPU::BUFFER_WBINVL1_VOL;
904 
905   if (Pos == Position::AFTER)
906     ++MI;
907 
908   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
909     switch (Scope) {
910     case SIAtomicScope::SYSTEM:
911     case SIAtomicScope::AGENT:
912       BuildMI(MBB, MI, DL, TII->get(InvalidateL1));
913       Changed = true;
914       break;
915     case SIAtomicScope::WORKGROUP:
916     case SIAtomicScope::WAVEFRONT:
917     case SIAtomicScope::SINGLETHREAD:
918       // No cache to invalidate.
919       break;
920     default:
921       llvm_unreachable("Unsupported synchronization scope");
922     }
923   }
924 
925   /// The scratch address space does not need the global memory cache
926   /// to be flushed as all memory operations by the same thread are
927   /// sequentially consistent, and no other thread can access scratch
928   /// memory.
929 
930   /// Other address spaces do not have a cache.
931 
932   if (Pos == Position::AFTER)
933     --MI;
934 
935   return Changed;
936 }
937 
938 bool SIGfx10CacheControl::enableLoadCacheBypass(
939     const MachineBasicBlock::iterator &MI,
940     SIAtomicScope Scope,
941     SIAtomicAddrSpace AddrSpace) const {
942   assert(MI->mayLoad() && !MI->mayStore());
943   bool Changed = false;
944 
945   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
946     /// TODO Do not set glc for rmw atomic operations as they
947     /// implicitly bypass the L0/L1 caches.
948 
949     switch (Scope) {
950     case SIAtomicScope::SYSTEM:
951     case SIAtomicScope::AGENT:
952       Changed |= enableGLCBit(MI);
953       Changed |= enableDLCBit(MI);
954       break;
955     case SIAtomicScope::WORKGROUP:
956       // In WGP mode the waves of a work-group can be executing on either CU of
957       // the WGP. Therefore need to bypass the L0 which is per CU. Otherwise in
958       // CU mode all waves of a work-group are on the same CU, and so the L0
959       // does not need to be bypassed.
960       if (!ST.isCuModeEnabled()) Changed |= enableGLCBit(MI);
961       break;
962     case SIAtomicScope::WAVEFRONT:
963     case SIAtomicScope::SINGLETHREAD:
964       // No cache to bypass.
965       break;
966     default:
967       llvm_unreachable("Unsupported synchronization scope");
968     }
969   }
970 
971   /// The scratch address space does not need the global memory caches
972   /// to be bypassed as all memory operations by the same thread are
973   /// sequentially consistent, and no other thread can access scratch
974   /// memory.
975 
976   /// Other address spaces do not have a cache.
977 
978   return Changed;
979 }
980 
981 bool SIGfx10CacheControl::enableNonTemporal(
982     const MachineBasicBlock::iterator &MI) const {
983   assert(MI->mayLoad() ^ MI->mayStore());
984   bool Changed = false;
985 
986   Changed |= enableSLCBit(MI);
987   /// TODO for store (non-rmw atomic) instructions also enableGLCBit(MI)
988 
989   return Changed;
990 }
991 
992 bool SIGfx10CacheControl::insertWait(MachineBasicBlock::iterator &MI,
993                                      SIAtomicScope Scope,
994                                      SIAtomicAddrSpace AddrSpace,
995                                      SIMemOp Op,
996                                      bool IsCrossAddrSpaceOrdering,
997                                      Position Pos) const {
998   bool Changed = false;
999 
1000   MachineBasicBlock &MBB = *MI->getParent();
1001   DebugLoc DL = MI->getDebugLoc();
1002 
1003   if (Pos == Position::AFTER)
1004     ++MI;
1005 
1006   bool VMCnt = false;
1007   bool VSCnt = false;
1008   bool LGKMCnt = false;
1009 
1010   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
1011     switch (Scope) {
1012     case SIAtomicScope::SYSTEM:
1013     case SIAtomicScope::AGENT:
1014       if ((Op & SIMemOp::LOAD) != SIMemOp::NONE)
1015         VMCnt |= true;
1016       if ((Op & SIMemOp::STORE) != SIMemOp::NONE)
1017         VSCnt |= true;
1018       break;
1019     case SIAtomicScope::WORKGROUP:
1020       // In WGP mode the waves of a work-group can be executing on either CU of
1021       // the WGP. Therefore need to wait for operations to complete to ensure
1022       // they are visible to waves in the other CU as the L0 is per CU.
1023       // Otherwise in CU mode and all waves of a work-group are on the same CU
1024       // which shares the same L0.
1025       if (!ST.isCuModeEnabled()) {
1026         if ((Op & SIMemOp::LOAD) != SIMemOp::NONE)
1027           VMCnt |= true;
1028         if ((Op & SIMemOp::STORE) != SIMemOp::NONE)
1029           VSCnt |= true;
1030       }
1031       break;
1032     case SIAtomicScope::WAVEFRONT:
1033     case SIAtomicScope::SINGLETHREAD:
1034       // The L0 cache keeps all memory operations in order for
1035       // work-items in the same wavefront.
1036       break;
1037     default:
1038       llvm_unreachable("Unsupported synchronization scope");
1039     }
1040   }
1041 
1042   if ((AddrSpace & SIAtomicAddrSpace::LDS) != SIAtomicAddrSpace::NONE) {
1043     switch (Scope) {
1044     case SIAtomicScope::SYSTEM:
1045     case SIAtomicScope::AGENT:
1046     case SIAtomicScope::WORKGROUP:
1047       // If no cross address space ordering then an "S_WAITCNT lgkmcnt(0)" is
1048       // not needed as LDS operations for all waves are executed in a total
1049       // global ordering as observed by all waves. Required if also
1050       // synchronizing with global/GDS memory as LDS operations could be
1051       // reordered with respect to later global/GDS memory operations of the
1052       // same wave.
1053       LGKMCnt |= IsCrossAddrSpaceOrdering;
1054       break;
1055     case SIAtomicScope::WAVEFRONT:
1056     case SIAtomicScope::SINGLETHREAD:
1057       // The LDS keeps all memory operations in order for
1058       // the same wavesfront.
1059       break;
1060     default:
1061       llvm_unreachable("Unsupported synchronization scope");
1062     }
1063   }
1064 
1065   if ((AddrSpace & SIAtomicAddrSpace::GDS) != SIAtomicAddrSpace::NONE) {
1066     switch (Scope) {
1067     case SIAtomicScope::SYSTEM:
1068     case SIAtomicScope::AGENT:
1069       // If no cross address space ordering then an GDS "S_WAITCNT lgkmcnt(0)"
1070       // is not needed as GDS operations for all waves are executed in a total
1071       // global ordering as observed by all waves. Required if also
1072       // synchronizing with global/LDS memory as GDS operations could be
1073       // reordered with respect to later global/LDS memory operations of the
1074       // same wave.
1075       LGKMCnt |= IsCrossAddrSpaceOrdering;
1076       break;
1077     case SIAtomicScope::WORKGROUP:
1078     case SIAtomicScope::WAVEFRONT:
1079     case SIAtomicScope::SINGLETHREAD:
1080       // The GDS keeps all memory operations in order for
1081       // the same work-group.
1082       break;
1083     default:
1084       llvm_unreachable("Unsupported synchronization scope");
1085     }
1086   }
1087 
1088   if (VMCnt || LGKMCnt) {
1089     unsigned WaitCntImmediate =
1090       AMDGPU::encodeWaitcnt(IV,
1091                             VMCnt ? 0 : getVmcntBitMask(IV),
1092                             getExpcntBitMask(IV),
1093                             LGKMCnt ? 0 : getLgkmcntBitMask(IV));
1094     BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_WAITCNT)).addImm(WaitCntImmediate);
1095     Changed = true;
1096   }
1097 
1098   if (VSCnt) {
1099     BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_WAITCNT_VSCNT))
1100       .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1101       .addImm(0);
1102     Changed = true;
1103   }
1104 
1105   if (Pos == Position::AFTER)
1106     --MI;
1107 
1108   return Changed;
1109 }
1110 
1111 bool SIGfx10CacheControl::insertAcquire(MachineBasicBlock::iterator &MI,
1112                                         SIAtomicScope Scope,
1113                                         SIAtomicAddrSpace AddrSpace,
1114                                         Position Pos) const {
1115   if (!InsertCacheInv)
1116     return false;
1117 
1118   bool Changed = false;
1119 
1120   MachineBasicBlock &MBB = *MI->getParent();
1121   DebugLoc DL = MI->getDebugLoc();
1122 
1123   if (Pos == Position::AFTER)
1124     ++MI;
1125 
1126   if ((AddrSpace & SIAtomicAddrSpace::GLOBAL) != SIAtomicAddrSpace::NONE) {
1127     switch (Scope) {
1128     case SIAtomicScope::SYSTEM:
1129     case SIAtomicScope::AGENT:
1130       BuildMI(MBB, MI, DL, TII->get(AMDGPU::BUFFER_GL0_INV));
1131       BuildMI(MBB, MI, DL, TII->get(AMDGPU::BUFFER_GL1_INV));
1132       Changed = true;
1133       break;
1134     case SIAtomicScope::WORKGROUP:
1135       // In WGP mode the waves of a work-group can be executing on either CU of
1136       // the WGP. Therefore need to invalidate the L0 which is per CU. Otherwise
1137       // in CU mode and all waves of a work-group are on the same CU, and so the
1138       // L0 does not need to be invalidated.
1139       if (!ST.isCuModeEnabled()) {
1140         BuildMI(MBB, MI, DL, TII->get(AMDGPU::BUFFER_GL0_INV));
1141         Changed = true;
1142       }
1143       break;
1144     case SIAtomicScope::WAVEFRONT:
1145     case SIAtomicScope::SINGLETHREAD:
1146       // No cache to invalidate.
1147       break;
1148     default:
1149       llvm_unreachable("Unsupported synchronization scope");
1150     }
1151   }
1152 
1153   /// The scratch address space does not need the global memory cache
1154   /// to be flushed as all memory operations by the same thread are
1155   /// sequentially consistent, and no other thread can access scratch
1156   /// memory.
1157 
1158   /// Other address spaces do not have a cache.
1159 
1160   if (Pos == Position::AFTER)
1161     --MI;
1162 
1163   return Changed;
1164 }
1165 
1166 bool SIMemoryLegalizer::removeAtomicPseudoMIs() {
1167   if (AtomicPseudoMIs.empty())
1168     return false;
1169 
1170   for (auto &MI : AtomicPseudoMIs)
1171     MI->eraseFromParent();
1172 
1173   AtomicPseudoMIs.clear();
1174   return true;
1175 }
1176 
1177 bool SIMemoryLegalizer::expandLoad(const SIMemOpInfo &MOI,
1178                                    MachineBasicBlock::iterator &MI) {
1179   assert(MI->mayLoad() && !MI->mayStore());
1180 
1181   bool Changed = false;
1182 
1183   if (MOI.isAtomic()) {
1184     if (MOI.getOrdering() == AtomicOrdering::Monotonic ||
1185         MOI.getOrdering() == AtomicOrdering::Acquire ||
1186         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent) {
1187       Changed |= CC->enableLoadCacheBypass(MI, MOI.getScope(),
1188                                            MOI.getOrderingAddrSpace());
1189     }
1190 
1191     if (MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent)
1192       Changed |= CC->insertWait(MI, MOI.getScope(),
1193                                 MOI.getOrderingAddrSpace(),
1194                                 SIMemOp::LOAD | SIMemOp::STORE,
1195                                 MOI.getIsCrossAddressSpaceOrdering(),
1196                                 Position::BEFORE);
1197 
1198     if (MOI.getOrdering() == AtomicOrdering::Acquire ||
1199         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent) {
1200       Changed |= CC->insertWait(MI, MOI.getScope(),
1201                                 MOI.getInstrAddrSpace(),
1202                                 SIMemOp::LOAD,
1203                                 MOI.getIsCrossAddressSpaceOrdering(),
1204                                 Position::AFTER);
1205       Changed |= CC->insertAcquire(MI, MOI.getScope(),
1206                                    MOI.getOrderingAddrSpace(),
1207                                    Position::AFTER);
1208     }
1209 
1210     return Changed;
1211   }
1212 
1213   // Atomic instructions do not have the nontemporal attribute.
1214   if (MOI.isNonTemporal()) {
1215     Changed |= CC->enableNonTemporal(MI);
1216     return Changed;
1217   }
1218 
1219   return Changed;
1220 }
1221 
1222 bool SIMemoryLegalizer::expandStore(const SIMemOpInfo &MOI,
1223                                     MachineBasicBlock::iterator &MI) {
1224   assert(!MI->mayLoad() && MI->mayStore());
1225 
1226   bool Changed = false;
1227 
1228   if (MOI.isAtomic()) {
1229     if (MOI.getOrdering() == AtomicOrdering::Release ||
1230         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent)
1231       Changed |= CC->insertRelease(MI, MOI.getScope(),
1232                                    MOI.getOrderingAddrSpace(),
1233                                    MOI.getIsCrossAddressSpaceOrdering(),
1234                                    Position::BEFORE);
1235 
1236     return Changed;
1237   }
1238 
1239   // Atomic instructions do not have the nontemporal attribute.
1240   if (MOI.isNonTemporal()) {
1241     Changed |= CC->enableNonTemporal(MI);
1242     return Changed;
1243   }
1244 
1245   return Changed;
1246 }
1247 
1248 bool SIMemoryLegalizer::expandAtomicFence(const SIMemOpInfo &MOI,
1249                                           MachineBasicBlock::iterator &MI) {
1250   assert(MI->getOpcode() == AMDGPU::ATOMIC_FENCE);
1251 
1252   AtomicPseudoMIs.push_back(MI);
1253   bool Changed = false;
1254 
1255   if (MOI.isAtomic()) {
1256     if (MOI.getOrdering() == AtomicOrdering::Acquire ||
1257         MOI.getOrdering() == AtomicOrdering::Release ||
1258         MOI.getOrdering() == AtomicOrdering::AcquireRelease ||
1259         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent)
1260       /// TODO: This relies on a barrier always generating a waitcnt
1261       /// for LDS to ensure it is not reordered with the completion of
1262       /// the proceeding LDS operations. If barrier had a memory
1263       /// ordering and memory scope, then library does not need to
1264       /// generate a fence. Could add support in this file for
1265       /// barrier. SIInsertWaitcnt.cpp could then stop unconditionally
1266       /// adding S_WAITCNT before a S_BARRIER.
1267       Changed |= CC->insertRelease(MI, MOI.getScope(),
1268                                    MOI.getOrderingAddrSpace(),
1269                                    MOI.getIsCrossAddressSpaceOrdering(),
1270                                    Position::BEFORE);
1271 
1272     // TODO: If both release and invalidate are happening they could be combined
1273     // to use the single "BUFFER_WBL2" instruction. This could be done by
1274     // reorganizing this code or as part of optimizing SIInsertWaitcnt pass to
1275     // track cache invalidate and write back instructions.
1276 
1277     if (MOI.getOrdering() == AtomicOrdering::Acquire ||
1278         MOI.getOrdering() == AtomicOrdering::AcquireRelease ||
1279         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent)
1280       Changed |= CC->insertAcquire(MI, MOI.getScope(),
1281                                    MOI.getOrderingAddrSpace(),
1282                                    Position::BEFORE);
1283 
1284     return Changed;
1285   }
1286 
1287   return Changed;
1288 }
1289 
1290 bool SIMemoryLegalizer::expandAtomicCmpxchgOrRmw(const SIMemOpInfo &MOI,
1291   MachineBasicBlock::iterator &MI) {
1292   assert(MI->mayLoad() && MI->mayStore());
1293 
1294   bool Changed = false;
1295 
1296   if (MOI.isAtomic()) {
1297     if (MOI.getOrdering() == AtomicOrdering::Release ||
1298         MOI.getOrdering() == AtomicOrdering::AcquireRelease ||
1299         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent ||
1300         MOI.getFailureOrdering() == AtomicOrdering::SequentiallyConsistent)
1301       Changed |= CC->insertRelease(MI, MOI.getScope(),
1302                                    MOI.getOrderingAddrSpace(),
1303                                    MOI.getIsCrossAddressSpaceOrdering(),
1304                                    Position::BEFORE);
1305 
1306     if (MOI.getOrdering() == AtomicOrdering::Acquire ||
1307         MOI.getOrdering() == AtomicOrdering::AcquireRelease ||
1308         MOI.getOrdering() == AtomicOrdering::SequentiallyConsistent ||
1309         MOI.getFailureOrdering() == AtomicOrdering::Acquire ||
1310         MOI.getFailureOrdering() == AtomicOrdering::SequentiallyConsistent) {
1311       Changed |= CC->insertWait(MI, MOI.getScope(),
1312                                 MOI.getOrderingAddrSpace(),
1313                                 isAtomicRet(*MI) ? SIMemOp::LOAD :
1314                                                    SIMemOp::STORE,
1315                                 MOI.getIsCrossAddressSpaceOrdering(),
1316                                 Position::AFTER);
1317       Changed |= CC->insertAcquire(MI, MOI.getScope(),
1318                                    MOI.getOrderingAddrSpace(),
1319                                    Position::AFTER);
1320     }
1321 
1322     return Changed;
1323   }
1324 
1325   return Changed;
1326 }
1327 
1328 bool SIMemoryLegalizer::runOnMachineFunction(MachineFunction &MF) {
1329   bool Changed = false;
1330 
1331   SIMemOpAccess MOA(MF);
1332   CC = SICacheControl::create(MF.getSubtarget<GCNSubtarget>());
1333 
1334   for (auto &MBB : MF) {
1335     for (auto MI = MBB.begin(); MI != MBB.end(); ++MI) {
1336 
1337       // Unbundle instructions after the post-RA scheduler.
1338       if (MI->isBundle()) {
1339         MachineBasicBlock::instr_iterator II(MI->getIterator());
1340         for (MachineBasicBlock::instr_iterator I = ++II, E = MBB.instr_end();
1341              I != E && I->isBundledWithPred(); ++I) {
1342           I->unbundleFromPred();
1343           for (MachineOperand &MO : I->operands())
1344             if (MO.isReg())
1345               MO.setIsInternalRead(false);
1346         }
1347 
1348         MI->eraseFromParent();
1349         MI = II->getIterator();
1350       }
1351 
1352       if (!(MI->getDesc().TSFlags & SIInstrFlags::maybeAtomic))
1353         continue;
1354 
1355       if (const auto &MOI = MOA.getLoadInfo(MI))
1356         Changed |= expandLoad(MOI.getValue(), MI);
1357       else if (const auto &MOI = MOA.getStoreInfo(MI))
1358         Changed |= expandStore(MOI.getValue(), MI);
1359       else if (const auto &MOI = MOA.getAtomicFenceInfo(MI))
1360         Changed |= expandAtomicFence(MOI.getValue(), MI);
1361       else if (const auto &MOI = MOA.getAtomicCmpxchgOrRmwInfo(MI))
1362         Changed |= expandAtomicCmpxchgOrRmw(MOI.getValue(), MI);
1363     }
1364   }
1365 
1366   Changed |= removeAtomicPseudoMIs();
1367   return Changed;
1368 }
1369 
1370 INITIALIZE_PASS(SIMemoryLegalizer, DEBUG_TYPE, PASS_NAME, false, false)
1371 
1372 char SIMemoryLegalizer::ID = 0;
1373 char &llvm::SIMemoryLegalizerID = SIMemoryLegalizer::ID;
1374 
1375 FunctionPass *llvm::createSIMemoryLegalizerPass() {
1376   return new SIMemoryLegalizer();
1377 }
1378