106f32e7eSjoerg //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file contains a pass (at IR level) to replace atomic instructions with
1006f32e7eSjoerg // __atomic_* library calls, or target specific instruction which implement the
1106f32e7eSjoerg // same semantics in a way which better fits the target backend.  This can
1206f32e7eSjoerg // include the use of (intrinsic-based) load-linked/store-conditional loops,
1306f32e7eSjoerg // AtomicCmpXchg, or type coercions.
1406f32e7eSjoerg //
1506f32e7eSjoerg //===----------------------------------------------------------------------===//
1606f32e7eSjoerg 
1706f32e7eSjoerg #include "llvm/ADT/ArrayRef.h"
1806f32e7eSjoerg #include "llvm/ADT/STLExtras.h"
1906f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
2006f32e7eSjoerg #include "llvm/CodeGen/AtomicExpandUtils.h"
2106f32e7eSjoerg #include "llvm/CodeGen/RuntimeLibcalls.h"
2206f32e7eSjoerg #include "llvm/CodeGen/TargetLowering.h"
2306f32e7eSjoerg #include "llvm/CodeGen/TargetPassConfig.h"
2406f32e7eSjoerg #include "llvm/CodeGen/TargetSubtargetInfo.h"
2506f32e7eSjoerg #include "llvm/CodeGen/ValueTypes.h"
2606f32e7eSjoerg #include "llvm/IR/Attributes.h"
2706f32e7eSjoerg #include "llvm/IR/BasicBlock.h"
2806f32e7eSjoerg #include "llvm/IR/Constant.h"
2906f32e7eSjoerg #include "llvm/IR/Constants.h"
3006f32e7eSjoerg #include "llvm/IR/DataLayout.h"
3106f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
3206f32e7eSjoerg #include "llvm/IR/Function.h"
3306f32e7eSjoerg #include "llvm/IR/IRBuilder.h"
3406f32e7eSjoerg #include "llvm/IR/InstIterator.h"
3506f32e7eSjoerg #include "llvm/IR/Instruction.h"
3606f32e7eSjoerg #include "llvm/IR/Instructions.h"
3706f32e7eSjoerg #include "llvm/IR/Module.h"
3806f32e7eSjoerg #include "llvm/IR/Type.h"
3906f32e7eSjoerg #include "llvm/IR/User.h"
4006f32e7eSjoerg #include "llvm/IR/Value.h"
41*da58b97aSjoerg #include "llvm/InitializePasses.h"
4206f32e7eSjoerg #include "llvm/Pass.h"
4306f32e7eSjoerg #include "llvm/Support/AtomicOrdering.h"
4406f32e7eSjoerg #include "llvm/Support/Casting.h"
4506f32e7eSjoerg #include "llvm/Support/Debug.h"
4606f32e7eSjoerg #include "llvm/Support/ErrorHandling.h"
4706f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
4806f32e7eSjoerg #include "llvm/Target/TargetMachine.h"
4906f32e7eSjoerg #include <cassert>
5006f32e7eSjoerg #include <cstdint>
5106f32e7eSjoerg #include <iterator>
5206f32e7eSjoerg 
5306f32e7eSjoerg using namespace llvm;
5406f32e7eSjoerg 
5506f32e7eSjoerg #define DEBUG_TYPE "atomic-expand"
5606f32e7eSjoerg 
5706f32e7eSjoerg namespace {
5806f32e7eSjoerg 
5906f32e7eSjoerg   class AtomicExpand: public FunctionPass {
6006f32e7eSjoerg     const TargetLowering *TLI = nullptr;
6106f32e7eSjoerg 
6206f32e7eSjoerg   public:
6306f32e7eSjoerg     static char ID; // Pass identification, replacement for typeid
6406f32e7eSjoerg 
AtomicExpand()6506f32e7eSjoerg     AtomicExpand() : FunctionPass(ID) {
6606f32e7eSjoerg       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
6706f32e7eSjoerg     }
6806f32e7eSjoerg 
6906f32e7eSjoerg     bool runOnFunction(Function &F) override;
7006f32e7eSjoerg 
7106f32e7eSjoerg   private:
7206f32e7eSjoerg     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
7306f32e7eSjoerg     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
7406f32e7eSjoerg     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
7506f32e7eSjoerg     bool tryExpandAtomicLoad(LoadInst *LI);
7606f32e7eSjoerg     bool expandAtomicLoadToLL(LoadInst *LI);
7706f32e7eSjoerg     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
7806f32e7eSjoerg     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
7906f32e7eSjoerg     bool expandAtomicStore(StoreInst *SI);
8006f32e7eSjoerg     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
8106f32e7eSjoerg     Value *
8206f32e7eSjoerg     insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
83*da58b97aSjoerg                       Align AddrAlign, AtomicOrdering MemOpOrder,
8406f32e7eSjoerg                       function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
8506f32e7eSjoerg     void expandAtomicOpToLLSC(
86*da58b97aSjoerg         Instruction *I, Type *ResultTy, Value *Addr, Align AddrAlign,
87*da58b97aSjoerg         AtomicOrdering MemOpOrder,
8806f32e7eSjoerg         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
8906f32e7eSjoerg     void expandPartwordAtomicRMW(
9006f32e7eSjoerg         AtomicRMWInst *I,
9106f32e7eSjoerg         TargetLoweringBase::AtomicExpansionKind ExpansionKind);
9206f32e7eSjoerg     AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
93*da58b97aSjoerg     bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
9406f32e7eSjoerg     void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
9506f32e7eSjoerg     void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
9606f32e7eSjoerg 
9706f32e7eSjoerg     AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
9806f32e7eSjoerg     static Value *insertRMWCmpXchgLoop(
99*da58b97aSjoerg         IRBuilder<> &Builder, Type *ResultType, Value *Addr, Align AddrAlign,
100*da58b97aSjoerg         AtomicOrdering MemOpOrder, SyncScope::ID SSID,
10106f32e7eSjoerg         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
10206f32e7eSjoerg         CreateCmpXchgInstFun CreateCmpXchg);
10306f32e7eSjoerg     bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
10406f32e7eSjoerg 
10506f32e7eSjoerg     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
10606f32e7eSjoerg     bool isIdempotentRMW(AtomicRMWInst *RMWI);
10706f32e7eSjoerg     bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
10806f32e7eSjoerg 
109*da58b97aSjoerg     bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
11006f32e7eSjoerg                                  Value *PointerOperand, Value *ValueOperand,
11106f32e7eSjoerg                                  Value *CASExpected, AtomicOrdering Ordering,
11206f32e7eSjoerg                                  AtomicOrdering Ordering2,
11306f32e7eSjoerg                                  ArrayRef<RTLIB::Libcall> Libcalls);
11406f32e7eSjoerg     void expandAtomicLoadToLibcall(LoadInst *LI);
11506f32e7eSjoerg     void expandAtomicStoreToLibcall(StoreInst *LI);
11606f32e7eSjoerg     void expandAtomicRMWToLibcall(AtomicRMWInst *I);
11706f32e7eSjoerg     void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
11806f32e7eSjoerg 
11906f32e7eSjoerg     friend bool
12006f32e7eSjoerg     llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
12106f32e7eSjoerg                                    CreateCmpXchgInstFun CreateCmpXchg);
12206f32e7eSjoerg   };
12306f32e7eSjoerg 
12406f32e7eSjoerg } // end anonymous namespace
12506f32e7eSjoerg 
12606f32e7eSjoerg char AtomicExpand::ID = 0;
12706f32e7eSjoerg 
12806f32e7eSjoerg char &llvm::AtomicExpandID = AtomicExpand::ID;
12906f32e7eSjoerg 
13006f32e7eSjoerg INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions",
13106f32e7eSjoerg                 false, false)
13206f32e7eSjoerg 
createAtomicExpandPass()13306f32e7eSjoerg FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
13406f32e7eSjoerg 
13506f32e7eSjoerg // Helper functions to retrieve the size of atomic instructions.
getAtomicOpSize(LoadInst * LI)13606f32e7eSjoerg static unsigned getAtomicOpSize(LoadInst *LI) {
13706f32e7eSjoerg   const DataLayout &DL = LI->getModule()->getDataLayout();
13806f32e7eSjoerg   return DL.getTypeStoreSize(LI->getType());
13906f32e7eSjoerg }
14006f32e7eSjoerg 
getAtomicOpSize(StoreInst * SI)14106f32e7eSjoerg static unsigned getAtomicOpSize(StoreInst *SI) {
14206f32e7eSjoerg   const DataLayout &DL = SI->getModule()->getDataLayout();
14306f32e7eSjoerg   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
14406f32e7eSjoerg }
14506f32e7eSjoerg 
getAtomicOpSize(AtomicRMWInst * RMWI)14606f32e7eSjoerg static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
14706f32e7eSjoerg   const DataLayout &DL = RMWI->getModule()->getDataLayout();
14806f32e7eSjoerg   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
14906f32e7eSjoerg }
15006f32e7eSjoerg 
getAtomicOpSize(AtomicCmpXchgInst * CASI)15106f32e7eSjoerg static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
15206f32e7eSjoerg   const DataLayout &DL = CASI->getModule()->getDataLayout();
15306f32e7eSjoerg   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
15406f32e7eSjoerg }
15506f32e7eSjoerg 
15606f32e7eSjoerg // Determine if a particular atomic operation has a supported size,
15706f32e7eSjoerg // and is of appropriate alignment, to be passed through for target
15806f32e7eSjoerg // lowering. (Versus turning into a __atomic libcall)
15906f32e7eSjoerg template <typename Inst>
atomicSizeSupported(const TargetLowering * TLI,Inst * I)16006f32e7eSjoerg static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
16106f32e7eSjoerg   unsigned Size = getAtomicOpSize(I);
162*da58b97aSjoerg   Align Alignment = I->getAlign();
163*da58b97aSjoerg   return Alignment >= Size &&
164*da58b97aSjoerg          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
16506f32e7eSjoerg }
16606f32e7eSjoerg 
runOnFunction(Function & F)16706f32e7eSjoerg bool AtomicExpand::runOnFunction(Function &F) {
16806f32e7eSjoerg   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
16906f32e7eSjoerg   if (!TPC)
17006f32e7eSjoerg     return false;
17106f32e7eSjoerg 
17206f32e7eSjoerg   auto &TM = TPC->getTM<TargetMachine>();
17306f32e7eSjoerg   if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
17406f32e7eSjoerg     return false;
17506f32e7eSjoerg   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
17606f32e7eSjoerg 
17706f32e7eSjoerg   SmallVector<Instruction *, 1> AtomicInsts;
17806f32e7eSjoerg 
17906f32e7eSjoerg   // Changing control-flow while iterating through it is a bad idea, so gather a
18006f32e7eSjoerg   // list of all atomic instructions before we start.
18106f32e7eSjoerg   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
18206f32e7eSjoerg     Instruction *I = &*II;
18306f32e7eSjoerg     if (I->isAtomic() && !isa<FenceInst>(I))
18406f32e7eSjoerg       AtomicInsts.push_back(I);
18506f32e7eSjoerg   }
18606f32e7eSjoerg 
18706f32e7eSjoerg   bool MadeChange = false;
18806f32e7eSjoerg   for (auto I : AtomicInsts) {
18906f32e7eSjoerg     auto LI = dyn_cast<LoadInst>(I);
19006f32e7eSjoerg     auto SI = dyn_cast<StoreInst>(I);
19106f32e7eSjoerg     auto RMWI = dyn_cast<AtomicRMWInst>(I);
19206f32e7eSjoerg     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
19306f32e7eSjoerg     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
19406f32e7eSjoerg 
19506f32e7eSjoerg     // If the Size/Alignment is not supported, replace with a libcall.
19606f32e7eSjoerg     if (LI) {
19706f32e7eSjoerg       if (!atomicSizeSupported(TLI, LI)) {
19806f32e7eSjoerg         expandAtomicLoadToLibcall(LI);
19906f32e7eSjoerg         MadeChange = true;
20006f32e7eSjoerg         continue;
20106f32e7eSjoerg       }
20206f32e7eSjoerg     } else if (SI) {
20306f32e7eSjoerg       if (!atomicSizeSupported(TLI, SI)) {
20406f32e7eSjoerg         expandAtomicStoreToLibcall(SI);
20506f32e7eSjoerg         MadeChange = true;
20606f32e7eSjoerg         continue;
20706f32e7eSjoerg       }
20806f32e7eSjoerg     } else if (RMWI) {
20906f32e7eSjoerg       if (!atomicSizeSupported(TLI, RMWI)) {
21006f32e7eSjoerg         expandAtomicRMWToLibcall(RMWI);
21106f32e7eSjoerg         MadeChange = true;
21206f32e7eSjoerg         continue;
21306f32e7eSjoerg       }
21406f32e7eSjoerg     } else if (CASI) {
21506f32e7eSjoerg       if (!atomicSizeSupported(TLI, CASI)) {
21606f32e7eSjoerg         expandAtomicCASToLibcall(CASI);
21706f32e7eSjoerg         MadeChange = true;
21806f32e7eSjoerg         continue;
21906f32e7eSjoerg       }
22006f32e7eSjoerg     }
22106f32e7eSjoerg 
22206f32e7eSjoerg     if (TLI->shouldInsertFencesForAtomic(I)) {
22306f32e7eSjoerg       auto FenceOrdering = AtomicOrdering::Monotonic;
22406f32e7eSjoerg       if (LI && isAcquireOrStronger(LI->getOrdering())) {
22506f32e7eSjoerg         FenceOrdering = LI->getOrdering();
22606f32e7eSjoerg         LI->setOrdering(AtomicOrdering::Monotonic);
22706f32e7eSjoerg       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
22806f32e7eSjoerg         FenceOrdering = SI->getOrdering();
22906f32e7eSjoerg         SI->setOrdering(AtomicOrdering::Monotonic);
23006f32e7eSjoerg       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
23106f32e7eSjoerg                           isAcquireOrStronger(RMWI->getOrdering()))) {
23206f32e7eSjoerg         FenceOrdering = RMWI->getOrdering();
23306f32e7eSjoerg         RMWI->setOrdering(AtomicOrdering::Monotonic);
23406f32e7eSjoerg       } else if (CASI &&
23506f32e7eSjoerg                  TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
23606f32e7eSjoerg                      TargetLoweringBase::AtomicExpansionKind::None &&
23706f32e7eSjoerg                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
23806f32e7eSjoerg                   isAcquireOrStronger(CASI->getSuccessOrdering()))) {
23906f32e7eSjoerg         // If a compare and swap is lowered to LL/SC, we can do smarter fence
24006f32e7eSjoerg         // insertion, with a stronger one on the success path than on the
24106f32e7eSjoerg         // failure path. As a result, fence insertion is directly done by
24206f32e7eSjoerg         // expandAtomicCmpXchg in that case.
24306f32e7eSjoerg         FenceOrdering = CASI->getSuccessOrdering();
24406f32e7eSjoerg         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
24506f32e7eSjoerg         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
24606f32e7eSjoerg       }
24706f32e7eSjoerg 
24806f32e7eSjoerg       if (FenceOrdering != AtomicOrdering::Monotonic) {
24906f32e7eSjoerg         MadeChange |= bracketInstWithFences(I, FenceOrdering);
25006f32e7eSjoerg       }
25106f32e7eSjoerg     }
25206f32e7eSjoerg 
25306f32e7eSjoerg     if (LI) {
25406f32e7eSjoerg       if (LI->getType()->isFloatingPointTy()) {
25506f32e7eSjoerg         // TODO: add a TLI hook to control this so that each target can
25606f32e7eSjoerg         // convert to lowering the original type one at a time.
25706f32e7eSjoerg         LI = convertAtomicLoadToIntegerType(LI);
25806f32e7eSjoerg         assert(LI->getType()->isIntegerTy() && "invariant broken");
25906f32e7eSjoerg         MadeChange = true;
26006f32e7eSjoerg       }
26106f32e7eSjoerg 
26206f32e7eSjoerg       MadeChange |= tryExpandAtomicLoad(LI);
26306f32e7eSjoerg     } else if (SI) {
26406f32e7eSjoerg       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
26506f32e7eSjoerg         // TODO: add a TLI hook to control this so that each target can
26606f32e7eSjoerg         // convert to lowering the original type one at a time.
26706f32e7eSjoerg         SI = convertAtomicStoreToIntegerType(SI);
26806f32e7eSjoerg         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
26906f32e7eSjoerg                "invariant broken");
27006f32e7eSjoerg         MadeChange = true;
27106f32e7eSjoerg       }
27206f32e7eSjoerg 
27306f32e7eSjoerg       if (TLI->shouldExpandAtomicStoreInIR(SI))
27406f32e7eSjoerg         MadeChange |= expandAtomicStore(SI);
27506f32e7eSjoerg     } else if (RMWI) {
27606f32e7eSjoerg       // There are two different ways of expanding RMW instructions:
27706f32e7eSjoerg       // - into a load if it is idempotent
27806f32e7eSjoerg       // - into a Cmpxchg/LL-SC loop otherwise
27906f32e7eSjoerg       // we try them in that order.
28006f32e7eSjoerg 
28106f32e7eSjoerg       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
28206f32e7eSjoerg         MadeChange = true;
28306f32e7eSjoerg       } else {
28406f32e7eSjoerg         unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
28506f32e7eSjoerg         unsigned ValueSize = getAtomicOpSize(RMWI);
28606f32e7eSjoerg         AtomicRMWInst::BinOp Op = RMWI->getOperation();
28706f32e7eSjoerg         if (ValueSize < MinCASSize &&
28806f32e7eSjoerg             (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
28906f32e7eSjoerg              Op == AtomicRMWInst::And)) {
29006f32e7eSjoerg           RMWI = widenPartwordAtomicRMW(RMWI);
29106f32e7eSjoerg           MadeChange = true;
29206f32e7eSjoerg         }
29306f32e7eSjoerg 
29406f32e7eSjoerg         MadeChange |= tryExpandAtomicRMW(RMWI);
29506f32e7eSjoerg       }
29606f32e7eSjoerg     } else if (CASI) {
29706f32e7eSjoerg       // TODO: when we're ready to make the change at the IR level, we can
29806f32e7eSjoerg       // extend convertCmpXchgToInteger for floating point too.
29906f32e7eSjoerg       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
30006f32e7eSjoerg              "unimplemented - floating point not legal at IR level");
30106f32e7eSjoerg       if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
30206f32e7eSjoerg         // TODO: add a TLI hook to control this so that each target can
30306f32e7eSjoerg         // convert to lowering the original type one at a time.
30406f32e7eSjoerg         CASI = convertCmpXchgToIntegerType(CASI);
30506f32e7eSjoerg         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
30606f32e7eSjoerg                "invariant broken");
30706f32e7eSjoerg         MadeChange = true;
30806f32e7eSjoerg       }
30906f32e7eSjoerg 
31006f32e7eSjoerg       MadeChange |= tryExpandAtomicCmpXchg(CASI);
31106f32e7eSjoerg     }
31206f32e7eSjoerg   }
31306f32e7eSjoerg   return MadeChange;
31406f32e7eSjoerg }
31506f32e7eSjoerg 
bracketInstWithFences(Instruction * I,AtomicOrdering Order)31606f32e7eSjoerg bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
31706f32e7eSjoerg   IRBuilder<> Builder(I);
31806f32e7eSjoerg 
31906f32e7eSjoerg   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
32006f32e7eSjoerg 
32106f32e7eSjoerg   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
32206f32e7eSjoerg   // We have a guard here because not every atomic operation generates a
32306f32e7eSjoerg   // trailing fence.
32406f32e7eSjoerg   if (TrailingFence)
32506f32e7eSjoerg     TrailingFence->moveAfter(I);
32606f32e7eSjoerg 
32706f32e7eSjoerg   return (LeadingFence || TrailingFence);
32806f32e7eSjoerg }
32906f32e7eSjoerg 
33006f32e7eSjoerg /// Get the iX type with the same bitwidth as T.
getCorrespondingIntegerType(Type * T,const DataLayout & DL)33106f32e7eSjoerg IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
33206f32e7eSjoerg                                                        const DataLayout &DL) {
33306f32e7eSjoerg   EVT VT = TLI->getMemValueType(DL, T);
33406f32e7eSjoerg   unsigned BitWidth = VT.getStoreSizeInBits();
33506f32e7eSjoerg   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
33606f32e7eSjoerg   return IntegerType::get(T->getContext(), BitWidth);
33706f32e7eSjoerg }
33806f32e7eSjoerg 
33906f32e7eSjoerg /// Convert an atomic load of a non-integral type to an integer load of the
34006f32e7eSjoerg /// equivalent bitwidth.  See the function comment on
34106f32e7eSjoerg /// convertAtomicStoreToIntegerType for background.
convertAtomicLoadToIntegerType(LoadInst * LI)34206f32e7eSjoerg LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
34306f32e7eSjoerg   auto *M = LI->getModule();
34406f32e7eSjoerg   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
34506f32e7eSjoerg                                             M->getDataLayout());
34606f32e7eSjoerg 
34706f32e7eSjoerg   IRBuilder<> Builder(LI);
34806f32e7eSjoerg 
34906f32e7eSjoerg   Value *Addr = LI->getPointerOperand();
35006f32e7eSjoerg   Type *PT = PointerType::get(NewTy,
35106f32e7eSjoerg                               Addr->getType()->getPointerAddressSpace());
35206f32e7eSjoerg   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
35306f32e7eSjoerg 
35406f32e7eSjoerg   auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
355*da58b97aSjoerg   NewLI->setAlignment(LI->getAlign());
35606f32e7eSjoerg   NewLI->setVolatile(LI->isVolatile());
35706f32e7eSjoerg   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
35806f32e7eSjoerg   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
35906f32e7eSjoerg 
36006f32e7eSjoerg   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
36106f32e7eSjoerg   LI->replaceAllUsesWith(NewVal);
36206f32e7eSjoerg   LI->eraseFromParent();
36306f32e7eSjoerg   return NewLI;
36406f32e7eSjoerg }
36506f32e7eSjoerg 
tryExpandAtomicLoad(LoadInst * LI)36606f32e7eSjoerg bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
36706f32e7eSjoerg   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
36806f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::None:
36906f32e7eSjoerg     return false;
37006f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::LLSC:
37106f32e7eSjoerg     expandAtomicOpToLLSC(
372*da58b97aSjoerg         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
373*da58b97aSjoerg         LI->getOrdering(),
37406f32e7eSjoerg         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
37506f32e7eSjoerg     return true;
37606f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
37706f32e7eSjoerg     return expandAtomicLoadToLL(LI);
37806f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
37906f32e7eSjoerg     return expandAtomicLoadToCmpXchg(LI);
38006f32e7eSjoerg   default:
38106f32e7eSjoerg     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
38206f32e7eSjoerg   }
38306f32e7eSjoerg }
38406f32e7eSjoerg 
expandAtomicLoadToLL(LoadInst * LI)38506f32e7eSjoerg bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
38606f32e7eSjoerg   IRBuilder<> Builder(LI);
38706f32e7eSjoerg 
38806f32e7eSjoerg   // On some architectures, load-linked instructions are atomic for larger
38906f32e7eSjoerg   // sizes than normal loads. For example, the only 64-bit load guaranteed
39006f32e7eSjoerg   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
39106f32e7eSjoerg   Value *Val =
39206f32e7eSjoerg       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
39306f32e7eSjoerg   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
39406f32e7eSjoerg 
39506f32e7eSjoerg   LI->replaceAllUsesWith(Val);
39606f32e7eSjoerg   LI->eraseFromParent();
39706f32e7eSjoerg 
39806f32e7eSjoerg   return true;
39906f32e7eSjoerg }
40006f32e7eSjoerg 
expandAtomicLoadToCmpXchg(LoadInst * LI)40106f32e7eSjoerg bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
40206f32e7eSjoerg   IRBuilder<> Builder(LI);
40306f32e7eSjoerg   AtomicOrdering Order = LI->getOrdering();
40406f32e7eSjoerg   if (Order == AtomicOrdering::Unordered)
40506f32e7eSjoerg     Order = AtomicOrdering::Monotonic;
40606f32e7eSjoerg 
40706f32e7eSjoerg   Value *Addr = LI->getPointerOperand();
40806f32e7eSjoerg   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
40906f32e7eSjoerg   Constant *DummyVal = Constant::getNullValue(Ty);
41006f32e7eSjoerg 
41106f32e7eSjoerg   Value *Pair = Builder.CreateAtomicCmpXchg(
412*da58b97aSjoerg       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
41306f32e7eSjoerg       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
41406f32e7eSjoerg   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
41506f32e7eSjoerg 
41606f32e7eSjoerg   LI->replaceAllUsesWith(Loaded);
41706f32e7eSjoerg   LI->eraseFromParent();
41806f32e7eSjoerg 
41906f32e7eSjoerg   return true;
42006f32e7eSjoerg }
42106f32e7eSjoerg 
42206f32e7eSjoerg /// Convert an atomic store of a non-integral type to an integer store of the
42306f32e7eSjoerg /// equivalent bitwidth.  We used to not support floating point or vector
42406f32e7eSjoerg /// atomics in the IR at all.  The backends learned to deal with the bitcast
42506f32e7eSjoerg /// idiom because that was the only way of expressing the notion of a atomic
42606f32e7eSjoerg /// float or vector store.  The long term plan is to teach each backend to
42706f32e7eSjoerg /// instruction select from the original atomic store, but as a migration
42806f32e7eSjoerg /// mechanism, we convert back to the old format which the backends understand.
42906f32e7eSjoerg /// Each backend will need individual work to recognize the new format.
convertAtomicStoreToIntegerType(StoreInst * SI)43006f32e7eSjoerg StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
43106f32e7eSjoerg   IRBuilder<> Builder(SI);
43206f32e7eSjoerg   auto *M = SI->getModule();
43306f32e7eSjoerg   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
43406f32e7eSjoerg                                             M->getDataLayout());
43506f32e7eSjoerg   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
43606f32e7eSjoerg 
43706f32e7eSjoerg   Value *Addr = SI->getPointerOperand();
43806f32e7eSjoerg   Type *PT = PointerType::get(NewTy,
43906f32e7eSjoerg                               Addr->getType()->getPointerAddressSpace());
44006f32e7eSjoerg   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
44106f32e7eSjoerg 
44206f32e7eSjoerg   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
443*da58b97aSjoerg   NewSI->setAlignment(SI->getAlign());
44406f32e7eSjoerg   NewSI->setVolatile(SI->isVolatile());
44506f32e7eSjoerg   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
44606f32e7eSjoerg   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
44706f32e7eSjoerg   SI->eraseFromParent();
44806f32e7eSjoerg   return NewSI;
44906f32e7eSjoerg }
45006f32e7eSjoerg 
expandAtomicStore(StoreInst * SI)45106f32e7eSjoerg bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
45206f32e7eSjoerg   // This function is only called on atomic stores that are too large to be
45306f32e7eSjoerg   // atomic if implemented as a native store. So we replace them by an
45406f32e7eSjoerg   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
45506f32e7eSjoerg   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
45606f32e7eSjoerg   // It is the responsibility of the target to only signal expansion via
45706f32e7eSjoerg   // shouldExpandAtomicRMW in cases where this is required and possible.
45806f32e7eSjoerg   IRBuilder<> Builder(SI);
459*da58b97aSjoerg   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
460*da58b97aSjoerg       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
461*da58b97aSjoerg       SI->getAlign(), SI->getOrdering());
46206f32e7eSjoerg   SI->eraseFromParent();
46306f32e7eSjoerg 
46406f32e7eSjoerg   // Now we have an appropriate swap instruction, lower it as usual.
46506f32e7eSjoerg   return tryExpandAtomicRMW(AI);
46606f32e7eSjoerg }
46706f32e7eSjoerg 
createCmpXchgInstFun(IRBuilder<> & Builder,Value * Addr,Value * Loaded,Value * NewVal,Align AddrAlign,AtomicOrdering MemOpOrder,SyncScope::ID SSID,Value * & Success,Value * & NewLoaded)46806f32e7eSjoerg static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
469*da58b97aSjoerg                                  Value *Loaded, Value *NewVal, Align AddrAlign,
470*da58b97aSjoerg                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
47106f32e7eSjoerg                                  Value *&Success, Value *&NewLoaded) {
47206f32e7eSjoerg   Type *OrigTy = NewVal->getType();
47306f32e7eSjoerg 
47406f32e7eSjoerg   // This code can go away when cmpxchg supports FP types.
47506f32e7eSjoerg   bool NeedBitcast = OrigTy->isFloatingPointTy();
47606f32e7eSjoerg   if (NeedBitcast) {
47706f32e7eSjoerg     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
47806f32e7eSjoerg     unsigned AS = Addr->getType()->getPointerAddressSpace();
47906f32e7eSjoerg     Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
48006f32e7eSjoerg     NewVal = Builder.CreateBitCast(NewVal, IntTy);
48106f32e7eSjoerg     Loaded = Builder.CreateBitCast(Loaded, IntTy);
48206f32e7eSjoerg   }
48306f32e7eSjoerg 
48406f32e7eSjoerg   Value *Pair = Builder.CreateAtomicCmpXchg(
485*da58b97aSjoerg       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
486*da58b97aSjoerg       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
48706f32e7eSjoerg   Success = Builder.CreateExtractValue(Pair, 1, "success");
48806f32e7eSjoerg   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
48906f32e7eSjoerg 
49006f32e7eSjoerg   if (NeedBitcast)
49106f32e7eSjoerg     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
49206f32e7eSjoerg }
49306f32e7eSjoerg 
49406f32e7eSjoerg /// Emit IR to implement the given atomicrmw operation on values in registers,
49506f32e7eSjoerg /// returning the new value.
performAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Inc)49606f32e7eSjoerg static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
49706f32e7eSjoerg                               Value *Loaded, Value *Inc) {
49806f32e7eSjoerg   Value *NewVal;
49906f32e7eSjoerg   switch (Op) {
50006f32e7eSjoerg   case AtomicRMWInst::Xchg:
50106f32e7eSjoerg     return Inc;
50206f32e7eSjoerg   case AtomicRMWInst::Add:
50306f32e7eSjoerg     return Builder.CreateAdd(Loaded, Inc, "new");
50406f32e7eSjoerg   case AtomicRMWInst::Sub:
50506f32e7eSjoerg     return Builder.CreateSub(Loaded, Inc, "new");
50606f32e7eSjoerg   case AtomicRMWInst::And:
50706f32e7eSjoerg     return Builder.CreateAnd(Loaded, Inc, "new");
50806f32e7eSjoerg   case AtomicRMWInst::Nand:
50906f32e7eSjoerg     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
51006f32e7eSjoerg   case AtomicRMWInst::Or:
51106f32e7eSjoerg     return Builder.CreateOr(Loaded, Inc, "new");
51206f32e7eSjoerg   case AtomicRMWInst::Xor:
51306f32e7eSjoerg     return Builder.CreateXor(Loaded, Inc, "new");
51406f32e7eSjoerg   case AtomicRMWInst::Max:
51506f32e7eSjoerg     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
51606f32e7eSjoerg     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
51706f32e7eSjoerg   case AtomicRMWInst::Min:
51806f32e7eSjoerg     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
51906f32e7eSjoerg     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
52006f32e7eSjoerg   case AtomicRMWInst::UMax:
52106f32e7eSjoerg     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
52206f32e7eSjoerg     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
52306f32e7eSjoerg   case AtomicRMWInst::UMin:
52406f32e7eSjoerg     NewVal = Builder.CreateICmpULE(Loaded, Inc);
52506f32e7eSjoerg     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
52606f32e7eSjoerg   case AtomicRMWInst::FAdd:
52706f32e7eSjoerg     return Builder.CreateFAdd(Loaded, Inc, "new");
52806f32e7eSjoerg   case AtomicRMWInst::FSub:
52906f32e7eSjoerg     return Builder.CreateFSub(Loaded, Inc, "new");
53006f32e7eSjoerg   default:
53106f32e7eSjoerg     llvm_unreachable("Unknown atomic op");
53206f32e7eSjoerg   }
53306f32e7eSjoerg }
53406f32e7eSjoerg 
tryExpandAtomicRMW(AtomicRMWInst * AI)53506f32e7eSjoerg bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
53606f32e7eSjoerg   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
53706f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::None:
53806f32e7eSjoerg     return false;
53906f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
54006f32e7eSjoerg     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
54106f32e7eSjoerg     unsigned ValueSize = getAtomicOpSize(AI);
54206f32e7eSjoerg     if (ValueSize < MinCASSize) {
543*da58b97aSjoerg       expandPartwordAtomicRMW(AI,
544*da58b97aSjoerg                               TargetLoweringBase::AtomicExpansionKind::LLSC);
54506f32e7eSjoerg     } else {
54606f32e7eSjoerg       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
54706f32e7eSjoerg         return performAtomicOp(AI->getOperation(), Builder, Loaded,
54806f32e7eSjoerg                                AI->getValOperand());
54906f32e7eSjoerg       };
55006f32e7eSjoerg       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
551*da58b97aSjoerg                            AI->getAlign(), AI->getOrdering(), PerformOp);
55206f32e7eSjoerg     }
55306f32e7eSjoerg     return true;
55406f32e7eSjoerg   }
55506f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
55606f32e7eSjoerg     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
55706f32e7eSjoerg     unsigned ValueSize = getAtomicOpSize(AI);
55806f32e7eSjoerg     if (ValueSize < MinCASSize) {
55906f32e7eSjoerg       // TODO: Handle atomicrmw fadd/fsub
56006f32e7eSjoerg       if (AI->getType()->isFloatingPointTy())
56106f32e7eSjoerg         return false;
56206f32e7eSjoerg 
56306f32e7eSjoerg       expandPartwordAtomicRMW(AI,
56406f32e7eSjoerg                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
56506f32e7eSjoerg     } else {
56606f32e7eSjoerg       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
56706f32e7eSjoerg     }
56806f32e7eSjoerg     return true;
56906f32e7eSjoerg   }
57006f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
57106f32e7eSjoerg     expandAtomicRMWToMaskedIntrinsic(AI);
57206f32e7eSjoerg     return true;
57306f32e7eSjoerg   }
57406f32e7eSjoerg   default:
57506f32e7eSjoerg     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
57606f32e7eSjoerg   }
57706f32e7eSjoerg }
57806f32e7eSjoerg 
57906f32e7eSjoerg namespace {
58006f32e7eSjoerg 
58106f32e7eSjoerg struct PartwordMaskValues {
582*da58b97aSjoerg   // These three fields are guaranteed to be set by createMaskInstrs.
583*da58b97aSjoerg   Type *WordType = nullptr;
584*da58b97aSjoerg   Type *ValueType = nullptr;
585*da58b97aSjoerg   Value *AlignedAddr = nullptr;
586*da58b97aSjoerg   Align AlignedAddrAlignment;
587*da58b97aSjoerg   // The remaining fields can be null.
588*da58b97aSjoerg   Value *ShiftAmt = nullptr;
589*da58b97aSjoerg   Value *Mask = nullptr;
590*da58b97aSjoerg   Value *Inv_Mask = nullptr;
59106f32e7eSjoerg };
59206f32e7eSjoerg 
593*da58b97aSjoerg LLVM_ATTRIBUTE_UNUSED
operator <<(raw_ostream & O,const PartwordMaskValues & PMV)594*da58b97aSjoerg raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
595*da58b97aSjoerg   auto PrintObj = [&O](auto *V) {
596*da58b97aSjoerg     if (V)
597*da58b97aSjoerg       O << *V;
598*da58b97aSjoerg     else
599*da58b97aSjoerg       O << "nullptr";
600*da58b97aSjoerg     O << '\n';
601*da58b97aSjoerg   };
602*da58b97aSjoerg   O << "PartwordMaskValues {\n";
603*da58b97aSjoerg   O << "  WordType: ";
604*da58b97aSjoerg   PrintObj(PMV.WordType);
605*da58b97aSjoerg   O << "  ValueType: ";
606*da58b97aSjoerg   PrintObj(PMV.ValueType);
607*da58b97aSjoerg   O << "  AlignedAddr: ";
608*da58b97aSjoerg   PrintObj(PMV.AlignedAddr);
609*da58b97aSjoerg   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
610*da58b97aSjoerg   O << "  ShiftAmt: ";
611*da58b97aSjoerg   PrintObj(PMV.ShiftAmt);
612*da58b97aSjoerg   O << "  Mask: ";
613*da58b97aSjoerg   PrintObj(PMV.Mask);
614*da58b97aSjoerg   O << "  Inv_Mask: ";
615*da58b97aSjoerg   PrintObj(PMV.Inv_Mask);
616*da58b97aSjoerg   O << "}\n";
617*da58b97aSjoerg   return O;
618*da58b97aSjoerg }
619*da58b97aSjoerg 
62006f32e7eSjoerg } // end anonymous namespace
62106f32e7eSjoerg 
62206f32e7eSjoerg /// This is a helper function which builds instructions to provide
62306f32e7eSjoerg /// values necessary for partword atomic operations. It takes an
62406f32e7eSjoerg /// incoming address, Addr, and ValueType, and constructs the address,
62506f32e7eSjoerg /// shift-amounts and masks needed to work with a larger value of size
62606f32e7eSjoerg /// WordSize.
62706f32e7eSjoerg ///
62806f32e7eSjoerg /// AlignedAddr: Addr rounded down to a multiple of WordSize
62906f32e7eSjoerg ///
63006f32e7eSjoerg /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
63106f32e7eSjoerg ///           from AlignAddr for it to have the same value as if
63206f32e7eSjoerg ///           ValueType was loaded from Addr.
63306f32e7eSjoerg ///
63406f32e7eSjoerg /// Mask: Value to mask with the value loaded from AlignAddr to
63506f32e7eSjoerg ///       include only the part that would've been loaded from Addr.
63606f32e7eSjoerg ///
63706f32e7eSjoerg /// Inv_Mask: The inverse of Mask.
createMaskInstrs(IRBuilder<> & Builder,Instruction * I,Type * ValueType,Value * Addr,Align AddrAlign,unsigned MinWordSize)63806f32e7eSjoerg static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
63906f32e7eSjoerg                                            Type *ValueType, Value *Addr,
640*da58b97aSjoerg                                            Align AddrAlign,
641*da58b97aSjoerg                                            unsigned MinWordSize) {
642*da58b97aSjoerg   PartwordMaskValues PMV;
64306f32e7eSjoerg 
64406f32e7eSjoerg   Module *M = I->getModule();
645*da58b97aSjoerg   LLVMContext &Ctx = M->getContext();
64606f32e7eSjoerg   const DataLayout &DL = M->getDataLayout();
64706f32e7eSjoerg   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
64806f32e7eSjoerg 
649*da58b97aSjoerg   PMV.ValueType = ValueType;
650*da58b97aSjoerg   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
651*da58b97aSjoerg                                          : ValueType;
652*da58b97aSjoerg   if (PMV.ValueType == PMV.WordType) {
653*da58b97aSjoerg     PMV.AlignedAddr = Addr;
654*da58b97aSjoerg     PMV.AlignedAddrAlignment = AddrAlign;
655*da58b97aSjoerg     return PMV;
65606f32e7eSjoerg   }
65706f32e7eSjoerg 
658*da58b97aSjoerg   assert(ValueSize < MinWordSize);
65906f32e7eSjoerg 
660*da58b97aSjoerg   Type *WordPtrType =
661*da58b97aSjoerg       PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
662*da58b97aSjoerg 
663*da58b97aSjoerg   // TODO: we could skip some of this if AddrAlign >= MinWordSize.
664*da58b97aSjoerg   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
665*da58b97aSjoerg   PMV.AlignedAddr = Builder.CreateIntToPtr(
666*da58b97aSjoerg       Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
667*da58b97aSjoerg       "AlignedAddr");
668*da58b97aSjoerg   PMV.AlignedAddrAlignment = Align(MinWordSize);
669*da58b97aSjoerg 
670*da58b97aSjoerg   Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
671*da58b97aSjoerg   if (DL.isLittleEndian()) {
672*da58b97aSjoerg     // turn bytes into bits
673*da58b97aSjoerg     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
674*da58b97aSjoerg   } else {
675*da58b97aSjoerg     // turn bytes into bits, and count from the other side.
676*da58b97aSjoerg     PMV.ShiftAmt = Builder.CreateShl(
677*da58b97aSjoerg         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
678*da58b97aSjoerg   }
679*da58b97aSjoerg 
680*da58b97aSjoerg   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
681*da58b97aSjoerg   PMV.Mask = Builder.CreateShl(
682*da58b97aSjoerg       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
683*da58b97aSjoerg       "Mask");
684*da58b97aSjoerg   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
685*da58b97aSjoerg   return PMV;
686*da58b97aSjoerg }
687*da58b97aSjoerg 
extractMaskedValue(IRBuilder<> & Builder,Value * WideWord,const PartwordMaskValues & PMV)688*da58b97aSjoerg static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
689*da58b97aSjoerg                                  const PartwordMaskValues &PMV) {
690*da58b97aSjoerg   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
691*da58b97aSjoerg   if (PMV.WordType == PMV.ValueType)
692*da58b97aSjoerg     return WideWord;
693*da58b97aSjoerg 
694*da58b97aSjoerg   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
695*da58b97aSjoerg   Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
696*da58b97aSjoerg   return Trunc;
697*da58b97aSjoerg }
698*da58b97aSjoerg 
insertMaskedValue(IRBuilder<> & Builder,Value * WideWord,Value * Updated,const PartwordMaskValues & PMV)699*da58b97aSjoerg static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
700*da58b97aSjoerg                                 Value *Updated, const PartwordMaskValues &PMV) {
701*da58b97aSjoerg   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
702*da58b97aSjoerg   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
703*da58b97aSjoerg   if (PMV.WordType == PMV.ValueType)
704*da58b97aSjoerg     return Updated;
705*da58b97aSjoerg 
706*da58b97aSjoerg   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
707*da58b97aSjoerg   Value *Shift =
708*da58b97aSjoerg       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
709*da58b97aSjoerg   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
710*da58b97aSjoerg   Value *Or = Builder.CreateOr(And, Shift, "inserted");
711*da58b97aSjoerg   return Or;
71206f32e7eSjoerg }
71306f32e7eSjoerg 
71406f32e7eSjoerg /// Emit IR to implement a masked version of a given atomicrmw
71506f32e7eSjoerg /// operation. (That is, only the bits under the Mask should be
71606f32e7eSjoerg /// affected by the operation)
performMaskedAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Shifted_Inc,Value * Inc,const PartwordMaskValues & PMV)71706f32e7eSjoerg static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
71806f32e7eSjoerg                                     IRBuilder<> &Builder, Value *Loaded,
71906f32e7eSjoerg                                     Value *Shifted_Inc, Value *Inc,
72006f32e7eSjoerg                                     const PartwordMaskValues &PMV) {
72106f32e7eSjoerg   // TODO: update to use
72206f32e7eSjoerg   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
72306f32e7eSjoerg   // to merge bits from two values without requiring PMV.Inv_Mask.
72406f32e7eSjoerg   switch (Op) {
72506f32e7eSjoerg   case AtomicRMWInst::Xchg: {
72606f32e7eSjoerg     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
72706f32e7eSjoerg     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
72806f32e7eSjoerg     return FinalVal;
72906f32e7eSjoerg   }
73006f32e7eSjoerg   case AtomicRMWInst::Or:
73106f32e7eSjoerg   case AtomicRMWInst::Xor:
73206f32e7eSjoerg   case AtomicRMWInst::And:
73306f32e7eSjoerg     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
73406f32e7eSjoerg   case AtomicRMWInst::Add:
73506f32e7eSjoerg   case AtomicRMWInst::Sub:
73606f32e7eSjoerg   case AtomicRMWInst::Nand: {
73706f32e7eSjoerg     // The other arithmetic ops need to be masked into place.
73806f32e7eSjoerg     Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
73906f32e7eSjoerg     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
74006f32e7eSjoerg     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
74106f32e7eSjoerg     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
74206f32e7eSjoerg     return FinalVal;
74306f32e7eSjoerg   }
74406f32e7eSjoerg   case AtomicRMWInst::Max:
74506f32e7eSjoerg   case AtomicRMWInst::Min:
74606f32e7eSjoerg   case AtomicRMWInst::UMax:
74706f32e7eSjoerg   case AtomicRMWInst::UMin: {
74806f32e7eSjoerg     // Finally, comparison ops will operate on the full value, so
74906f32e7eSjoerg     // truncate down to the original size, and expand out again after
75006f32e7eSjoerg     // doing the operation.
751*da58b97aSjoerg     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
752*da58b97aSjoerg     Value *NewVal = performAtomicOp(Op, Builder, Loaded_Extract, Inc);
753*da58b97aSjoerg     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
75406f32e7eSjoerg     return FinalVal;
75506f32e7eSjoerg   }
75606f32e7eSjoerg   default:
75706f32e7eSjoerg     llvm_unreachable("Unknown atomic op");
75806f32e7eSjoerg   }
75906f32e7eSjoerg }
76006f32e7eSjoerg 
76106f32e7eSjoerg /// Expand a sub-word atomicrmw operation into an appropriate
76206f32e7eSjoerg /// word-sized operation.
76306f32e7eSjoerg ///
76406f32e7eSjoerg /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
76506f32e7eSjoerg /// way as a typical atomicrmw expansion. The only difference here is
766*da58b97aSjoerg /// that the operation inside of the loop may operate upon only a
76706f32e7eSjoerg /// part of the value.
expandPartwordAtomicRMW(AtomicRMWInst * AI,TargetLoweringBase::AtomicExpansionKind ExpansionKind)76806f32e7eSjoerg void AtomicExpand::expandPartwordAtomicRMW(
76906f32e7eSjoerg     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
77006f32e7eSjoerg   AtomicOrdering MemOpOrder = AI->getOrdering();
771*da58b97aSjoerg   SyncScope::ID SSID = AI->getSyncScopeID();
77206f32e7eSjoerg 
77306f32e7eSjoerg   IRBuilder<> Builder(AI);
77406f32e7eSjoerg 
77506f32e7eSjoerg   PartwordMaskValues PMV =
77606f32e7eSjoerg       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
777*da58b97aSjoerg                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
77806f32e7eSjoerg 
77906f32e7eSjoerg   Value *ValOperand_Shifted =
78006f32e7eSjoerg       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
78106f32e7eSjoerg                         PMV.ShiftAmt, "ValOperand_Shifted");
78206f32e7eSjoerg 
78306f32e7eSjoerg   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
78406f32e7eSjoerg     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
78506f32e7eSjoerg                                  ValOperand_Shifted, AI->getValOperand(), PMV);
78606f32e7eSjoerg   };
78706f32e7eSjoerg 
788*da58b97aSjoerg   Value *OldResult;
789*da58b97aSjoerg   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
790*da58b97aSjoerg     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
791*da58b97aSjoerg                                      PMV.AlignedAddrAlignment, MemOpOrder,
792*da58b97aSjoerg                                      SSID, PerformPartwordOp,
793*da58b97aSjoerg                                      createCmpXchgInstFun);
794*da58b97aSjoerg   } else {
795*da58b97aSjoerg     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
796*da58b97aSjoerg     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
797*da58b97aSjoerg                                   PMV.AlignedAddrAlignment, MemOpOrder,
798*da58b97aSjoerg                                   PerformPartwordOp);
799*da58b97aSjoerg   }
800*da58b97aSjoerg 
801*da58b97aSjoerg   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
80206f32e7eSjoerg   AI->replaceAllUsesWith(FinalOldResult);
80306f32e7eSjoerg   AI->eraseFromParent();
80406f32e7eSjoerg }
80506f32e7eSjoerg 
80606f32e7eSjoerg // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
widenPartwordAtomicRMW(AtomicRMWInst * AI)80706f32e7eSjoerg AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
80806f32e7eSjoerg   IRBuilder<> Builder(AI);
80906f32e7eSjoerg   AtomicRMWInst::BinOp Op = AI->getOperation();
81006f32e7eSjoerg 
81106f32e7eSjoerg   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
81206f32e7eSjoerg           Op == AtomicRMWInst::And) &&
81306f32e7eSjoerg          "Unable to widen operation");
81406f32e7eSjoerg 
81506f32e7eSjoerg   PartwordMaskValues PMV =
81606f32e7eSjoerg       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
817*da58b97aSjoerg                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
81806f32e7eSjoerg 
81906f32e7eSjoerg   Value *ValOperand_Shifted =
82006f32e7eSjoerg       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
82106f32e7eSjoerg                         PMV.ShiftAmt, "ValOperand_Shifted");
82206f32e7eSjoerg 
82306f32e7eSjoerg   Value *NewOperand;
82406f32e7eSjoerg 
82506f32e7eSjoerg   if (Op == AtomicRMWInst::And)
82606f32e7eSjoerg     NewOperand =
82706f32e7eSjoerg         Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
82806f32e7eSjoerg   else
82906f32e7eSjoerg     NewOperand = ValOperand_Shifted;
83006f32e7eSjoerg 
831*da58b97aSjoerg   AtomicRMWInst *NewAI =
832*da58b97aSjoerg       Builder.CreateAtomicRMW(Op, PMV.AlignedAddr, NewOperand,
833*da58b97aSjoerg                               PMV.AlignedAddrAlignment, AI->getOrdering());
83406f32e7eSjoerg 
835*da58b97aSjoerg   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
83606f32e7eSjoerg   AI->replaceAllUsesWith(FinalOldResult);
83706f32e7eSjoerg   AI->eraseFromParent();
83806f32e7eSjoerg   return NewAI;
83906f32e7eSjoerg }
84006f32e7eSjoerg 
expandPartwordCmpXchg(AtomicCmpXchgInst * CI)841*da58b97aSjoerg bool AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
84206f32e7eSjoerg   // The basic idea here is that we're expanding a cmpxchg of a
84306f32e7eSjoerg   // smaller memory size up to a word-sized cmpxchg. To do this, we
84406f32e7eSjoerg   // need to add a retry-loop for strong cmpxchg, so that
84506f32e7eSjoerg   // modifications to other parts of the word don't cause a spurious
84606f32e7eSjoerg   // failure.
84706f32e7eSjoerg 
84806f32e7eSjoerg   // This generates code like the following:
84906f32e7eSjoerg   //     [[Setup mask values PMV.*]]
85006f32e7eSjoerg   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
85106f32e7eSjoerg   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
85206f32e7eSjoerg   //     %InitLoaded = load i32* %addr
85306f32e7eSjoerg   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
85406f32e7eSjoerg   //     br partword.cmpxchg.loop
85506f32e7eSjoerg   // partword.cmpxchg.loop:
85606f32e7eSjoerg   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
85706f32e7eSjoerg   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
85806f32e7eSjoerg   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
85906f32e7eSjoerg   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
86006f32e7eSjoerg   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
86106f32e7eSjoerg   //        i32 %FullWord_NewVal success_ordering failure_ordering
86206f32e7eSjoerg   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
86306f32e7eSjoerg   //     %Success = extractvalue { i32, i1 } %NewCI, 1
86406f32e7eSjoerg   //     br i1 %Success, label %partword.cmpxchg.end,
86506f32e7eSjoerg   //        label %partword.cmpxchg.failure
86606f32e7eSjoerg   // partword.cmpxchg.failure:
86706f32e7eSjoerg   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
86806f32e7eSjoerg   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
86906f32e7eSjoerg   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
87006f32e7eSjoerg   //         label %partword.cmpxchg.end
87106f32e7eSjoerg   // partword.cmpxchg.end:
87206f32e7eSjoerg   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
87306f32e7eSjoerg   //    %FinalOldVal = trunc i32 %tmp1 to i8
87406f32e7eSjoerg   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
87506f32e7eSjoerg   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
87606f32e7eSjoerg 
87706f32e7eSjoerg   Value *Addr = CI->getPointerOperand();
87806f32e7eSjoerg   Value *Cmp = CI->getCompareOperand();
87906f32e7eSjoerg   Value *NewVal = CI->getNewValOperand();
88006f32e7eSjoerg 
88106f32e7eSjoerg   BasicBlock *BB = CI->getParent();
88206f32e7eSjoerg   Function *F = BB->getParent();
88306f32e7eSjoerg   IRBuilder<> Builder(CI);
88406f32e7eSjoerg   LLVMContext &Ctx = Builder.getContext();
88506f32e7eSjoerg 
88606f32e7eSjoerg   BasicBlock *EndBB =
88706f32e7eSjoerg       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
88806f32e7eSjoerg   auto FailureBB =
88906f32e7eSjoerg       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
89006f32e7eSjoerg   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
89106f32e7eSjoerg 
89206f32e7eSjoerg   // The split call above "helpfully" added a branch at the end of BB
89306f32e7eSjoerg   // (to the wrong place).
89406f32e7eSjoerg   std::prev(BB->end())->eraseFromParent();
89506f32e7eSjoerg   Builder.SetInsertPoint(BB);
89606f32e7eSjoerg 
897*da58b97aSjoerg   PartwordMaskValues PMV =
898*da58b97aSjoerg       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
899*da58b97aSjoerg                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
90006f32e7eSjoerg 
90106f32e7eSjoerg   // Shift the incoming values over, into the right location in the word.
90206f32e7eSjoerg   Value *NewVal_Shifted =
90306f32e7eSjoerg       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
90406f32e7eSjoerg   Value *Cmp_Shifted =
90506f32e7eSjoerg       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
90606f32e7eSjoerg 
90706f32e7eSjoerg   // Load the entire current word, and mask into place the expected and new
90806f32e7eSjoerg   // values
90906f32e7eSjoerg   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
91006f32e7eSjoerg   InitLoaded->setVolatile(CI->isVolatile());
91106f32e7eSjoerg   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
91206f32e7eSjoerg   Builder.CreateBr(LoopBB);
91306f32e7eSjoerg 
91406f32e7eSjoerg   // partword.cmpxchg.loop:
91506f32e7eSjoerg   Builder.SetInsertPoint(LoopBB);
91606f32e7eSjoerg   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
91706f32e7eSjoerg   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
91806f32e7eSjoerg 
91906f32e7eSjoerg   // Mask/Or the expected and new values into place in the loaded word.
92006f32e7eSjoerg   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
92106f32e7eSjoerg   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
92206f32e7eSjoerg   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
923*da58b97aSjoerg       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
924*da58b97aSjoerg       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
92506f32e7eSjoerg   NewCI->setVolatile(CI->isVolatile());
92606f32e7eSjoerg   // When we're building a strong cmpxchg, we need a loop, so you
92706f32e7eSjoerg   // might think we could use a weak cmpxchg inside. But, using strong
92806f32e7eSjoerg   // allows the below comparison for ShouldContinue, and we're
92906f32e7eSjoerg   // expecting the underlying cmpxchg to be a machine instruction,
93006f32e7eSjoerg   // which is strong anyways.
93106f32e7eSjoerg   NewCI->setWeak(CI->isWeak());
93206f32e7eSjoerg 
93306f32e7eSjoerg   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
93406f32e7eSjoerg   Value *Success = Builder.CreateExtractValue(NewCI, 1);
93506f32e7eSjoerg 
93606f32e7eSjoerg   if (CI->isWeak())
93706f32e7eSjoerg     Builder.CreateBr(EndBB);
93806f32e7eSjoerg   else
93906f32e7eSjoerg     Builder.CreateCondBr(Success, EndBB, FailureBB);
94006f32e7eSjoerg 
94106f32e7eSjoerg   // partword.cmpxchg.failure:
94206f32e7eSjoerg   Builder.SetInsertPoint(FailureBB);
94306f32e7eSjoerg   // Upon failure, verify that the masked-out part of the loaded value
94406f32e7eSjoerg   // has been modified.  If it didn't, abort the cmpxchg, since the
94506f32e7eSjoerg   // masked-in part must've.
94606f32e7eSjoerg   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
94706f32e7eSjoerg   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
94806f32e7eSjoerg   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
94906f32e7eSjoerg 
95006f32e7eSjoerg   // Add the second value to the phi from above
95106f32e7eSjoerg   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
95206f32e7eSjoerg 
95306f32e7eSjoerg   // partword.cmpxchg.end:
95406f32e7eSjoerg   Builder.SetInsertPoint(CI);
95506f32e7eSjoerg 
956*da58b97aSjoerg   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
95706f32e7eSjoerg   Value *Res = UndefValue::get(CI->getType());
95806f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
95906f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, Success, 1);
96006f32e7eSjoerg 
96106f32e7eSjoerg   CI->replaceAllUsesWith(Res);
96206f32e7eSjoerg   CI->eraseFromParent();
963*da58b97aSjoerg   return true;
96406f32e7eSjoerg }
96506f32e7eSjoerg 
expandAtomicOpToLLSC(Instruction * I,Type * ResultType,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)96606f32e7eSjoerg void AtomicExpand::expandAtomicOpToLLSC(
967*da58b97aSjoerg     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
968*da58b97aSjoerg     AtomicOrdering MemOpOrder,
96906f32e7eSjoerg     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
97006f32e7eSjoerg   IRBuilder<> Builder(I);
971*da58b97aSjoerg   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
972*da58b97aSjoerg                                     MemOpOrder, PerformOp);
97306f32e7eSjoerg 
97406f32e7eSjoerg   I->replaceAllUsesWith(Loaded);
97506f32e7eSjoerg   I->eraseFromParent();
97606f32e7eSjoerg }
97706f32e7eSjoerg 
expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst * AI)97806f32e7eSjoerg void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
97906f32e7eSjoerg   IRBuilder<> Builder(AI);
98006f32e7eSjoerg 
98106f32e7eSjoerg   PartwordMaskValues PMV =
98206f32e7eSjoerg       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
983*da58b97aSjoerg                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
98406f32e7eSjoerg 
98506f32e7eSjoerg   // The value operand must be sign-extended for signed min/max so that the
98606f32e7eSjoerg   // target's signed comparison instructions can be used. Otherwise, just
98706f32e7eSjoerg   // zero-ext.
98806f32e7eSjoerg   Instruction::CastOps CastOp = Instruction::ZExt;
98906f32e7eSjoerg   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
99006f32e7eSjoerg   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
99106f32e7eSjoerg     CastOp = Instruction::SExt;
99206f32e7eSjoerg 
99306f32e7eSjoerg   Value *ValOperand_Shifted = Builder.CreateShl(
99406f32e7eSjoerg       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
99506f32e7eSjoerg       PMV.ShiftAmt, "ValOperand_Shifted");
99606f32e7eSjoerg   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
99706f32e7eSjoerg       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
99806f32e7eSjoerg       AI->getOrdering());
999*da58b97aSjoerg   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
100006f32e7eSjoerg   AI->replaceAllUsesWith(FinalOldResult);
100106f32e7eSjoerg   AI->eraseFromParent();
100206f32e7eSjoerg }
100306f32e7eSjoerg 
expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst * CI)100406f32e7eSjoerg void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
100506f32e7eSjoerg   IRBuilder<> Builder(CI);
100606f32e7eSjoerg 
100706f32e7eSjoerg   PartwordMaskValues PMV = createMaskInstrs(
100806f32e7eSjoerg       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1009*da58b97aSjoerg       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
101006f32e7eSjoerg 
101106f32e7eSjoerg   Value *CmpVal_Shifted = Builder.CreateShl(
101206f32e7eSjoerg       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
101306f32e7eSjoerg       "CmpVal_Shifted");
101406f32e7eSjoerg   Value *NewVal_Shifted = Builder.CreateShl(
101506f32e7eSjoerg       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
101606f32e7eSjoerg       "NewVal_Shifted");
101706f32e7eSjoerg   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
101806f32e7eSjoerg       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
101906f32e7eSjoerg       CI->getSuccessOrdering());
1020*da58b97aSjoerg   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
102106f32e7eSjoerg   Value *Res = UndefValue::get(CI->getType());
102206f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
102306f32e7eSjoerg   Value *Success = Builder.CreateICmpEQ(
102406f32e7eSjoerg       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
102506f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, Success, 1);
102606f32e7eSjoerg 
102706f32e7eSjoerg   CI->replaceAllUsesWith(Res);
102806f32e7eSjoerg   CI->eraseFromParent();
102906f32e7eSjoerg }
103006f32e7eSjoerg 
insertRMWLLSCLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)103106f32e7eSjoerg Value *AtomicExpand::insertRMWLLSCLoop(
1032*da58b97aSjoerg     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
103306f32e7eSjoerg     AtomicOrdering MemOpOrder,
103406f32e7eSjoerg     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
103506f32e7eSjoerg   LLVMContext &Ctx = Builder.getContext();
103606f32e7eSjoerg   BasicBlock *BB = Builder.GetInsertBlock();
103706f32e7eSjoerg   Function *F = BB->getParent();
103806f32e7eSjoerg 
1039*da58b97aSjoerg   assert(AddrAlign >=
1040*da58b97aSjoerg              F->getParent()->getDataLayout().getTypeStoreSize(ResultTy) &&
1041*da58b97aSjoerg          "Expected at least natural alignment at this point.");
1042*da58b97aSjoerg 
104306f32e7eSjoerg   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
104406f32e7eSjoerg   //
104506f32e7eSjoerg   // The standard expansion we produce is:
104606f32e7eSjoerg   //     [...]
104706f32e7eSjoerg   // atomicrmw.start:
104806f32e7eSjoerg   //     %loaded = @load.linked(%addr)
104906f32e7eSjoerg   //     %new = some_op iN %loaded, %incr
105006f32e7eSjoerg   //     %stored = @store_conditional(%new, %addr)
105106f32e7eSjoerg   //     %try_again = icmp i32 ne %stored, 0
105206f32e7eSjoerg   //     br i1 %try_again, label %loop, label %atomicrmw.end
105306f32e7eSjoerg   // atomicrmw.end:
105406f32e7eSjoerg   //     [...]
105506f32e7eSjoerg   BasicBlock *ExitBB =
105606f32e7eSjoerg       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
105706f32e7eSjoerg   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
105806f32e7eSjoerg 
105906f32e7eSjoerg   // The split call above "helpfully" added a branch at the end of BB (to the
106006f32e7eSjoerg   // wrong place).
106106f32e7eSjoerg   std::prev(BB->end())->eraseFromParent();
106206f32e7eSjoerg   Builder.SetInsertPoint(BB);
106306f32e7eSjoerg   Builder.CreateBr(LoopBB);
106406f32e7eSjoerg 
106506f32e7eSjoerg   // Start the main loop block now that we've taken care of the preliminaries.
106606f32e7eSjoerg   Builder.SetInsertPoint(LoopBB);
106706f32e7eSjoerg   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
106806f32e7eSjoerg 
106906f32e7eSjoerg   Value *NewVal = PerformOp(Builder, Loaded);
107006f32e7eSjoerg 
107106f32e7eSjoerg   Value *StoreSuccess =
107206f32e7eSjoerg       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
107306f32e7eSjoerg   Value *TryAgain = Builder.CreateICmpNE(
107406f32e7eSjoerg       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
107506f32e7eSjoerg   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
107606f32e7eSjoerg 
107706f32e7eSjoerg   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
107806f32e7eSjoerg   return Loaded;
107906f32e7eSjoerg }
108006f32e7eSjoerg 
108106f32e7eSjoerg /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
108206f32e7eSjoerg /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
108306f32e7eSjoerg /// IR.  As a migration step, we convert back to what use to be the standard
108406f32e7eSjoerg /// way to represent a pointer cmpxchg so that we can update backends one by
108506f32e7eSjoerg /// one.
convertCmpXchgToIntegerType(AtomicCmpXchgInst * CI)108606f32e7eSjoerg AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
108706f32e7eSjoerg   auto *M = CI->getModule();
108806f32e7eSjoerg   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
108906f32e7eSjoerg                                             M->getDataLayout());
109006f32e7eSjoerg 
109106f32e7eSjoerg   IRBuilder<> Builder(CI);
109206f32e7eSjoerg 
109306f32e7eSjoerg   Value *Addr = CI->getPointerOperand();
109406f32e7eSjoerg   Type *PT = PointerType::get(NewTy,
109506f32e7eSjoerg                               Addr->getType()->getPointerAddressSpace());
109606f32e7eSjoerg   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
109706f32e7eSjoerg 
109806f32e7eSjoerg   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
109906f32e7eSjoerg   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
110006f32e7eSjoerg 
1101*da58b97aSjoerg   auto *NewCI = Builder.CreateAtomicCmpXchg(
1102*da58b97aSjoerg       NewAddr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
1103*da58b97aSjoerg       CI->getFailureOrdering(), CI->getSyncScopeID());
110406f32e7eSjoerg   NewCI->setVolatile(CI->isVolatile());
110506f32e7eSjoerg   NewCI->setWeak(CI->isWeak());
110606f32e7eSjoerg   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
110706f32e7eSjoerg 
110806f32e7eSjoerg   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
110906f32e7eSjoerg   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
111006f32e7eSjoerg 
111106f32e7eSjoerg   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
111206f32e7eSjoerg 
111306f32e7eSjoerg   Value *Res = UndefValue::get(CI->getType());
111406f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, OldVal, 0);
111506f32e7eSjoerg   Res = Builder.CreateInsertValue(Res, Succ, 1);
111606f32e7eSjoerg 
111706f32e7eSjoerg   CI->replaceAllUsesWith(Res);
111806f32e7eSjoerg   CI->eraseFromParent();
111906f32e7eSjoerg   return NewCI;
112006f32e7eSjoerg }
112106f32e7eSjoerg 
expandAtomicCmpXchg(AtomicCmpXchgInst * CI)112206f32e7eSjoerg bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
112306f32e7eSjoerg   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
112406f32e7eSjoerg   AtomicOrdering FailureOrder = CI->getFailureOrdering();
112506f32e7eSjoerg   Value *Addr = CI->getPointerOperand();
112606f32e7eSjoerg   BasicBlock *BB = CI->getParent();
112706f32e7eSjoerg   Function *F = BB->getParent();
112806f32e7eSjoerg   LLVMContext &Ctx = F->getContext();
112906f32e7eSjoerg   // If shouldInsertFencesForAtomic() returns true, then the target does not
113006f32e7eSjoerg   // want to deal with memory orders, and emitLeading/TrailingFence should take
113106f32e7eSjoerg   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
113206f32e7eSjoerg   // should preserve the ordering.
113306f32e7eSjoerg   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
113406f32e7eSjoerg   AtomicOrdering MemOpOrder =
113506f32e7eSjoerg       ShouldInsertFencesForAtomic ? AtomicOrdering::Monotonic : SuccessOrder;
113606f32e7eSjoerg 
113706f32e7eSjoerg   // In implementations which use a barrier to achieve release semantics, we can
113806f32e7eSjoerg   // delay emitting this barrier until we know a store is actually going to be
113906f32e7eSjoerg   // attempted. The cost of this delay is that we need 2 copies of the block
114006f32e7eSjoerg   // emitting the load-linked, affecting code size.
114106f32e7eSjoerg   //
114206f32e7eSjoerg   // Ideally, this logic would be unconditional except for the minsize check
114306f32e7eSjoerg   // since in other cases the extra blocks naturally collapse down to the
114406f32e7eSjoerg   // minimal loop. Unfortunately, this puts too much stress on later
114506f32e7eSjoerg   // optimisations so we avoid emitting the extra logic in those cases too.
114606f32e7eSjoerg   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
114706f32e7eSjoerg                            SuccessOrder != AtomicOrdering::Monotonic &&
114806f32e7eSjoerg                            SuccessOrder != AtomicOrdering::Acquire &&
114906f32e7eSjoerg                            !F->hasMinSize();
115006f32e7eSjoerg 
115106f32e7eSjoerg   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
115206f32e7eSjoerg   // do it even on minsize.
115306f32e7eSjoerg   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
115406f32e7eSjoerg 
115506f32e7eSjoerg   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
115606f32e7eSjoerg   //
115706f32e7eSjoerg   // The full expansion we produce is:
115806f32e7eSjoerg   //     [...]
1159*da58b97aSjoerg   // %aligned.addr = ...
116006f32e7eSjoerg   // cmpxchg.start:
1161*da58b97aSjoerg   //     %unreleasedload = @load.linked(%aligned.addr)
1162*da58b97aSjoerg   //     %unreleasedload.extract = extract value from %unreleasedload
1163*da58b97aSjoerg   //     %should_store = icmp eq %unreleasedload.extract, %desired
1164*da58b97aSjoerg   //     br i1 %should_store, label %cmpxchg.releasingstore,
116506f32e7eSjoerg   //                          label %cmpxchg.nostore
116606f32e7eSjoerg   // cmpxchg.releasingstore:
116706f32e7eSjoerg   //     fence?
116806f32e7eSjoerg   //     br label cmpxchg.trystore
116906f32e7eSjoerg   // cmpxchg.trystore:
1170*da58b97aSjoerg   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
117106f32e7eSjoerg   //                            [%releasedload, %cmpxchg.releasedload]
1172*da58b97aSjoerg   //     %updated.new = insert %new into %loaded.trystore
1173*da58b97aSjoerg   //     %stored = @store_conditional(%updated.new, %aligned.addr)
117406f32e7eSjoerg   //     %success = icmp eq i32 %stored, 0
117506f32e7eSjoerg   //     br i1 %success, label %cmpxchg.success,
117606f32e7eSjoerg   //                     label %cmpxchg.releasedload/%cmpxchg.failure
117706f32e7eSjoerg   // cmpxchg.releasedload:
1178*da58b97aSjoerg   //     %releasedload = @load.linked(%aligned.addr)
1179*da58b97aSjoerg   //     %releasedload.extract = extract value from %releasedload
1180*da58b97aSjoerg   //     %should_store = icmp eq %releasedload.extract, %desired
118106f32e7eSjoerg   //     br i1 %should_store, label %cmpxchg.trystore,
118206f32e7eSjoerg   //                          label %cmpxchg.failure
118306f32e7eSjoerg   // cmpxchg.success:
118406f32e7eSjoerg   //     fence?
118506f32e7eSjoerg   //     br label %cmpxchg.end
118606f32e7eSjoerg   // cmpxchg.nostore:
118706f32e7eSjoerg   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
118806f32e7eSjoerg   //                           [%releasedload,
118906f32e7eSjoerg   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
119006f32e7eSjoerg   //     @load_linked_fail_balance()?
119106f32e7eSjoerg   //     br label %cmpxchg.failure
119206f32e7eSjoerg   // cmpxchg.failure:
119306f32e7eSjoerg   //     fence?
119406f32e7eSjoerg   //     br label %cmpxchg.end
119506f32e7eSjoerg   // cmpxchg.end:
1196*da58b97aSjoerg   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
119706f32e7eSjoerg   //                        [%loaded.trystore, %cmpxchg.trystore]
119806f32e7eSjoerg   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1199*da58b97aSjoerg   //     %loaded = extract value from %loaded.exit
120006f32e7eSjoerg   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
120106f32e7eSjoerg   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
120206f32e7eSjoerg   //     [...]
120306f32e7eSjoerg   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
120406f32e7eSjoerg   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
120506f32e7eSjoerg   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
120606f32e7eSjoerg   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
120706f32e7eSjoerg   auto ReleasedLoadBB =
120806f32e7eSjoerg       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
120906f32e7eSjoerg   auto TryStoreBB =
121006f32e7eSjoerg       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
121106f32e7eSjoerg   auto ReleasingStoreBB =
121206f32e7eSjoerg       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
121306f32e7eSjoerg   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
121406f32e7eSjoerg 
121506f32e7eSjoerg   // This grabs the DebugLoc from CI
121606f32e7eSjoerg   IRBuilder<> Builder(CI);
121706f32e7eSjoerg 
121806f32e7eSjoerg   // The split call above "helpfully" added a branch at the end of BB (to the
121906f32e7eSjoerg   // wrong place), but we might want a fence too. It's easiest to just remove
122006f32e7eSjoerg   // the branch entirely.
122106f32e7eSjoerg   std::prev(BB->end())->eraseFromParent();
122206f32e7eSjoerg   Builder.SetInsertPoint(BB);
122306f32e7eSjoerg   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
122406f32e7eSjoerg     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1225*da58b97aSjoerg 
1226*da58b97aSjoerg   PartwordMaskValues PMV =
1227*da58b97aSjoerg       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1228*da58b97aSjoerg                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
122906f32e7eSjoerg   Builder.CreateBr(StartBB);
123006f32e7eSjoerg 
123106f32e7eSjoerg   // Start the main loop block now that we've taken care of the preliminaries.
123206f32e7eSjoerg   Builder.SetInsertPoint(StartBB);
1233*da58b97aSjoerg   Value *UnreleasedLoad =
1234*da58b97aSjoerg       TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1235*da58b97aSjoerg   Value *UnreleasedLoadExtract =
1236*da58b97aSjoerg       extractMaskedValue(Builder, UnreleasedLoad, PMV);
123706f32e7eSjoerg   Value *ShouldStore = Builder.CreateICmpEQ(
1238*da58b97aSjoerg       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
123906f32e7eSjoerg 
124006f32e7eSjoerg   // If the cmpxchg doesn't actually need any ordering when it fails, we can
124106f32e7eSjoerg   // jump straight past that fence instruction (if it exists).
124206f32e7eSjoerg   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
124306f32e7eSjoerg 
124406f32e7eSjoerg   Builder.SetInsertPoint(ReleasingStoreBB);
124506f32e7eSjoerg   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
124606f32e7eSjoerg     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
124706f32e7eSjoerg   Builder.CreateBr(TryStoreBB);
124806f32e7eSjoerg 
124906f32e7eSjoerg   Builder.SetInsertPoint(TryStoreBB);
1250*da58b97aSjoerg   PHINode *LoadedTryStore =
1251*da58b97aSjoerg       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1252*da58b97aSjoerg   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1253*da58b97aSjoerg   Value *NewValueInsert =
1254*da58b97aSjoerg       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1255*da58b97aSjoerg   Value *StoreSuccess =
1256*da58b97aSjoerg       TLI->emitStoreConditional(Builder, NewValueInsert, PMV.AlignedAddr,
1257*da58b97aSjoerg                                 MemOpOrder);
125806f32e7eSjoerg   StoreSuccess = Builder.CreateICmpEQ(
125906f32e7eSjoerg       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
126006f32e7eSjoerg   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
126106f32e7eSjoerg   Builder.CreateCondBr(StoreSuccess, SuccessBB,
126206f32e7eSjoerg                        CI->isWeak() ? FailureBB : RetryBB);
126306f32e7eSjoerg 
126406f32e7eSjoerg   Builder.SetInsertPoint(ReleasedLoadBB);
126506f32e7eSjoerg   Value *SecondLoad;
126606f32e7eSjoerg   if (HasReleasedLoadBB) {
1267*da58b97aSjoerg     SecondLoad = TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1268*da58b97aSjoerg     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1269*da58b97aSjoerg     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1270*da58b97aSjoerg                                        CI->getCompareOperand(), "should_store");
127106f32e7eSjoerg 
127206f32e7eSjoerg     // If the cmpxchg doesn't actually need any ordering when it fails, we can
127306f32e7eSjoerg     // jump straight past that fence instruction (if it exists).
127406f32e7eSjoerg     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1275*da58b97aSjoerg     // Update PHI node in TryStoreBB.
1276*da58b97aSjoerg     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
127706f32e7eSjoerg   } else
127806f32e7eSjoerg     Builder.CreateUnreachable();
127906f32e7eSjoerg 
128006f32e7eSjoerg   // Make sure later instructions don't get reordered with a fence if
128106f32e7eSjoerg   // necessary.
128206f32e7eSjoerg   Builder.SetInsertPoint(SuccessBB);
128306f32e7eSjoerg   if (ShouldInsertFencesForAtomic)
128406f32e7eSjoerg     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
128506f32e7eSjoerg   Builder.CreateBr(ExitBB);
128606f32e7eSjoerg 
128706f32e7eSjoerg   Builder.SetInsertPoint(NoStoreBB);
1288*da58b97aSjoerg   PHINode *LoadedNoStore =
1289*da58b97aSjoerg       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1290*da58b97aSjoerg   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1291*da58b97aSjoerg   if (HasReleasedLoadBB)
1292*da58b97aSjoerg     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1293*da58b97aSjoerg 
129406f32e7eSjoerg   // In the failing case, where we don't execute the store-conditional, the
129506f32e7eSjoerg   // target might want to balance out the load-linked with a dedicated
129606f32e7eSjoerg   // instruction (e.g., on ARM, clearing the exclusive monitor).
129706f32e7eSjoerg   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
129806f32e7eSjoerg   Builder.CreateBr(FailureBB);
129906f32e7eSjoerg 
130006f32e7eSjoerg   Builder.SetInsertPoint(FailureBB);
1301*da58b97aSjoerg   PHINode *LoadedFailure =
1302*da58b97aSjoerg       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1303*da58b97aSjoerg   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1304*da58b97aSjoerg   if (CI->isWeak())
1305*da58b97aSjoerg     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
130606f32e7eSjoerg   if (ShouldInsertFencesForAtomic)
130706f32e7eSjoerg     TLI->emitTrailingFence(Builder, CI, FailureOrder);
130806f32e7eSjoerg   Builder.CreateBr(ExitBB);
130906f32e7eSjoerg 
131006f32e7eSjoerg   // Finally, we have control-flow based knowledge of whether the cmpxchg
131106f32e7eSjoerg   // succeeded or not. We expose this to later passes by converting any
131206f32e7eSjoerg   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
131306f32e7eSjoerg   // PHI.
131406f32e7eSjoerg   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1315*da58b97aSjoerg   PHINode *LoadedExit =
1316*da58b97aSjoerg       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1317*da58b97aSjoerg   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1318*da58b97aSjoerg   LoadedExit->addIncoming(LoadedFailure, FailureBB);
1319*da58b97aSjoerg   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
132006f32e7eSjoerg   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
132106f32e7eSjoerg   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
132206f32e7eSjoerg 
1323*da58b97aSjoerg   // This is the "exit value" from the cmpxchg expansion. It may be of
1324*da58b97aSjoerg   // a type wider than the one in the cmpxchg instruction.
1325*da58b97aSjoerg   Value *LoadedFull = LoadedExit;
132606f32e7eSjoerg 
1327*da58b97aSjoerg   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1328*da58b97aSjoerg   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
132906f32e7eSjoerg 
133006f32e7eSjoerg   // Look for any users of the cmpxchg that are just comparing the loaded value
133106f32e7eSjoerg   // against the desired one, and replace them with the CFG-derived version.
133206f32e7eSjoerg   SmallVector<ExtractValueInst *, 2> PrunedInsts;
133306f32e7eSjoerg   for (auto User : CI->users()) {
133406f32e7eSjoerg     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
133506f32e7eSjoerg     if (!EV)
133606f32e7eSjoerg       continue;
133706f32e7eSjoerg 
133806f32e7eSjoerg     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
133906f32e7eSjoerg            "weird extraction from { iN, i1 }");
134006f32e7eSjoerg 
134106f32e7eSjoerg     if (EV->getIndices()[0] == 0)
134206f32e7eSjoerg       EV->replaceAllUsesWith(Loaded);
134306f32e7eSjoerg     else
134406f32e7eSjoerg       EV->replaceAllUsesWith(Success);
134506f32e7eSjoerg 
134606f32e7eSjoerg     PrunedInsts.push_back(EV);
134706f32e7eSjoerg   }
134806f32e7eSjoerg 
134906f32e7eSjoerg   // We can remove the instructions now we're no longer iterating through them.
135006f32e7eSjoerg   for (auto EV : PrunedInsts)
135106f32e7eSjoerg     EV->eraseFromParent();
135206f32e7eSjoerg 
135306f32e7eSjoerg   if (!CI->use_empty()) {
135406f32e7eSjoerg     // Some use of the full struct return that we don't understand has happened,
135506f32e7eSjoerg     // so we've got to reconstruct it properly.
135606f32e7eSjoerg     Value *Res;
135706f32e7eSjoerg     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
135806f32e7eSjoerg     Res = Builder.CreateInsertValue(Res, Success, 1);
135906f32e7eSjoerg 
136006f32e7eSjoerg     CI->replaceAllUsesWith(Res);
136106f32e7eSjoerg   }
136206f32e7eSjoerg 
136306f32e7eSjoerg   CI->eraseFromParent();
136406f32e7eSjoerg   return true;
136506f32e7eSjoerg }
136606f32e7eSjoerg 
isIdempotentRMW(AtomicRMWInst * RMWI)136706f32e7eSjoerg bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
136806f32e7eSjoerg   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
136906f32e7eSjoerg   if(!C)
137006f32e7eSjoerg     return false;
137106f32e7eSjoerg 
137206f32e7eSjoerg   AtomicRMWInst::BinOp Op = RMWI->getOperation();
137306f32e7eSjoerg   switch(Op) {
137406f32e7eSjoerg     case AtomicRMWInst::Add:
137506f32e7eSjoerg     case AtomicRMWInst::Sub:
137606f32e7eSjoerg     case AtomicRMWInst::Or:
137706f32e7eSjoerg     case AtomicRMWInst::Xor:
137806f32e7eSjoerg       return C->isZero();
137906f32e7eSjoerg     case AtomicRMWInst::And:
138006f32e7eSjoerg       return C->isMinusOne();
138106f32e7eSjoerg     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
138206f32e7eSjoerg     default:
138306f32e7eSjoerg       return false;
138406f32e7eSjoerg   }
138506f32e7eSjoerg }
138606f32e7eSjoerg 
simplifyIdempotentRMW(AtomicRMWInst * RMWI)138706f32e7eSjoerg bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
138806f32e7eSjoerg   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
138906f32e7eSjoerg     tryExpandAtomicLoad(ResultingLoad);
139006f32e7eSjoerg     return true;
139106f32e7eSjoerg   }
139206f32e7eSjoerg   return false;
139306f32e7eSjoerg }
139406f32e7eSjoerg 
insertRMWCmpXchgLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,SyncScope::ID SSID,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp,CreateCmpXchgInstFun CreateCmpXchg)139506f32e7eSjoerg Value *AtomicExpand::insertRMWCmpXchgLoop(
1396*da58b97aSjoerg     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1397*da58b97aSjoerg     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
139806f32e7eSjoerg     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
139906f32e7eSjoerg     CreateCmpXchgInstFun CreateCmpXchg) {
140006f32e7eSjoerg   LLVMContext &Ctx = Builder.getContext();
140106f32e7eSjoerg   BasicBlock *BB = Builder.GetInsertBlock();
140206f32e7eSjoerg   Function *F = BB->getParent();
140306f32e7eSjoerg 
140406f32e7eSjoerg   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
140506f32e7eSjoerg   //
140606f32e7eSjoerg   // The standard expansion we produce is:
140706f32e7eSjoerg   //     [...]
140806f32e7eSjoerg   //     %init_loaded = load atomic iN* %addr
140906f32e7eSjoerg   //     br label %loop
141006f32e7eSjoerg   // loop:
141106f32e7eSjoerg   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
141206f32e7eSjoerg   //     %new = some_op iN %loaded, %incr
141306f32e7eSjoerg   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
141406f32e7eSjoerg   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
141506f32e7eSjoerg   //     %success = extractvalue { iN, i1 } %pair, 1
141606f32e7eSjoerg   //     br i1 %success, label %atomicrmw.end, label %loop
141706f32e7eSjoerg   // atomicrmw.end:
141806f32e7eSjoerg   //     [...]
141906f32e7eSjoerg   BasicBlock *ExitBB =
142006f32e7eSjoerg       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
142106f32e7eSjoerg   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
142206f32e7eSjoerg 
142306f32e7eSjoerg   // The split call above "helpfully" added a branch at the end of BB (to the
142406f32e7eSjoerg   // wrong place), but we want a load. It's easiest to just remove
142506f32e7eSjoerg   // the branch entirely.
142606f32e7eSjoerg   std::prev(BB->end())->eraseFromParent();
142706f32e7eSjoerg   Builder.SetInsertPoint(BB);
1428*da58b97aSjoerg   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
142906f32e7eSjoerg   Builder.CreateBr(LoopBB);
143006f32e7eSjoerg 
143106f32e7eSjoerg   // Start the main loop block now that we've taken care of the preliminaries.
143206f32e7eSjoerg   Builder.SetInsertPoint(LoopBB);
143306f32e7eSjoerg   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
143406f32e7eSjoerg   Loaded->addIncoming(InitLoaded, BB);
143506f32e7eSjoerg 
143606f32e7eSjoerg   Value *NewVal = PerformOp(Builder, Loaded);
143706f32e7eSjoerg 
143806f32e7eSjoerg   Value *NewLoaded = nullptr;
143906f32e7eSjoerg   Value *Success = nullptr;
144006f32e7eSjoerg 
1441*da58b97aSjoerg   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
144206f32e7eSjoerg                 MemOpOrder == AtomicOrdering::Unordered
144306f32e7eSjoerg                     ? AtomicOrdering::Monotonic
144406f32e7eSjoerg                     : MemOpOrder,
1445*da58b97aSjoerg                 SSID, Success, NewLoaded);
144606f32e7eSjoerg   assert(Success && NewLoaded);
144706f32e7eSjoerg 
144806f32e7eSjoerg   Loaded->addIncoming(NewLoaded, LoopBB);
144906f32e7eSjoerg 
145006f32e7eSjoerg   Builder.CreateCondBr(Success, ExitBB, LoopBB);
145106f32e7eSjoerg 
145206f32e7eSjoerg   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
145306f32e7eSjoerg   return NewLoaded;
145406f32e7eSjoerg }
145506f32e7eSjoerg 
tryExpandAtomicCmpXchg(AtomicCmpXchgInst * CI)145606f32e7eSjoerg bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
145706f32e7eSjoerg   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
145806f32e7eSjoerg   unsigned ValueSize = getAtomicOpSize(CI);
145906f32e7eSjoerg 
146006f32e7eSjoerg   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
146106f32e7eSjoerg   default:
146206f32e7eSjoerg     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
146306f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::None:
146406f32e7eSjoerg     if (ValueSize < MinCASSize)
1465*da58b97aSjoerg       return expandPartwordCmpXchg(CI);
146606f32e7eSjoerg     return false;
146706f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
146806f32e7eSjoerg     return expandAtomicCmpXchg(CI);
146906f32e7eSjoerg   }
147006f32e7eSjoerg   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
147106f32e7eSjoerg     expandAtomicCmpXchgToMaskedIntrinsic(CI);
147206f32e7eSjoerg     return true;
147306f32e7eSjoerg   }
147406f32e7eSjoerg }
147506f32e7eSjoerg 
147606f32e7eSjoerg // Note: This function is exposed externally by AtomicExpandUtils.h
expandAtomicRMWToCmpXchg(AtomicRMWInst * AI,CreateCmpXchgInstFun CreateCmpXchg)147706f32e7eSjoerg bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
147806f32e7eSjoerg                                     CreateCmpXchgInstFun CreateCmpXchg) {
147906f32e7eSjoerg   IRBuilder<> Builder(AI);
148006f32e7eSjoerg   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1481*da58b97aSjoerg       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1482*da58b97aSjoerg       AI->getOrdering(), AI->getSyncScopeID(),
148306f32e7eSjoerg       [&](IRBuilder<> &Builder, Value *Loaded) {
148406f32e7eSjoerg         return performAtomicOp(AI->getOperation(), Builder, Loaded,
148506f32e7eSjoerg                                AI->getValOperand());
148606f32e7eSjoerg       },
148706f32e7eSjoerg       CreateCmpXchg);
148806f32e7eSjoerg 
148906f32e7eSjoerg   AI->replaceAllUsesWith(Loaded);
149006f32e7eSjoerg   AI->eraseFromParent();
149106f32e7eSjoerg   return true;
149206f32e7eSjoerg }
149306f32e7eSjoerg 
149406f32e7eSjoerg // In order to use one of the sized library calls such as
149506f32e7eSjoerg // __atomic_fetch_add_4, the alignment must be sufficient, the size
149606f32e7eSjoerg // must be one of the potentially-specialized sizes, and the value
149706f32e7eSjoerg // type must actually exist in C on the target (otherwise, the
149806f32e7eSjoerg // function wouldn't actually be defined.)
canUseSizedAtomicCall(unsigned Size,Align Alignment,const DataLayout & DL)1499*da58b97aSjoerg static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
150006f32e7eSjoerg                                   const DataLayout &DL) {
150106f32e7eSjoerg   // TODO: "LargestSize" is an approximation for "largest type that
150206f32e7eSjoerg   // you can express in C". It seems to be the case that int128 is
150306f32e7eSjoerg   // supported on all 64-bit platforms, otherwise only up to 64-bit
150406f32e7eSjoerg   // integers are supported. If we get this wrong, then we'll try to
150506f32e7eSjoerg   // call a sized libcall that doesn't actually exist. There should
150606f32e7eSjoerg   // really be some more reliable way in LLVM of determining integer
150706f32e7eSjoerg   // sizes which are valid in the target's C ABI...
150806f32e7eSjoerg   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1509*da58b97aSjoerg   return Alignment >= Size &&
151006f32e7eSjoerg          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
151106f32e7eSjoerg          Size <= LargestSize;
151206f32e7eSjoerg }
151306f32e7eSjoerg 
expandAtomicLoadToLibcall(LoadInst * I)151406f32e7eSjoerg void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
151506f32e7eSjoerg   static const RTLIB::Libcall Libcalls[6] = {
151606f32e7eSjoerg       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
151706f32e7eSjoerg       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
151806f32e7eSjoerg   unsigned Size = getAtomicOpSize(I);
151906f32e7eSjoerg 
152006f32e7eSjoerg   bool expanded = expandAtomicOpToLibcall(
1521*da58b97aSjoerg       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
152206f32e7eSjoerg       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1523*da58b97aSjoerg   if (!expanded)
1524*da58b97aSjoerg     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
152506f32e7eSjoerg }
152606f32e7eSjoerg 
expandAtomicStoreToLibcall(StoreInst * I)152706f32e7eSjoerg void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
152806f32e7eSjoerg   static const RTLIB::Libcall Libcalls[6] = {
152906f32e7eSjoerg       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
153006f32e7eSjoerg       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
153106f32e7eSjoerg   unsigned Size = getAtomicOpSize(I);
153206f32e7eSjoerg 
153306f32e7eSjoerg   bool expanded = expandAtomicOpToLibcall(
1534*da58b97aSjoerg       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1535*da58b97aSjoerg       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1536*da58b97aSjoerg   if (!expanded)
1537*da58b97aSjoerg     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
153806f32e7eSjoerg }
153906f32e7eSjoerg 
expandAtomicCASToLibcall(AtomicCmpXchgInst * I)154006f32e7eSjoerg void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
154106f32e7eSjoerg   static const RTLIB::Libcall Libcalls[6] = {
154206f32e7eSjoerg       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
154306f32e7eSjoerg       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
154406f32e7eSjoerg       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
154506f32e7eSjoerg   unsigned Size = getAtomicOpSize(I);
154606f32e7eSjoerg 
154706f32e7eSjoerg   bool expanded = expandAtomicOpToLibcall(
1548*da58b97aSjoerg       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
154906f32e7eSjoerg       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
155006f32e7eSjoerg       Libcalls);
1551*da58b97aSjoerg   if (!expanded)
1552*da58b97aSjoerg     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
155306f32e7eSjoerg }
155406f32e7eSjoerg 
GetRMWLibcall(AtomicRMWInst::BinOp Op)155506f32e7eSjoerg static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
155606f32e7eSjoerg   static const RTLIB::Libcall LibcallsXchg[6] = {
155706f32e7eSjoerg       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
155806f32e7eSjoerg       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
155906f32e7eSjoerg       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
156006f32e7eSjoerg   static const RTLIB::Libcall LibcallsAdd[6] = {
156106f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
156206f32e7eSjoerg       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
156306f32e7eSjoerg       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
156406f32e7eSjoerg   static const RTLIB::Libcall LibcallsSub[6] = {
156506f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
156606f32e7eSjoerg       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
156706f32e7eSjoerg       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
156806f32e7eSjoerg   static const RTLIB::Libcall LibcallsAnd[6] = {
156906f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
157006f32e7eSjoerg       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
157106f32e7eSjoerg       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
157206f32e7eSjoerg   static const RTLIB::Libcall LibcallsOr[6] = {
157306f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
157406f32e7eSjoerg       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
157506f32e7eSjoerg       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
157606f32e7eSjoerg   static const RTLIB::Libcall LibcallsXor[6] = {
157706f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
157806f32e7eSjoerg       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
157906f32e7eSjoerg       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
158006f32e7eSjoerg   static const RTLIB::Libcall LibcallsNand[6] = {
158106f32e7eSjoerg       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
158206f32e7eSjoerg       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
158306f32e7eSjoerg       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
158406f32e7eSjoerg 
158506f32e7eSjoerg   switch (Op) {
158606f32e7eSjoerg   case AtomicRMWInst::BAD_BINOP:
158706f32e7eSjoerg     llvm_unreachable("Should not have BAD_BINOP.");
158806f32e7eSjoerg   case AtomicRMWInst::Xchg:
158906f32e7eSjoerg     return makeArrayRef(LibcallsXchg);
159006f32e7eSjoerg   case AtomicRMWInst::Add:
159106f32e7eSjoerg     return makeArrayRef(LibcallsAdd);
159206f32e7eSjoerg   case AtomicRMWInst::Sub:
159306f32e7eSjoerg     return makeArrayRef(LibcallsSub);
159406f32e7eSjoerg   case AtomicRMWInst::And:
159506f32e7eSjoerg     return makeArrayRef(LibcallsAnd);
159606f32e7eSjoerg   case AtomicRMWInst::Or:
159706f32e7eSjoerg     return makeArrayRef(LibcallsOr);
159806f32e7eSjoerg   case AtomicRMWInst::Xor:
159906f32e7eSjoerg     return makeArrayRef(LibcallsXor);
160006f32e7eSjoerg   case AtomicRMWInst::Nand:
160106f32e7eSjoerg     return makeArrayRef(LibcallsNand);
160206f32e7eSjoerg   case AtomicRMWInst::Max:
160306f32e7eSjoerg   case AtomicRMWInst::Min:
160406f32e7eSjoerg   case AtomicRMWInst::UMax:
160506f32e7eSjoerg   case AtomicRMWInst::UMin:
160606f32e7eSjoerg   case AtomicRMWInst::FAdd:
160706f32e7eSjoerg   case AtomicRMWInst::FSub:
160806f32e7eSjoerg     // No atomic libcalls are available for max/min/umax/umin.
160906f32e7eSjoerg     return {};
161006f32e7eSjoerg   }
161106f32e7eSjoerg   llvm_unreachable("Unexpected AtomicRMW operation.");
161206f32e7eSjoerg }
161306f32e7eSjoerg 
expandAtomicRMWToLibcall(AtomicRMWInst * I)161406f32e7eSjoerg void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
161506f32e7eSjoerg   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
161606f32e7eSjoerg 
161706f32e7eSjoerg   unsigned Size = getAtomicOpSize(I);
161806f32e7eSjoerg 
161906f32e7eSjoerg   bool Success = false;
162006f32e7eSjoerg   if (!Libcalls.empty())
162106f32e7eSjoerg     Success = expandAtomicOpToLibcall(
1622*da58b97aSjoerg         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1623*da58b97aSjoerg         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
162406f32e7eSjoerg 
162506f32e7eSjoerg   // The expansion failed: either there were no libcalls at all for
162606f32e7eSjoerg   // the operation (min/max), or there were only size-specialized
162706f32e7eSjoerg   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
162806f32e7eSjoerg   // CAS libcall, via a CAS loop, instead.
162906f32e7eSjoerg   if (!Success) {
1630*da58b97aSjoerg     expandAtomicRMWToCmpXchg(
1631*da58b97aSjoerg         I, [this](IRBuilder<> &Builder, Value *Addr, Value *Loaded,
1632*da58b97aSjoerg                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1633*da58b97aSjoerg                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
163406f32e7eSjoerg           // Create the CAS instruction normally...
163506f32e7eSjoerg           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1636*da58b97aSjoerg               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1637*da58b97aSjoerg               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
163806f32e7eSjoerg           Success = Builder.CreateExtractValue(Pair, 1, "success");
163906f32e7eSjoerg           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
164006f32e7eSjoerg 
164106f32e7eSjoerg           // ...and then expand the CAS into a libcall.
164206f32e7eSjoerg           expandAtomicCASToLibcall(Pair);
164306f32e7eSjoerg         });
164406f32e7eSjoerg   }
164506f32e7eSjoerg }
164606f32e7eSjoerg 
164706f32e7eSjoerg // A helper routine for the above expandAtomic*ToLibcall functions.
164806f32e7eSjoerg //
164906f32e7eSjoerg // 'Libcalls' contains an array of enum values for the particular
165006f32e7eSjoerg // ATOMIC libcalls to be emitted. All of the other arguments besides
165106f32e7eSjoerg // 'I' are extracted from the Instruction subclass by the
165206f32e7eSjoerg // caller. Depending on the particular call, some will be null.
expandAtomicOpToLibcall(Instruction * I,unsigned Size,Align Alignment,Value * PointerOperand,Value * ValueOperand,Value * CASExpected,AtomicOrdering Ordering,AtomicOrdering Ordering2,ArrayRef<RTLIB::Libcall> Libcalls)165306f32e7eSjoerg bool AtomicExpand::expandAtomicOpToLibcall(
1654*da58b97aSjoerg     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
165506f32e7eSjoerg     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
165606f32e7eSjoerg     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
165706f32e7eSjoerg   assert(Libcalls.size() == 6);
165806f32e7eSjoerg 
165906f32e7eSjoerg   LLVMContext &Ctx = I->getContext();
166006f32e7eSjoerg   Module *M = I->getModule();
166106f32e7eSjoerg   const DataLayout &DL = M->getDataLayout();
166206f32e7eSjoerg   IRBuilder<> Builder(I);
166306f32e7eSjoerg   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
166406f32e7eSjoerg 
1665*da58b97aSjoerg   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
166606f32e7eSjoerg   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
166706f32e7eSjoerg 
1668*da58b97aSjoerg   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
166906f32e7eSjoerg 
167006f32e7eSjoerg   // TODO: the "order" argument type is "int", not int32. So
167106f32e7eSjoerg   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
167206f32e7eSjoerg   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
167306f32e7eSjoerg   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
167406f32e7eSjoerg   Constant *OrderingVal =
167506f32e7eSjoerg       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
167606f32e7eSjoerg   Constant *Ordering2Val = nullptr;
167706f32e7eSjoerg   if (CASExpected) {
167806f32e7eSjoerg     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
167906f32e7eSjoerg     Ordering2Val =
168006f32e7eSjoerg         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
168106f32e7eSjoerg   }
168206f32e7eSjoerg   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
168306f32e7eSjoerg 
168406f32e7eSjoerg   RTLIB::Libcall RTLibType;
168506f32e7eSjoerg   if (UseSizedLibcall) {
168606f32e7eSjoerg     switch (Size) {
168706f32e7eSjoerg     case 1: RTLibType = Libcalls[1]; break;
168806f32e7eSjoerg     case 2: RTLibType = Libcalls[2]; break;
168906f32e7eSjoerg     case 4: RTLibType = Libcalls[3]; break;
169006f32e7eSjoerg     case 8: RTLibType = Libcalls[4]; break;
169106f32e7eSjoerg     case 16: RTLibType = Libcalls[5]; break;
169206f32e7eSjoerg     }
169306f32e7eSjoerg   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
169406f32e7eSjoerg     RTLibType = Libcalls[0];
169506f32e7eSjoerg   } else {
169606f32e7eSjoerg     // Can't use sized function, and there's no generic for this
169706f32e7eSjoerg     // operation, so give up.
169806f32e7eSjoerg     return false;
169906f32e7eSjoerg   }
170006f32e7eSjoerg 
1701*da58b97aSjoerg   if (!TLI->getLibcallName(RTLibType)) {
1702*da58b97aSjoerg     // This target does not implement the requested atomic libcall so give up.
1703*da58b97aSjoerg     return false;
1704*da58b97aSjoerg   }
1705*da58b97aSjoerg 
170606f32e7eSjoerg   // Build up the function call. There's two kinds. First, the sized
170706f32e7eSjoerg   // variants.  These calls are going to be one of the following (with
170806f32e7eSjoerg   // N=1,2,4,8,16):
170906f32e7eSjoerg   //  iN    __atomic_load_N(iN *ptr, int ordering)
171006f32e7eSjoerg   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
171106f32e7eSjoerg   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
171206f32e7eSjoerg   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
171306f32e7eSjoerg   //                                    int success_order, int failure_order)
171406f32e7eSjoerg   //
171506f32e7eSjoerg   // Note that these functions can be used for non-integer atomic
171606f32e7eSjoerg   // operations, the values just need to be bitcast to integers on the
171706f32e7eSjoerg   // way in and out.
171806f32e7eSjoerg   //
171906f32e7eSjoerg   // And, then, the generic variants. They look like the following:
172006f32e7eSjoerg   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
172106f32e7eSjoerg   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
172206f32e7eSjoerg   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
172306f32e7eSjoerg   //                          int ordering)
172406f32e7eSjoerg   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
172506f32e7eSjoerg   //                                  void *desired, int success_order,
172606f32e7eSjoerg   //                                  int failure_order)
172706f32e7eSjoerg   //
172806f32e7eSjoerg   // The different signatures are built up depending on the
172906f32e7eSjoerg   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
173006f32e7eSjoerg   // variables.
173106f32e7eSjoerg 
173206f32e7eSjoerg   AllocaInst *AllocaCASExpected = nullptr;
173306f32e7eSjoerg   Value *AllocaCASExpected_i8 = nullptr;
173406f32e7eSjoerg   AllocaInst *AllocaValue = nullptr;
173506f32e7eSjoerg   Value *AllocaValue_i8 = nullptr;
173606f32e7eSjoerg   AllocaInst *AllocaResult = nullptr;
173706f32e7eSjoerg   Value *AllocaResult_i8 = nullptr;
173806f32e7eSjoerg 
173906f32e7eSjoerg   Type *ResultTy;
174006f32e7eSjoerg   SmallVector<Value *, 6> Args;
174106f32e7eSjoerg   AttributeList Attr;
174206f32e7eSjoerg 
174306f32e7eSjoerg   // 'size' argument.
174406f32e7eSjoerg   if (!UseSizedLibcall) {
174506f32e7eSjoerg     // Note, getIntPtrType is assumed equivalent to size_t.
174606f32e7eSjoerg     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
174706f32e7eSjoerg   }
174806f32e7eSjoerg 
174906f32e7eSjoerg   // 'ptr' argument.
175006f32e7eSjoerg   // note: This assumes all address spaces share a common libfunc
175106f32e7eSjoerg   // implementation and that addresses are convertable.  For systems without
175206f32e7eSjoerg   // that property, we'd need to extend this mechanism to support AS-specific
175306f32e7eSjoerg   // families of atomic intrinsics.
175406f32e7eSjoerg   auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
175506f32e7eSjoerg   Value *PtrVal = Builder.CreateBitCast(PointerOperand,
175606f32e7eSjoerg                                         Type::getInt8PtrTy(Ctx, PtrTypeAS));
175706f32e7eSjoerg   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
175806f32e7eSjoerg   Args.push_back(PtrVal);
175906f32e7eSjoerg 
176006f32e7eSjoerg   // 'expected' argument, if present.
176106f32e7eSjoerg   if (CASExpected) {
176206f32e7eSjoerg     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1763*da58b97aSjoerg     AllocaCASExpected->setAlignment(AllocaAlignment);
176406f32e7eSjoerg     unsigned AllocaAS =  AllocaCASExpected->getType()->getPointerAddressSpace();
176506f32e7eSjoerg 
176606f32e7eSjoerg     AllocaCASExpected_i8 =
176706f32e7eSjoerg       Builder.CreateBitCast(AllocaCASExpected,
176806f32e7eSjoerg                             Type::getInt8PtrTy(Ctx, AllocaAS));
176906f32e7eSjoerg     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
177006f32e7eSjoerg     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
177106f32e7eSjoerg     Args.push_back(AllocaCASExpected_i8);
177206f32e7eSjoerg   }
177306f32e7eSjoerg 
177406f32e7eSjoerg   // 'val' argument ('desired' for cas), if present.
177506f32e7eSjoerg   if (ValueOperand) {
177606f32e7eSjoerg     if (UseSizedLibcall) {
177706f32e7eSjoerg       Value *IntValue =
177806f32e7eSjoerg           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
177906f32e7eSjoerg       Args.push_back(IntValue);
178006f32e7eSjoerg     } else {
178106f32e7eSjoerg       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1782*da58b97aSjoerg       AllocaValue->setAlignment(AllocaAlignment);
178306f32e7eSjoerg       AllocaValue_i8 =
178406f32e7eSjoerg           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
178506f32e7eSjoerg       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
178606f32e7eSjoerg       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
178706f32e7eSjoerg       Args.push_back(AllocaValue_i8);
178806f32e7eSjoerg     }
178906f32e7eSjoerg   }
179006f32e7eSjoerg 
179106f32e7eSjoerg   // 'ret' argument.
179206f32e7eSjoerg   if (!CASExpected && HasResult && !UseSizedLibcall) {
179306f32e7eSjoerg     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1794*da58b97aSjoerg     AllocaResult->setAlignment(AllocaAlignment);
179506f32e7eSjoerg     unsigned AllocaAS =  AllocaResult->getType()->getPointerAddressSpace();
179606f32e7eSjoerg     AllocaResult_i8 =
179706f32e7eSjoerg       Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
179806f32e7eSjoerg     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
179906f32e7eSjoerg     Args.push_back(AllocaResult_i8);
180006f32e7eSjoerg   }
180106f32e7eSjoerg 
180206f32e7eSjoerg   // 'ordering' ('success_order' for cas) argument.
180306f32e7eSjoerg   Args.push_back(OrderingVal);
180406f32e7eSjoerg 
180506f32e7eSjoerg   // 'failure_order' argument, if present.
180606f32e7eSjoerg   if (Ordering2Val)
180706f32e7eSjoerg     Args.push_back(Ordering2Val);
180806f32e7eSjoerg 
180906f32e7eSjoerg   // Now, the return type.
181006f32e7eSjoerg   if (CASExpected) {
181106f32e7eSjoerg     ResultTy = Type::getInt1Ty(Ctx);
181206f32e7eSjoerg     Attr = Attr.addAttribute(Ctx, AttributeList::ReturnIndex, Attribute::ZExt);
181306f32e7eSjoerg   } else if (HasResult && UseSizedLibcall)
181406f32e7eSjoerg     ResultTy = SizedIntTy;
181506f32e7eSjoerg   else
181606f32e7eSjoerg     ResultTy = Type::getVoidTy(Ctx);
181706f32e7eSjoerg 
181806f32e7eSjoerg   // Done with setting up arguments and return types, create the call:
181906f32e7eSjoerg   SmallVector<Type *, 6> ArgTys;
182006f32e7eSjoerg   for (Value *Arg : Args)
182106f32e7eSjoerg     ArgTys.push_back(Arg->getType());
182206f32e7eSjoerg   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
182306f32e7eSjoerg   FunctionCallee LibcallFn =
182406f32e7eSjoerg       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
182506f32e7eSjoerg   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
182606f32e7eSjoerg   Call->setAttributes(Attr);
182706f32e7eSjoerg   Value *Result = Call;
182806f32e7eSjoerg 
182906f32e7eSjoerg   // And then, extract the results...
183006f32e7eSjoerg   if (ValueOperand && !UseSizedLibcall)
183106f32e7eSjoerg     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
183206f32e7eSjoerg 
183306f32e7eSjoerg   if (CASExpected) {
183406f32e7eSjoerg     // The final result from the CAS is {load of 'expected' alloca, bool result
183506f32e7eSjoerg     // from call}
183606f32e7eSjoerg     Type *FinalResultTy = I->getType();
183706f32e7eSjoerg     Value *V = UndefValue::get(FinalResultTy);
183806f32e7eSjoerg     Value *ExpectedOut = Builder.CreateAlignedLoad(
183906f32e7eSjoerg         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
184006f32e7eSjoerg     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
184106f32e7eSjoerg     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
184206f32e7eSjoerg     V = Builder.CreateInsertValue(V, Result, 1);
184306f32e7eSjoerg     I->replaceAllUsesWith(V);
184406f32e7eSjoerg   } else if (HasResult) {
184506f32e7eSjoerg     Value *V;
184606f32e7eSjoerg     if (UseSizedLibcall)
184706f32e7eSjoerg       V = Builder.CreateBitOrPointerCast(Result, I->getType());
184806f32e7eSjoerg     else {
184906f32e7eSjoerg       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
185006f32e7eSjoerg                                     AllocaAlignment);
185106f32e7eSjoerg       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
185206f32e7eSjoerg     }
185306f32e7eSjoerg     I->replaceAllUsesWith(V);
185406f32e7eSjoerg   }
185506f32e7eSjoerg   I->eraseFromParent();
185606f32e7eSjoerg   return true;
185706f32e7eSjoerg }
1858