12cab237bSDimitry Andric //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
239d628a0SDimitry Andric //
339d628a0SDimitry Andric // The LLVM Compiler Infrastructure
439d628a0SDimitry Andric //
539d628a0SDimitry Andric // This file is distributed under the University of Illinois Open Source
639d628a0SDimitry Andric // License. See LICENSE.TXT for details.
739d628a0SDimitry Andric //
839d628a0SDimitry Andric //===----------------------------------------------------------------------===//
939d628a0SDimitry Andric //
1039d628a0SDimitry Andric // This file contains a pass (at IR level) to replace atomic instructions with
113ca95b02SDimitry Andric // __atomic_* library calls, or target specific instruction which implement the
123ca95b02SDimitry Andric // same semantics in a way which better fits the target backend. This can
133ca95b02SDimitry Andric // include the use of (intrinsic-based) load-linked/store-conditional loops,
143ca95b02SDimitry Andric // AtomicCmpXchg, or type coercions.
1539d628a0SDimitry Andric //
1639d628a0SDimitry Andric //===----------------------------------------------------------------------===//
1739d628a0SDimitry Andric
182cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
192cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
202cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
217d523365SDimitry Andric #include "llvm/CodeGen/AtomicExpandUtils.h"
222cab237bSDimitry Andric #include "llvm/CodeGen/RuntimeLibcalls.h"
232cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
24d8866befSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
252cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/ValueTypes.h"
272cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
282cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
292cab237bSDimitry Andric #include "llvm/IR/Constant.h"
302cab237bSDimitry Andric #include "llvm/IR/Constants.h"
312cab237bSDimitry Andric #include "llvm/IR/DataLayout.h"
322cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3339d628a0SDimitry Andric #include "llvm/IR/Function.h"
3439d628a0SDimitry Andric #include "llvm/IR/IRBuilder.h"
3539d628a0SDimitry Andric #include "llvm/IR/InstIterator.h"
362cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
3739d628a0SDimitry Andric #include "llvm/IR/Instructions.h"
3839d628a0SDimitry Andric #include "llvm/IR/Module.h"
392cab237bSDimitry Andric #include "llvm/IR/Type.h"
402cab237bSDimitry Andric #include "llvm/IR/User.h"
412cab237bSDimitry Andric #include "llvm/IR/Value.h"
422cab237bSDimitry Andric #include "llvm/Pass.h"
432cab237bSDimitry Andric #include "llvm/Support/AtomicOrdering.h"
442cab237bSDimitry Andric #include "llvm/Support/Casting.h"
4539d628a0SDimitry Andric #include "llvm/Support/Debug.h"
462cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
477d523365SDimitry Andric #include "llvm/Support/raw_ostream.h"
4839d628a0SDimitry Andric #include "llvm/Target/TargetMachine.h"
492cab237bSDimitry Andric #include <cassert>
502cab237bSDimitry Andric #include <cstdint>
512cab237bSDimitry Andric #include <iterator>
5239d628a0SDimitry Andric
5339d628a0SDimitry Andric using namespace llvm;
5439d628a0SDimitry Andric
5539d628a0SDimitry Andric #define DEBUG_TYPE "atomic-expand"
5639d628a0SDimitry Andric
5739d628a0SDimitry Andric namespace {
582cab237bSDimitry Andric
5939d628a0SDimitry Andric class AtomicExpand: public FunctionPass {
602cab237bSDimitry Andric const TargetLowering *TLI = nullptr;
612cab237bSDimitry Andric
6239d628a0SDimitry Andric public:
6339d628a0SDimitry Andric static char ID; // Pass identification, replacement for typeid
642cab237bSDimitry Andric
AtomicExpand()652cab237bSDimitry Andric AtomicExpand() : FunctionPass(ID) {
6639d628a0SDimitry Andric initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
6739d628a0SDimitry Andric }
6839d628a0SDimitry Andric
6939d628a0SDimitry Andric bool runOnFunction(Function &F) override;
7039d628a0SDimitry Andric
7139d628a0SDimitry Andric private:
725517e702SDimitry Andric bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
737d523365SDimitry Andric IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
747d523365SDimitry Andric LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
757d523365SDimitry Andric bool tryExpandAtomicLoad(LoadInst *LI);
7639d628a0SDimitry Andric bool expandAtomicLoadToLL(LoadInst *LI);
7739d628a0SDimitry Andric bool expandAtomicLoadToCmpXchg(LoadInst *LI);
787d523365SDimitry Andric StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
7939d628a0SDimitry Andric bool expandAtomicStore(StoreInst *SI);
80ff0cc061SDimitry Andric bool tryExpandAtomicRMW(AtomicRMWInst *AI);
813ca95b02SDimitry Andric Value *
823ca95b02SDimitry Andric insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
833ca95b02SDimitry Andric AtomicOrdering MemOpOrder,
843ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
853ca95b02SDimitry Andric void expandAtomicOpToLLSC(
863ca95b02SDimitry Andric Instruction *I, Type *ResultTy, Value *Addr, AtomicOrdering MemOpOrder,
873ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
883ca95b02SDimitry Andric void expandPartwordAtomicRMW(
893ca95b02SDimitry Andric AtomicRMWInst *I,
903ca95b02SDimitry Andric TargetLoweringBase::AtomicExpansionKind ExpansionKind);
91*b5893f02SDimitry Andric AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
923ca95b02SDimitry Andric void expandPartwordCmpXchg(AtomicCmpXchgInst *I);
93*b5893f02SDimitry Andric void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
94*b5893f02SDimitry Andric void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
953ca95b02SDimitry Andric
963ca95b02SDimitry Andric AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
973ca95b02SDimitry Andric static Value *insertRMWCmpXchgLoop(
983ca95b02SDimitry Andric IRBuilder<> &Builder, Type *ResultType, Value *Addr,
993ca95b02SDimitry Andric AtomicOrdering MemOpOrder,
1003ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1013ca95b02SDimitry Andric CreateCmpXchgInstFun CreateCmpXchg);
102*b5893f02SDimitry Andric bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
1033ca95b02SDimitry Andric
10439d628a0SDimitry Andric bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
1054ba319b5SDimitry Andric bool isIdempotentRMW(AtomicRMWInst *RMWI);
1064ba319b5SDimitry Andric bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
1073ca95b02SDimitry Andric
1083ca95b02SDimitry Andric bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, unsigned Align,
1093ca95b02SDimitry Andric Value *PointerOperand, Value *ValueOperand,
1103ca95b02SDimitry Andric Value *CASExpected, AtomicOrdering Ordering,
1113ca95b02SDimitry Andric AtomicOrdering Ordering2,
1123ca95b02SDimitry Andric ArrayRef<RTLIB::Libcall> Libcalls);
1133ca95b02SDimitry Andric void expandAtomicLoadToLibcall(LoadInst *LI);
1143ca95b02SDimitry Andric void expandAtomicStoreToLibcall(StoreInst *LI);
1153ca95b02SDimitry Andric void expandAtomicRMWToLibcall(AtomicRMWInst *I);
1163ca95b02SDimitry Andric void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
1173ca95b02SDimitry Andric
1183ca95b02SDimitry Andric friend bool
1193ca95b02SDimitry Andric llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1203ca95b02SDimitry Andric CreateCmpXchgInstFun CreateCmpXchg);
12139d628a0SDimitry Andric };
1222cab237bSDimitry Andric
1232cab237bSDimitry Andric } // end anonymous namespace
12439d628a0SDimitry Andric
12539d628a0SDimitry Andric char AtomicExpand::ID = 0;
1262cab237bSDimitry Andric
12739d628a0SDimitry Andric char &llvm::AtomicExpandID = AtomicExpand::ID;
1282cab237bSDimitry Andric
129302affcbSDimitry Andric INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions",
13039d628a0SDimitry Andric false, false)
13139d628a0SDimitry Andric
createAtomicExpandPass()132d8866befSDimitry Andric FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
13339d628a0SDimitry Andric
1343ca95b02SDimitry Andric // Helper functions to retrieve the size of atomic instructions.
getAtomicOpSize(LoadInst * LI)1352cab237bSDimitry Andric static unsigned getAtomicOpSize(LoadInst *LI) {
1363ca95b02SDimitry Andric const DataLayout &DL = LI->getModule()->getDataLayout();
1373ca95b02SDimitry Andric return DL.getTypeStoreSize(LI->getType());
1383ca95b02SDimitry Andric }
1393ca95b02SDimitry Andric
getAtomicOpSize(StoreInst * SI)1402cab237bSDimitry Andric static unsigned getAtomicOpSize(StoreInst *SI) {
1413ca95b02SDimitry Andric const DataLayout &DL = SI->getModule()->getDataLayout();
1423ca95b02SDimitry Andric return DL.getTypeStoreSize(SI->getValueOperand()->getType());
1433ca95b02SDimitry Andric }
1443ca95b02SDimitry Andric
getAtomicOpSize(AtomicRMWInst * RMWI)1452cab237bSDimitry Andric static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
1463ca95b02SDimitry Andric const DataLayout &DL = RMWI->getModule()->getDataLayout();
1473ca95b02SDimitry Andric return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
1483ca95b02SDimitry Andric }
1493ca95b02SDimitry Andric
getAtomicOpSize(AtomicCmpXchgInst * CASI)1502cab237bSDimitry Andric static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
1513ca95b02SDimitry Andric const DataLayout &DL = CASI->getModule()->getDataLayout();
1523ca95b02SDimitry Andric return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
1533ca95b02SDimitry Andric }
1543ca95b02SDimitry Andric
1553ca95b02SDimitry Andric // Helper functions to retrieve the alignment of atomic instructions.
getAtomicOpAlign(LoadInst * LI)1562cab237bSDimitry Andric static unsigned getAtomicOpAlign(LoadInst *LI) {
1573ca95b02SDimitry Andric unsigned Align = LI->getAlignment();
1583ca95b02SDimitry Andric // In the future, if this IR restriction is relaxed, we should
1593ca95b02SDimitry Andric // return DataLayout::getABITypeAlignment when there's no align
1603ca95b02SDimitry Andric // value.
1613ca95b02SDimitry Andric assert(Align != 0 && "An atomic LoadInst always has an explicit alignment");
1623ca95b02SDimitry Andric return Align;
1633ca95b02SDimitry Andric }
1643ca95b02SDimitry Andric
getAtomicOpAlign(StoreInst * SI)1652cab237bSDimitry Andric static unsigned getAtomicOpAlign(StoreInst *SI) {
1663ca95b02SDimitry Andric unsigned Align = SI->getAlignment();
1673ca95b02SDimitry Andric // In the future, if this IR restriction is relaxed, we should
1683ca95b02SDimitry Andric // return DataLayout::getABITypeAlignment when there's no align
1693ca95b02SDimitry Andric // value.
1703ca95b02SDimitry Andric assert(Align != 0 && "An atomic StoreInst always has an explicit alignment");
1713ca95b02SDimitry Andric return Align;
1723ca95b02SDimitry Andric }
1733ca95b02SDimitry Andric
getAtomicOpAlign(AtomicRMWInst * RMWI)1742cab237bSDimitry Andric static unsigned getAtomicOpAlign(AtomicRMWInst *RMWI) {
1753ca95b02SDimitry Andric // TODO(PR27168): This instruction has no alignment attribute, but unlike the
1763ca95b02SDimitry Andric // default alignment for load/store, the default here is to assume
1773ca95b02SDimitry Andric // it has NATURAL alignment, not DataLayout-specified alignment.
1783ca95b02SDimitry Andric const DataLayout &DL = RMWI->getModule()->getDataLayout();
1793ca95b02SDimitry Andric return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
1803ca95b02SDimitry Andric }
1813ca95b02SDimitry Andric
getAtomicOpAlign(AtomicCmpXchgInst * CASI)1822cab237bSDimitry Andric static unsigned getAtomicOpAlign(AtomicCmpXchgInst *CASI) {
1833ca95b02SDimitry Andric // TODO(PR27168): same comment as above.
1843ca95b02SDimitry Andric const DataLayout &DL = CASI->getModule()->getDataLayout();
1853ca95b02SDimitry Andric return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
1863ca95b02SDimitry Andric }
1873ca95b02SDimitry Andric
1883ca95b02SDimitry Andric // Determine if a particular atomic operation has a supported size,
1893ca95b02SDimitry Andric // and is of appropriate alignment, to be passed through for target
1903ca95b02SDimitry Andric // lowering. (Versus turning into a __atomic libcall)
1913ca95b02SDimitry Andric template <typename Inst>
atomicSizeSupported(const TargetLowering * TLI,Inst * I)1922cab237bSDimitry Andric static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
1933ca95b02SDimitry Andric unsigned Size = getAtomicOpSize(I);
1943ca95b02SDimitry Andric unsigned Align = getAtomicOpAlign(I);
1953ca95b02SDimitry Andric return Align >= Size && Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
1963ca95b02SDimitry Andric }
1973ca95b02SDimitry Andric
runOnFunction(Function & F)19839d628a0SDimitry Andric bool AtomicExpand::runOnFunction(Function &F) {
199d8866befSDimitry Andric auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
200d8866befSDimitry Andric if (!TPC)
20139d628a0SDimitry Andric return false;
202d8866befSDimitry Andric
203d8866befSDimitry Andric auto &TM = TPC->getTM<TargetMachine>();
204d8866befSDimitry Andric if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
205d8866befSDimitry Andric return false;
206d8866befSDimitry Andric TLI = TM.getSubtargetImpl(F)->getTargetLowering();
20739d628a0SDimitry Andric
20839d628a0SDimitry Andric SmallVector<Instruction *, 1> AtomicInsts;
20939d628a0SDimitry Andric
21039d628a0SDimitry Andric // Changing control-flow while iterating through it is a bad idea, so gather a
21139d628a0SDimitry Andric // list of all atomic instructions before we start.
2123ca95b02SDimitry Andric for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
2133ca95b02SDimitry Andric Instruction *I = &*II;
2143ca95b02SDimitry Andric if (I->isAtomic() && !isa<FenceInst>(I))
2153ca95b02SDimitry Andric AtomicInsts.push_back(I);
21639d628a0SDimitry Andric }
21739d628a0SDimitry Andric
21839d628a0SDimitry Andric bool MadeChange = false;
21939d628a0SDimitry Andric for (auto I : AtomicInsts) {
22039d628a0SDimitry Andric auto LI = dyn_cast<LoadInst>(I);
22139d628a0SDimitry Andric auto SI = dyn_cast<StoreInst>(I);
22239d628a0SDimitry Andric auto RMWI = dyn_cast<AtomicRMWInst>(I);
22339d628a0SDimitry Andric auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
2243ca95b02SDimitry Andric assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
22539d628a0SDimitry Andric
2263ca95b02SDimitry Andric // If the Size/Alignment is not supported, replace with a libcall.
2273ca95b02SDimitry Andric if (LI) {
2283ca95b02SDimitry Andric if (!atomicSizeSupported(TLI, LI)) {
2293ca95b02SDimitry Andric expandAtomicLoadToLibcall(LI);
2303ca95b02SDimitry Andric MadeChange = true;
2313ca95b02SDimitry Andric continue;
2323ca95b02SDimitry Andric }
2333ca95b02SDimitry Andric } else if (SI) {
2343ca95b02SDimitry Andric if (!atomicSizeSupported(TLI, SI)) {
2353ca95b02SDimitry Andric expandAtomicStoreToLibcall(SI);
2363ca95b02SDimitry Andric MadeChange = true;
2373ca95b02SDimitry Andric continue;
2383ca95b02SDimitry Andric }
2393ca95b02SDimitry Andric } else if (RMWI) {
2403ca95b02SDimitry Andric if (!atomicSizeSupported(TLI, RMWI)) {
2413ca95b02SDimitry Andric expandAtomicRMWToLibcall(RMWI);
2423ca95b02SDimitry Andric MadeChange = true;
2433ca95b02SDimitry Andric continue;
2443ca95b02SDimitry Andric }
2453ca95b02SDimitry Andric } else if (CASI) {
2463ca95b02SDimitry Andric if (!atomicSizeSupported(TLI, CASI)) {
2473ca95b02SDimitry Andric expandAtomicCASToLibcall(CASI);
2483ca95b02SDimitry Andric MadeChange = true;
2493ca95b02SDimitry Andric continue;
2503ca95b02SDimitry Andric }
2513ca95b02SDimitry Andric }
2523ca95b02SDimitry Andric
2533ca95b02SDimitry Andric if (TLI->shouldInsertFencesForAtomic(I)) {
2543ca95b02SDimitry Andric auto FenceOrdering = AtomicOrdering::Monotonic;
2553ca95b02SDimitry Andric if (LI && isAcquireOrStronger(LI->getOrdering())) {
25639d628a0SDimitry Andric FenceOrdering = LI->getOrdering();
2573ca95b02SDimitry Andric LI->setOrdering(AtomicOrdering::Monotonic);
2583ca95b02SDimitry Andric } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
25939d628a0SDimitry Andric FenceOrdering = SI->getOrdering();
2603ca95b02SDimitry Andric SI->setOrdering(AtomicOrdering::Monotonic);
2613ca95b02SDimitry Andric } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
2623ca95b02SDimitry Andric isAcquireOrStronger(RMWI->getOrdering()))) {
26339d628a0SDimitry Andric FenceOrdering = RMWI->getOrdering();
2643ca95b02SDimitry Andric RMWI->setOrdering(AtomicOrdering::Monotonic);
265*b5893f02SDimitry Andric } else if (CASI &&
266*b5893f02SDimitry Andric TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
267*b5893f02SDimitry Andric TargetLoweringBase::AtomicExpansionKind::None &&
2683ca95b02SDimitry Andric (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
2693ca95b02SDimitry Andric isAcquireOrStronger(CASI->getSuccessOrdering()))) {
27039d628a0SDimitry Andric // If a compare and swap is lowered to LL/SC, we can do smarter fence
27139d628a0SDimitry Andric // insertion, with a stronger one on the success path than on the
27239d628a0SDimitry Andric // failure path. As a result, fence insertion is directly done by
27339d628a0SDimitry Andric // expandAtomicCmpXchg in that case.
27439d628a0SDimitry Andric FenceOrdering = CASI->getSuccessOrdering();
2753ca95b02SDimitry Andric CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
2763ca95b02SDimitry Andric CASI->setFailureOrdering(AtomicOrdering::Monotonic);
27739d628a0SDimitry Andric }
27839d628a0SDimitry Andric
2793ca95b02SDimitry Andric if (FenceOrdering != AtomicOrdering::Monotonic) {
2805517e702SDimitry Andric MadeChange |= bracketInstWithFences(I, FenceOrdering);
28139d628a0SDimitry Andric }
28239d628a0SDimitry Andric }
28339d628a0SDimitry Andric
2847d523365SDimitry Andric if (LI) {
2857d523365SDimitry Andric if (LI->getType()->isFloatingPointTy()) {
2867d523365SDimitry Andric // TODO: add a TLI hook to control this so that each target can
2877d523365SDimitry Andric // convert to lowering the original type one at a time.
2887d523365SDimitry Andric LI = convertAtomicLoadToIntegerType(LI);
2897d523365SDimitry Andric assert(LI->getType()->isIntegerTy() && "invariant broken");
2907d523365SDimitry Andric MadeChange = true;
2917d523365SDimitry Andric }
2927d523365SDimitry Andric
2937d523365SDimitry Andric MadeChange |= tryExpandAtomicLoad(LI);
2947d523365SDimitry Andric } else if (SI) {
2957d523365SDimitry Andric if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
2967d523365SDimitry Andric // TODO: add a TLI hook to control this so that each target can
2977d523365SDimitry Andric // convert to lowering the original type one at a time.
2987d523365SDimitry Andric SI = convertAtomicStoreToIntegerType(SI);
2997d523365SDimitry Andric assert(SI->getValueOperand()->getType()->isIntegerTy() &&
3007d523365SDimitry Andric "invariant broken");
3017d523365SDimitry Andric MadeChange = true;
3027d523365SDimitry Andric }
3037d523365SDimitry Andric
3047d523365SDimitry Andric if (TLI->shouldExpandAtomicStoreInIR(SI))
30539d628a0SDimitry Andric MadeChange |= expandAtomicStore(SI);
30639d628a0SDimitry Andric } else if (RMWI) {
30739d628a0SDimitry Andric // There are two different ways of expanding RMW instructions:
30839d628a0SDimitry Andric // - into a load if it is idempotent
30939d628a0SDimitry Andric // - into a Cmpxchg/LL-SC loop otherwise
31039d628a0SDimitry Andric // we try them in that order.
311ff0cc061SDimitry Andric
312ff0cc061SDimitry Andric if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
313ff0cc061SDimitry Andric MadeChange = true;
314ff0cc061SDimitry Andric } else {
315*b5893f02SDimitry Andric unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
316*b5893f02SDimitry Andric unsigned ValueSize = getAtomicOpSize(RMWI);
317*b5893f02SDimitry Andric AtomicRMWInst::BinOp Op = RMWI->getOperation();
318*b5893f02SDimitry Andric if (ValueSize < MinCASSize &&
319*b5893f02SDimitry Andric (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
320*b5893f02SDimitry Andric Op == AtomicRMWInst::And)) {
321*b5893f02SDimitry Andric RMWI = widenPartwordAtomicRMW(RMWI);
322*b5893f02SDimitry Andric MadeChange = true;
323*b5893f02SDimitry Andric }
324*b5893f02SDimitry Andric
325ff0cc061SDimitry Andric MadeChange |= tryExpandAtomicRMW(RMWI);
326ff0cc061SDimitry Andric }
3273ca95b02SDimitry Andric } else if (CASI) {
3283ca95b02SDimitry Andric // TODO: when we're ready to make the change at the IR level, we can
3293ca95b02SDimitry Andric // extend convertCmpXchgToInteger for floating point too.
3303ca95b02SDimitry Andric assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
3313ca95b02SDimitry Andric "unimplemented - floating point not legal at IR level");
3323ca95b02SDimitry Andric if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
3333ca95b02SDimitry Andric // TODO: add a TLI hook to control this so that each target can
3343ca95b02SDimitry Andric // convert to lowering the original type one at a time.
3353ca95b02SDimitry Andric CASI = convertCmpXchgToIntegerType(CASI);
3363ca95b02SDimitry Andric assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
3373ca95b02SDimitry Andric "invariant broken");
3383ca95b02SDimitry Andric MadeChange = true;
3393ca95b02SDimitry Andric }
3403ca95b02SDimitry Andric
341*b5893f02SDimitry Andric MadeChange |= tryExpandAtomicCmpXchg(CASI);
34239d628a0SDimitry Andric }
3433ca95b02SDimitry Andric }
34439d628a0SDimitry Andric return MadeChange;
34539d628a0SDimitry Andric }
34639d628a0SDimitry Andric
bracketInstWithFences(Instruction * I,AtomicOrdering Order)3475517e702SDimitry Andric bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
34839d628a0SDimitry Andric IRBuilder<> Builder(I);
34939d628a0SDimitry Andric
3505517e702SDimitry Andric auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
35139d628a0SDimitry Andric
3525517e702SDimitry Andric auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
35339d628a0SDimitry Andric // We have a guard here because not every atomic operation generates a
35439d628a0SDimitry Andric // trailing fence.
3552cab237bSDimitry Andric if (TrailingFence)
3562cab237bSDimitry Andric TrailingFence->moveAfter(I);
35739d628a0SDimitry Andric
35839d628a0SDimitry Andric return (LeadingFence || TrailingFence);
35939d628a0SDimitry Andric }
36039d628a0SDimitry Andric
3617d523365SDimitry Andric /// Get the iX type with the same bitwidth as T.
getCorrespondingIntegerType(Type * T,const DataLayout & DL)3627d523365SDimitry Andric IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
3637d523365SDimitry Andric const DataLayout &DL) {
3647d523365SDimitry Andric EVT VT = TLI->getValueType(DL, T);
3657d523365SDimitry Andric unsigned BitWidth = VT.getStoreSizeInBits();
3667d523365SDimitry Andric assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
3677d523365SDimitry Andric return IntegerType::get(T->getContext(), BitWidth);
3687d523365SDimitry Andric }
3697d523365SDimitry Andric
3707d523365SDimitry Andric /// Convert an atomic load of a non-integral type to an integer load of the
3713ca95b02SDimitry Andric /// equivalent bitwidth. See the function comment on
3727d523365SDimitry Andric /// convertAtomicStoreToIntegerType for background.
convertAtomicLoadToIntegerType(LoadInst * LI)3737d523365SDimitry Andric LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
3747d523365SDimitry Andric auto *M = LI->getModule();
3757d523365SDimitry Andric Type *NewTy = getCorrespondingIntegerType(LI->getType(),
3767d523365SDimitry Andric M->getDataLayout());
3777d523365SDimitry Andric
3787d523365SDimitry Andric IRBuilder<> Builder(LI);
3797d523365SDimitry Andric
3807d523365SDimitry Andric Value *Addr = LI->getPointerOperand();
3817d523365SDimitry Andric Type *PT = PointerType::get(NewTy,
3827d523365SDimitry Andric Addr->getType()->getPointerAddressSpace());
3837d523365SDimitry Andric Value *NewAddr = Builder.CreateBitCast(Addr, PT);
3847d523365SDimitry Andric
3857d523365SDimitry Andric auto *NewLI = Builder.CreateLoad(NewAddr);
3867d523365SDimitry Andric NewLI->setAlignment(LI->getAlignment());
3877d523365SDimitry Andric NewLI->setVolatile(LI->isVolatile());
388c4394386SDimitry Andric NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
3894ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
3907d523365SDimitry Andric
3917d523365SDimitry Andric Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
3927d523365SDimitry Andric LI->replaceAllUsesWith(NewVal);
3937d523365SDimitry Andric LI->eraseFromParent();
3947d523365SDimitry Andric return NewLI;
3957d523365SDimitry Andric }
3967d523365SDimitry Andric
tryExpandAtomicLoad(LoadInst * LI)3977d523365SDimitry Andric bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
3987d523365SDimitry Andric switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
3997d523365SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::None:
4007d523365SDimitry Andric return false;
4017d523365SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::LLSC:
4023ca95b02SDimitry Andric expandAtomicOpToLLSC(
4033ca95b02SDimitry Andric LI, LI->getType(), LI->getPointerOperand(), LI->getOrdering(),
4047d523365SDimitry Andric [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
4053ca95b02SDimitry Andric return true;
4067d523365SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::LLOnly:
40739d628a0SDimitry Andric return expandAtomicLoadToLL(LI);
4087d523365SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
40939d628a0SDimitry Andric return expandAtomicLoadToCmpXchg(LI);
410*b5893f02SDimitry Andric default:
4117d523365SDimitry Andric llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
4127d523365SDimitry Andric }
413*b5893f02SDimitry Andric }
41439d628a0SDimitry Andric
expandAtomicLoadToLL(LoadInst * LI)41539d628a0SDimitry Andric bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
41639d628a0SDimitry Andric IRBuilder<> Builder(LI);
41739d628a0SDimitry Andric
41839d628a0SDimitry Andric // On some architectures, load-linked instructions are atomic for larger
41939d628a0SDimitry Andric // sizes than normal loads. For example, the only 64-bit load guaranteed
42039d628a0SDimitry Andric // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
42139d628a0SDimitry Andric Value *Val =
42239d628a0SDimitry Andric TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
4237d523365SDimitry Andric TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
42439d628a0SDimitry Andric
42539d628a0SDimitry Andric LI->replaceAllUsesWith(Val);
42639d628a0SDimitry Andric LI->eraseFromParent();
42739d628a0SDimitry Andric
42839d628a0SDimitry Andric return true;
42939d628a0SDimitry Andric }
43039d628a0SDimitry Andric
expandAtomicLoadToCmpXchg(LoadInst * LI)43139d628a0SDimitry Andric bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
43239d628a0SDimitry Andric IRBuilder<> Builder(LI);
43339d628a0SDimitry Andric AtomicOrdering Order = LI->getOrdering();
43439d628a0SDimitry Andric Value *Addr = LI->getPointerOperand();
43539d628a0SDimitry Andric Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
43639d628a0SDimitry Andric Constant *DummyVal = Constant::getNullValue(Ty);
43739d628a0SDimitry Andric
43839d628a0SDimitry Andric Value *Pair = Builder.CreateAtomicCmpXchg(
43939d628a0SDimitry Andric Addr, DummyVal, DummyVal, Order,
44039d628a0SDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
44139d628a0SDimitry Andric Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
44239d628a0SDimitry Andric
44339d628a0SDimitry Andric LI->replaceAllUsesWith(Loaded);
44439d628a0SDimitry Andric LI->eraseFromParent();
44539d628a0SDimitry Andric
44639d628a0SDimitry Andric return true;
44739d628a0SDimitry Andric }
44839d628a0SDimitry Andric
4497d523365SDimitry Andric /// Convert an atomic store of a non-integral type to an integer store of the
4503ca95b02SDimitry Andric /// equivalent bitwidth. We used to not support floating point or vector
4517d523365SDimitry Andric /// atomics in the IR at all. The backends learned to deal with the bitcast
4527d523365SDimitry Andric /// idiom because that was the only way of expressing the notion of a atomic
4537d523365SDimitry Andric /// float or vector store. The long term plan is to teach each backend to
4547d523365SDimitry Andric /// instruction select from the original atomic store, but as a migration
4557d523365SDimitry Andric /// mechanism, we convert back to the old format which the backends understand.
4567d523365SDimitry Andric /// Each backend will need individual work to recognize the new format.
convertAtomicStoreToIntegerType(StoreInst * SI)4577d523365SDimitry Andric StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
4587d523365SDimitry Andric IRBuilder<> Builder(SI);
4597d523365SDimitry Andric auto *M = SI->getModule();
4607d523365SDimitry Andric Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
4617d523365SDimitry Andric M->getDataLayout());
4627d523365SDimitry Andric Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
4637d523365SDimitry Andric
4647d523365SDimitry Andric Value *Addr = SI->getPointerOperand();
4657d523365SDimitry Andric Type *PT = PointerType::get(NewTy,
4667d523365SDimitry Andric Addr->getType()->getPointerAddressSpace());
4677d523365SDimitry Andric Value *NewAddr = Builder.CreateBitCast(Addr, PT);
4687d523365SDimitry Andric
4697d523365SDimitry Andric StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
4707d523365SDimitry Andric NewSI->setAlignment(SI->getAlignment());
4717d523365SDimitry Andric NewSI->setVolatile(SI->isVolatile());
472c4394386SDimitry Andric NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
4734ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
4747d523365SDimitry Andric SI->eraseFromParent();
4757d523365SDimitry Andric return NewSI;
4767d523365SDimitry Andric }
4777d523365SDimitry Andric
expandAtomicStore(StoreInst * SI)47839d628a0SDimitry Andric bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
47939d628a0SDimitry Andric // This function is only called on atomic stores that are too large to be
48039d628a0SDimitry Andric // atomic if implemented as a native store. So we replace them by an
48139d628a0SDimitry Andric // atomic swap, that can be implemented for example as a ldrex/strex on ARM
48239d628a0SDimitry Andric // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
483ff0cc061SDimitry Andric // It is the responsibility of the target to only signal expansion via
48439d628a0SDimitry Andric // shouldExpandAtomicRMW in cases where this is required and possible.
48539d628a0SDimitry Andric IRBuilder<> Builder(SI);
48639d628a0SDimitry Andric AtomicRMWInst *AI =
48739d628a0SDimitry Andric Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
48839d628a0SDimitry Andric SI->getValueOperand(), SI->getOrdering());
48939d628a0SDimitry Andric SI->eraseFromParent();
49039d628a0SDimitry Andric
49139d628a0SDimitry Andric // Now we have an appropriate swap instruction, lower it as usual.
492ff0cc061SDimitry Andric return tryExpandAtomicRMW(AI);
49339d628a0SDimitry Andric }
49439d628a0SDimitry Andric
createCmpXchgInstFun(IRBuilder<> & Builder,Value * Addr,Value * Loaded,Value * NewVal,AtomicOrdering MemOpOrder,Value * & Success,Value * & NewLoaded)4957d523365SDimitry Andric static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
4967d523365SDimitry Andric Value *Loaded, Value *NewVal,
4977d523365SDimitry Andric AtomicOrdering MemOpOrder,
4987d523365SDimitry Andric Value *&Success, Value *&NewLoaded) {
4997d523365SDimitry Andric Value* Pair = Builder.CreateAtomicCmpXchg(
5007d523365SDimitry Andric Addr, Loaded, NewVal, MemOpOrder,
5017d523365SDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
5027d523365SDimitry Andric Success = Builder.CreateExtractValue(Pair, 1, "success");
5037d523365SDimitry Andric NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
504ff0cc061SDimitry Andric }
50539d628a0SDimitry Andric
50639d628a0SDimitry Andric /// Emit IR to implement the given atomicrmw operation on values in registers,
50739d628a0SDimitry Andric /// returning the new value.
performAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Inc)50839d628a0SDimitry Andric static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
50939d628a0SDimitry Andric Value *Loaded, Value *Inc) {
51039d628a0SDimitry Andric Value *NewVal;
51139d628a0SDimitry Andric switch (Op) {
51239d628a0SDimitry Andric case AtomicRMWInst::Xchg:
51339d628a0SDimitry Andric return Inc;
51439d628a0SDimitry Andric case AtomicRMWInst::Add:
51539d628a0SDimitry Andric return Builder.CreateAdd(Loaded, Inc, "new");
51639d628a0SDimitry Andric case AtomicRMWInst::Sub:
51739d628a0SDimitry Andric return Builder.CreateSub(Loaded, Inc, "new");
51839d628a0SDimitry Andric case AtomicRMWInst::And:
51939d628a0SDimitry Andric return Builder.CreateAnd(Loaded, Inc, "new");
52039d628a0SDimitry Andric case AtomicRMWInst::Nand:
52139d628a0SDimitry Andric return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
52239d628a0SDimitry Andric case AtomicRMWInst::Or:
52339d628a0SDimitry Andric return Builder.CreateOr(Loaded, Inc, "new");
52439d628a0SDimitry Andric case AtomicRMWInst::Xor:
52539d628a0SDimitry Andric return Builder.CreateXor(Loaded, Inc, "new");
52639d628a0SDimitry Andric case AtomicRMWInst::Max:
52739d628a0SDimitry Andric NewVal = Builder.CreateICmpSGT(Loaded, Inc);
52839d628a0SDimitry Andric return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
52939d628a0SDimitry Andric case AtomicRMWInst::Min:
53039d628a0SDimitry Andric NewVal = Builder.CreateICmpSLE(Loaded, Inc);
53139d628a0SDimitry Andric return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
53239d628a0SDimitry Andric case AtomicRMWInst::UMax:
53339d628a0SDimitry Andric NewVal = Builder.CreateICmpUGT(Loaded, Inc);
53439d628a0SDimitry Andric return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
53539d628a0SDimitry Andric case AtomicRMWInst::UMin:
53639d628a0SDimitry Andric NewVal = Builder.CreateICmpULE(Loaded, Inc);
53739d628a0SDimitry Andric return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
53839d628a0SDimitry Andric default:
53939d628a0SDimitry Andric llvm_unreachable("Unknown atomic op");
54039d628a0SDimitry Andric }
54139d628a0SDimitry Andric }
54239d628a0SDimitry Andric
tryExpandAtomicRMW(AtomicRMWInst * AI)5437d523365SDimitry Andric bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
5447d523365SDimitry Andric switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
5457d523365SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::None:
5467d523365SDimitry Andric return false;
5473ca95b02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::LLSC: {
5483ca95b02SDimitry Andric unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
5493ca95b02SDimitry Andric unsigned ValueSize = getAtomicOpSize(AI);
5503ca95b02SDimitry Andric if (ValueSize < MinCASSize) {
5513ca95b02SDimitry Andric llvm_unreachable(
5523ca95b02SDimitry Andric "MinCmpXchgSizeInBits not yet supported for LL/SC architectures.");
5533ca95b02SDimitry Andric } else {
5543ca95b02SDimitry Andric auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
5553ca95b02SDimitry Andric return performAtomicOp(AI->getOperation(), Builder, Loaded,
5567d523365SDimitry Andric AI->getValOperand());
5573ca95b02SDimitry Andric };
5583ca95b02SDimitry Andric expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
5593ca95b02SDimitry Andric AI->getOrdering(), PerformOp);
5603ca95b02SDimitry Andric }
5613ca95b02SDimitry Andric return true;
5623ca95b02SDimitry Andric }
5633ca95b02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
5643ca95b02SDimitry Andric unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
5653ca95b02SDimitry Andric unsigned ValueSize = getAtomicOpSize(AI);
5663ca95b02SDimitry Andric if (ValueSize < MinCASSize) {
5673ca95b02SDimitry Andric expandPartwordAtomicRMW(AI,
5683ca95b02SDimitry Andric TargetLoweringBase::AtomicExpansionKind::CmpXChg);
5693ca95b02SDimitry Andric } else {
5703ca95b02SDimitry Andric expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
5713ca95b02SDimitry Andric }
5723ca95b02SDimitry Andric return true;
5733ca95b02SDimitry Andric }
574*b5893f02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
575*b5893f02SDimitry Andric expandAtomicRMWToMaskedIntrinsic(AI);
576*b5893f02SDimitry Andric return true;
577*b5893f02SDimitry Andric }
5787d523365SDimitry Andric default:
5797d523365SDimitry Andric llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
5807d523365SDimitry Andric }
5817d523365SDimitry Andric }
5827d523365SDimitry Andric
5833ca95b02SDimitry Andric namespace {
5843ca95b02SDimitry Andric
5853ca95b02SDimitry Andric /// Result values from createMaskInstrs helper.
5863ca95b02SDimitry Andric struct PartwordMaskValues {
5873ca95b02SDimitry Andric Type *WordType;
5883ca95b02SDimitry Andric Type *ValueType;
5893ca95b02SDimitry Andric Value *AlignedAddr;
5903ca95b02SDimitry Andric Value *ShiftAmt;
5913ca95b02SDimitry Andric Value *Mask;
5923ca95b02SDimitry Andric Value *Inv_Mask;
5933ca95b02SDimitry Andric };
5942cab237bSDimitry Andric
5953ca95b02SDimitry Andric } // end anonymous namespace
5963ca95b02SDimitry Andric
5973ca95b02SDimitry Andric /// This is a helper function which builds instructions to provide
5983ca95b02SDimitry Andric /// values necessary for partword atomic operations. It takes an
5993ca95b02SDimitry Andric /// incoming address, Addr, and ValueType, and constructs the address,
6003ca95b02SDimitry Andric /// shift-amounts and masks needed to work with a larger value of size
6013ca95b02SDimitry Andric /// WordSize.
6023ca95b02SDimitry Andric ///
6033ca95b02SDimitry Andric /// AlignedAddr: Addr rounded down to a multiple of WordSize
6043ca95b02SDimitry Andric ///
6053ca95b02SDimitry Andric /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
6063ca95b02SDimitry Andric /// from AlignAddr for it to have the same value as if
6073ca95b02SDimitry Andric /// ValueType was loaded from Addr.
6083ca95b02SDimitry Andric ///
6093ca95b02SDimitry Andric /// Mask: Value to mask with the value loaded from AlignAddr to
6103ca95b02SDimitry Andric /// include only the part that would've been loaded from Addr.
6113ca95b02SDimitry Andric ///
6123ca95b02SDimitry Andric /// Inv_Mask: The inverse of Mask.
createMaskInstrs(IRBuilder<> & Builder,Instruction * I,Type * ValueType,Value * Addr,unsigned WordSize)6133ca95b02SDimitry Andric static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
6143ca95b02SDimitry Andric Type *ValueType, Value *Addr,
6153ca95b02SDimitry Andric unsigned WordSize) {
6163ca95b02SDimitry Andric PartwordMaskValues Ret;
6173ca95b02SDimitry Andric
6187d523365SDimitry Andric BasicBlock *BB = I->getParent();
61939d628a0SDimitry Andric Function *F = BB->getParent();
6203ca95b02SDimitry Andric Module *M = I->getModule();
6213ca95b02SDimitry Andric
62239d628a0SDimitry Andric LLVMContext &Ctx = F->getContext();
6233ca95b02SDimitry Andric const DataLayout &DL = M->getDataLayout();
6243ca95b02SDimitry Andric
6253ca95b02SDimitry Andric unsigned ValueSize = DL.getTypeStoreSize(ValueType);
6263ca95b02SDimitry Andric
6273ca95b02SDimitry Andric assert(ValueSize < WordSize);
6283ca95b02SDimitry Andric
6293ca95b02SDimitry Andric Ret.ValueType = ValueType;
6303ca95b02SDimitry Andric Ret.WordType = Type::getIntNTy(Ctx, WordSize * 8);
6313ca95b02SDimitry Andric
6323ca95b02SDimitry Andric Type *WordPtrType =
6333ca95b02SDimitry Andric Ret.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
6343ca95b02SDimitry Andric
6353ca95b02SDimitry Andric Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
6363ca95b02SDimitry Andric Ret.AlignedAddr = Builder.CreateIntToPtr(
6373ca95b02SDimitry Andric Builder.CreateAnd(AddrInt, ~(uint64_t)(WordSize - 1)), WordPtrType,
6383ca95b02SDimitry Andric "AlignedAddr");
6393ca95b02SDimitry Andric
6403ca95b02SDimitry Andric Value *PtrLSB = Builder.CreateAnd(AddrInt, WordSize - 1, "PtrLSB");
6413ca95b02SDimitry Andric if (DL.isLittleEndian()) {
6423ca95b02SDimitry Andric // turn bytes into bits
6433ca95b02SDimitry Andric Ret.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
6443ca95b02SDimitry Andric } else {
6453ca95b02SDimitry Andric // turn bytes into bits, and count from the other side.
6463ca95b02SDimitry Andric Ret.ShiftAmt =
6473ca95b02SDimitry Andric Builder.CreateShl(Builder.CreateXor(PtrLSB, WordSize - ValueSize), 3);
6483ca95b02SDimitry Andric }
6493ca95b02SDimitry Andric
6503ca95b02SDimitry Andric Ret.ShiftAmt = Builder.CreateTrunc(Ret.ShiftAmt, Ret.WordType, "ShiftAmt");
6513ca95b02SDimitry Andric Ret.Mask = Builder.CreateShl(
6523ca95b02SDimitry Andric ConstantInt::get(Ret.WordType, (1 << ValueSize * 8) - 1), Ret.ShiftAmt,
6533ca95b02SDimitry Andric "Mask");
6543ca95b02SDimitry Andric Ret.Inv_Mask = Builder.CreateNot(Ret.Mask, "Inv_Mask");
6553ca95b02SDimitry Andric
6563ca95b02SDimitry Andric return Ret;
6573ca95b02SDimitry Andric }
6583ca95b02SDimitry Andric
6593ca95b02SDimitry Andric /// Emit IR to implement a masked version of a given atomicrmw
6603ca95b02SDimitry Andric /// operation. (That is, only the bits under the Mask should be
6613ca95b02SDimitry Andric /// affected by the operation)
performMaskedAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Shifted_Inc,Value * Inc,const PartwordMaskValues & PMV)6623ca95b02SDimitry Andric static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
6633ca95b02SDimitry Andric IRBuilder<> &Builder, Value *Loaded,
6643ca95b02SDimitry Andric Value *Shifted_Inc, Value *Inc,
6653ca95b02SDimitry Andric const PartwordMaskValues &PMV) {
666*b5893f02SDimitry Andric // TODO: update to use
667*b5893f02SDimitry Andric // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
668*b5893f02SDimitry Andric // to merge bits from two values without requiring PMV.Inv_Mask.
6693ca95b02SDimitry Andric switch (Op) {
6703ca95b02SDimitry Andric case AtomicRMWInst::Xchg: {
6713ca95b02SDimitry Andric Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
6723ca95b02SDimitry Andric Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
6733ca95b02SDimitry Andric return FinalVal;
6743ca95b02SDimitry Andric }
6753ca95b02SDimitry Andric case AtomicRMWInst::Or:
6763ca95b02SDimitry Andric case AtomicRMWInst::Xor:
677*b5893f02SDimitry Andric case AtomicRMWInst::And:
678*b5893f02SDimitry Andric llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
6793ca95b02SDimitry Andric case AtomicRMWInst::Add:
6803ca95b02SDimitry Andric case AtomicRMWInst::Sub:
6813ca95b02SDimitry Andric case AtomicRMWInst::Nand: {
6823ca95b02SDimitry Andric // The other arithmetic ops need to be masked into place.
6833ca95b02SDimitry Andric Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
6843ca95b02SDimitry Andric Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
6853ca95b02SDimitry Andric Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
6863ca95b02SDimitry Andric Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
6873ca95b02SDimitry Andric return FinalVal;
6883ca95b02SDimitry Andric }
6893ca95b02SDimitry Andric case AtomicRMWInst::Max:
6903ca95b02SDimitry Andric case AtomicRMWInst::Min:
6913ca95b02SDimitry Andric case AtomicRMWInst::UMax:
6923ca95b02SDimitry Andric case AtomicRMWInst::UMin: {
6933ca95b02SDimitry Andric // Finally, comparison ops will operate on the full value, so
6943ca95b02SDimitry Andric // truncate down to the original size, and expand out again after
6953ca95b02SDimitry Andric // doing the operation.
6963ca95b02SDimitry Andric Value *Loaded_Shiftdown = Builder.CreateTrunc(
6973ca95b02SDimitry Andric Builder.CreateLShr(Loaded, PMV.ShiftAmt), PMV.ValueType);
6983ca95b02SDimitry Andric Value *NewVal = performAtomicOp(Op, Builder, Loaded_Shiftdown, Inc);
6993ca95b02SDimitry Andric Value *NewVal_Shiftup = Builder.CreateShl(
7003ca95b02SDimitry Andric Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
7013ca95b02SDimitry Andric Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
7023ca95b02SDimitry Andric Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shiftup);
7033ca95b02SDimitry Andric return FinalVal;
7043ca95b02SDimitry Andric }
7053ca95b02SDimitry Andric default:
7063ca95b02SDimitry Andric llvm_unreachable("Unknown atomic op");
7073ca95b02SDimitry Andric }
7083ca95b02SDimitry Andric }
7093ca95b02SDimitry Andric
7103ca95b02SDimitry Andric /// Expand a sub-word atomicrmw operation into an appropriate
7113ca95b02SDimitry Andric /// word-sized operation.
7123ca95b02SDimitry Andric ///
7133ca95b02SDimitry Andric /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
7143ca95b02SDimitry Andric /// way as a typical atomicrmw expansion. The only difference here is
7153ca95b02SDimitry Andric /// that the operation inside of the loop must operate only upon a
7163ca95b02SDimitry Andric /// part of the value.
expandPartwordAtomicRMW(AtomicRMWInst * AI,TargetLoweringBase::AtomicExpansionKind ExpansionKind)7173ca95b02SDimitry Andric void AtomicExpand::expandPartwordAtomicRMW(
7183ca95b02SDimitry Andric AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
7193ca95b02SDimitry Andric assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg);
7203ca95b02SDimitry Andric
7213ca95b02SDimitry Andric AtomicOrdering MemOpOrder = AI->getOrdering();
7223ca95b02SDimitry Andric
7233ca95b02SDimitry Andric IRBuilder<> Builder(AI);
7243ca95b02SDimitry Andric
7253ca95b02SDimitry Andric PartwordMaskValues PMV =
7263ca95b02SDimitry Andric createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
7273ca95b02SDimitry Andric TLI->getMinCmpXchgSizeInBits() / 8);
7283ca95b02SDimitry Andric
7293ca95b02SDimitry Andric Value *ValOperand_Shifted =
7303ca95b02SDimitry Andric Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
7313ca95b02SDimitry Andric PMV.ShiftAmt, "ValOperand_Shifted");
7323ca95b02SDimitry Andric
7333ca95b02SDimitry Andric auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
7343ca95b02SDimitry Andric return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
7353ca95b02SDimitry Andric ValOperand_Shifted, AI->getValOperand(), PMV);
7363ca95b02SDimitry Andric };
7373ca95b02SDimitry Andric
7383ca95b02SDimitry Andric // TODO: When we're ready to support LLSC conversions too, use
7393ca95b02SDimitry Andric // insertRMWLLSCLoop here for ExpansionKind==LLSC.
7403ca95b02SDimitry Andric Value *OldResult =
7413ca95b02SDimitry Andric insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder,
7423ca95b02SDimitry Andric PerformPartwordOp, createCmpXchgInstFun);
7433ca95b02SDimitry Andric Value *FinalOldResult = Builder.CreateTrunc(
7443ca95b02SDimitry Andric Builder.CreateLShr(OldResult, PMV.ShiftAmt), PMV.ValueType);
7453ca95b02SDimitry Andric AI->replaceAllUsesWith(FinalOldResult);
7463ca95b02SDimitry Andric AI->eraseFromParent();
7473ca95b02SDimitry Andric }
7483ca95b02SDimitry Andric
749*b5893f02SDimitry Andric // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
widenPartwordAtomicRMW(AtomicRMWInst * AI)750*b5893f02SDimitry Andric AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
751*b5893f02SDimitry Andric IRBuilder<> Builder(AI);
752*b5893f02SDimitry Andric AtomicRMWInst::BinOp Op = AI->getOperation();
753*b5893f02SDimitry Andric
754*b5893f02SDimitry Andric assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
755*b5893f02SDimitry Andric Op == AtomicRMWInst::And) &&
756*b5893f02SDimitry Andric "Unable to widen operation");
757*b5893f02SDimitry Andric
758*b5893f02SDimitry Andric PartwordMaskValues PMV =
759*b5893f02SDimitry Andric createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
760*b5893f02SDimitry Andric TLI->getMinCmpXchgSizeInBits() / 8);
761*b5893f02SDimitry Andric
762*b5893f02SDimitry Andric Value *ValOperand_Shifted =
763*b5893f02SDimitry Andric Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
764*b5893f02SDimitry Andric PMV.ShiftAmt, "ValOperand_Shifted");
765*b5893f02SDimitry Andric
766*b5893f02SDimitry Andric Value *NewOperand;
767*b5893f02SDimitry Andric
768*b5893f02SDimitry Andric if (Op == AtomicRMWInst::And)
769*b5893f02SDimitry Andric NewOperand =
770*b5893f02SDimitry Andric Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
771*b5893f02SDimitry Andric else
772*b5893f02SDimitry Andric NewOperand = ValOperand_Shifted;
773*b5893f02SDimitry Andric
774*b5893f02SDimitry Andric AtomicRMWInst *NewAI = Builder.CreateAtomicRMW(Op, PMV.AlignedAddr,
775*b5893f02SDimitry Andric NewOperand, AI->getOrdering());
776*b5893f02SDimitry Andric
777*b5893f02SDimitry Andric Value *FinalOldResult = Builder.CreateTrunc(
778*b5893f02SDimitry Andric Builder.CreateLShr(NewAI, PMV.ShiftAmt), PMV.ValueType);
779*b5893f02SDimitry Andric AI->replaceAllUsesWith(FinalOldResult);
780*b5893f02SDimitry Andric AI->eraseFromParent();
781*b5893f02SDimitry Andric return NewAI;
782*b5893f02SDimitry Andric }
783*b5893f02SDimitry Andric
expandPartwordCmpXchg(AtomicCmpXchgInst * CI)7843ca95b02SDimitry Andric void AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
7853ca95b02SDimitry Andric // The basic idea here is that we're expanding a cmpxchg of a
7863ca95b02SDimitry Andric // smaller memory size up to a word-sized cmpxchg. To do this, we
7873ca95b02SDimitry Andric // need to add a retry-loop for strong cmpxchg, so that
7883ca95b02SDimitry Andric // modifications to other parts of the word don't cause a spurious
7893ca95b02SDimitry Andric // failure.
7903ca95b02SDimitry Andric
7913ca95b02SDimitry Andric // This generates code like the following:
7923ca95b02SDimitry Andric // [[Setup mask values PMV.*]]
7933ca95b02SDimitry Andric // %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
7943ca95b02SDimitry Andric // %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
7953ca95b02SDimitry Andric // %InitLoaded = load i32* %addr
7963ca95b02SDimitry Andric // %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
7973ca95b02SDimitry Andric // br partword.cmpxchg.loop
7983ca95b02SDimitry Andric // partword.cmpxchg.loop:
7993ca95b02SDimitry Andric // %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
8003ca95b02SDimitry Andric // [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
8013ca95b02SDimitry Andric // %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
8023ca95b02SDimitry Andric // %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
8033ca95b02SDimitry Andric // %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
8043ca95b02SDimitry Andric // i32 %FullWord_NewVal success_ordering failure_ordering
8053ca95b02SDimitry Andric // %OldVal = extractvalue { i32, i1 } %NewCI, 0
8063ca95b02SDimitry Andric // %Success = extractvalue { i32, i1 } %NewCI, 1
8073ca95b02SDimitry Andric // br i1 %Success, label %partword.cmpxchg.end,
8083ca95b02SDimitry Andric // label %partword.cmpxchg.failure
8093ca95b02SDimitry Andric // partword.cmpxchg.failure:
8103ca95b02SDimitry Andric // %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
8113ca95b02SDimitry Andric // %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
8123ca95b02SDimitry Andric // br i1 %ShouldContinue, label %partword.cmpxchg.loop,
8133ca95b02SDimitry Andric // label %partword.cmpxchg.end
8143ca95b02SDimitry Andric // partword.cmpxchg.end:
8153ca95b02SDimitry Andric // %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
8163ca95b02SDimitry Andric // %FinalOldVal = trunc i32 %tmp1 to i8
8173ca95b02SDimitry Andric // %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
8183ca95b02SDimitry Andric // %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
8193ca95b02SDimitry Andric
8203ca95b02SDimitry Andric Value *Addr = CI->getPointerOperand();
8213ca95b02SDimitry Andric Value *Cmp = CI->getCompareOperand();
8223ca95b02SDimitry Andric Value *NewVal = CI->getNewValOperand();
8233ca95b02SDimitry Andric
8243ca95b02SDimitry Andric BasicBlock *BB = CI->getParent();
8253ca95b02SDimitry Andric Function *F = BB->getParent();
8263ca95b02SDimitry Andric IRBuilder<> Builder(CI);
8273ca95b02SDimitry Andric LLVMContext &Ctx = Builder.getContext();
8283ca95b02SDimitry Andric
8293ca95b02SDimitry Andric const int WordSize = TLI->getMinCmpXchgSizeInBits() / 8;
8303ca95b02SDimitry Andric
8313ca95b02SDimitry Andric BasicBlock *EndBB =
8323ca95b02SDimitry Andric BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
8333ca95b02SDimitry Andric auto FailureBB =
8343ca95b02SDimitry Andric BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
8353ca95b02SDimitry Andric auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
8363ca95b02SDimitry Andric
8373ca95b02SDimitry Andric // The split call above "helpfully" added a branch at the end of BB
8383ca95b02SDimitry Andric // (to the wrong place).
8393ca95b02SDimitry Andric std::prev(BB->end())->eraseFromParent();
8403ca95b02SDimitry Andric Builder.SetInsertPoint(BB);
8413ca95b02SDimitry Andric
8423ca95b02SDimitry Andric PartwordMaskValues PMV = createMaskInstrs(
8433ca95b02SDimitry Andric Builder, CI, CI->getCompareOperand()->getType(), Addr, WordSize);
8443ca95b02SDimitry Andric
8453ca95b02SDimitry Andric // Shift the incoming values over, into the right location in the word.
8463ca95b02SDimitry Andric Value *NewVal_Shifted =
8473ca95b02SDimitry Andric Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
8483ca95b02SDimitry Andric Value *Cmp_Shifted =
8493ca95b02SDimitry Andric Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
8503ca95b02SDimitry Andric
8513ca95b02SDimitry Andric // Load the entire current word, and mask into place the expected and new
8523ca95b02SDimitry Andric // values
8533ca95b02SDimitry Andric LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
8543ca95b02SDimitry Andric InitLoaded->setVolatile(CI->isVolatile());
8553ca95b02SDimitry Andric Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
8563ca95b02SDimitry Andric Builder.CreateBr(LoopBB);
8573ca95b02SDimitry Andric
8583ca95b02SDimitry Andric // partword.cmpxchg.loop:
8593ca95b02SDimitry Andric Builder.SetInsertPoint(LoopBB);
8603ca95b02SDimitry Andric PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
8613ca95b02SDimitry Andric Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
8623ca95b02SDimitry Andric
8633ca95b02SDimitry Andric // Mask/Or the expected and new values into place in the loaded word.
8643ca95b02SDimitry Andric Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
8653ca95b02SDimitry Andric Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
8663ca95b02SDimitry Andric AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
8673ca95b02SDimitry Andric PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, CI->getSuccessOrdering(),
868c4394386SDimitry Andric CI->getFailureOrdering(), CI->getSyncScopeID());
8693ca95b02SDimitry Andric NewCI->setVolatile(CI->isVolatile());
8703ca95b02SDimitry Andric // When we're building a strong cmpxchg, we need a loop, so you
8713ca95b02SDimitry Andric // might think we could use a weak cmpxchg inside. But, using strong
8723ca95b02SDimitry Andric // allows the below comparison for ShouldContinue, and we're
8733ca95b02SDimitry Andric // expecting the underlying cmpxchg to be a machine instruction,
8743ca95b02SDimitry Andric // which is strong anyways.
8753ca95b02SDimitry Andric NewCI->setWeak(CI->isWeak());
8763ca95b02SDimitry Andric
8773ca95b02SDimitry Andric Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
8783ca95b02SDimitry Andric Value *Success = Builder.CreateExtractValue(NewCI, 1);
8793ca95b02SDimitry Andric
8803ca95b02SDimitry Andric if (CI->isWeak())
8813ca95b02SDimitry Andric Builder.CreateBr(EndBB);
8823ca95b02SDimitry Andric else
8833ca95b02SDimitry Andric Builder.CreateCondBr(Success, EndBB, FailureBB);
8843ca95b02SDimitry Andric
8853ca95b02SDimitry Andric // partword.cmpxchg.failure:
8863ca95b02SDimitry Andric Builder.SetInsertPoint(FailureBB);
8873ca95b02SDimitry Andric // Upon failure, verify that the masked-out part of the loaded value
8883ca95b02SDimitry Andric // has been modified. If it didn't, abort the cmpxchg, since the
8893ca95b02SDimitry Andric // masked-in part must've.
8903ca95b02SDimitry Andric Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
8913ca95b02SDimitry Andric Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
8923ca95b02SDimitry Andric Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
8933ca95b02SDimitry Andric
8943ca95b02SDimitry Andric // Add the second value to the phi from above
8953ca95b02SDimitry Andric Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
8963ca95b02SDimitry Andric
8973ca95b02SDimitry Andric // partword.cmpxchg.end:
8983ca95b02SDimitry Andric Builder.SetInsertPoint(CI);
8993ca95b02SDimitry Andric
9003ca95b02SDimitry Andric Value *FinalOldVal = Builder.CreateTrunc(
9013ca95b02SDimitry Andric Builder.CreateLShr(OldVal, PMV.ShiftAmt), PMV.ValueType);
9023ca95b02SDimitry Andric Value *Res = UndefValue::get(CI->getType());
9033ca95b02SDimitry Andric Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
9043ca95b02SDimitry Andric Res = Builder.CreateInsertValue(Res, Success, 1);
9053ca95b02SDimitry Andric
9063ca95b02SDimitry Andric CI->replaceAllUsesWith(Res);
9073ca95b02SDimitry Andric CI->eraseFromParent();
9083ca95b02SDimitry Andric }
9093ca95b02SDimitry Andric
expandAtomicOpToLLSC(Instruction * I,Type * ResultType,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)9103ca95b02SDimitry Andric void AtomicExpand::expandAtomicOpToLLSC(
9113ca95b02SDimitry Andric Instruction *I, Type *ResultType, Value *Addr, AtomicOrdering MemOpOrder,
9123ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
9133ca95b02SDimitry Andric IRBuilder<> Builder(I);
9143ca95b02SDimitry Andric Value *Loaded =
9153ca95b02SDimitry Andric insertRMWLLSCLoop(Builder, ResultType, Addr, MemOpOrder, PerformOp);
9163ca95b02SDimitry Andric
9173ca95b02SDimitry Andric I->replaceAllUsesWith(Loaded);
9183ca95b02SDimitry Andric I->eraseFromParent();
9193ca95b02SDimitry Andric }
9203ca95b02SDimitry Andric
expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst * AI)921*b5893f02SDimitry Andric void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
922*b5893f02SDimitry Andric IRBuilder<> Builder(AI);
923*b5893f02SDimitry Andric
924*b5893f02SDimitry Andric PartwordMaskValues PMV =
925*b5893f02SDimitry Andric createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
926*b5893f02SDimitry Andric TLI->getMinCmpXchgSizeInBits() / 8);
927*b5893f02SDimitry Andric
928*b5893f02SDimitry Andric // The value operand must be sign-extended for signed min/max so that the
929*b5893f02SDimitry Andric // target's signed comparison instructions can be used. Otherwise, just
930*b5893f02SDimitry Andric // zero-ext.
931*b5893f02SDimitry Andric Instruction::CastOps CastOp = Instruction::ZExt;
932*b5893f02SDimitry Andric AtomicRMWInst::BinOp RMWOp = AI->getOperation();
933*b5893f02SDimitry Andric if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
934*b5893f02SDimitry Andric CastOp = Instruction::SExt;
935*b5893f02SDimitry Andric
936*b5893f02SDimitry Andric Value *ValOperand_Shifted = Builder.CreateShl(
937*b5893f02SDimitry Andric Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
938*b5893f02SDimitry Andric PMV.ShiftAmt, "ValOperand_Shifted");
939*b5893f02SDimitry Andric Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
940*b5893f02SDimitry Andric Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
941*b5893f02SDimitry Andric AI->getOrdering());
942*b5893f02SDimitry Andric Value *FinalOldResult = Builder.CreateTrunc(
943*b5893f02SDimitry Andric Builder.CreateLShr(OldResult, PMV.ShiftAmt), PMV.ValueType);
944*b5893f02SDimitry Andric AI->replaceAllUsesWith(FinalOldResult);
945*b5893f02SDimitry Andric AI->eraseFromParent();
946*b5893f02SDimitry Andric }
947*b5893f02SDimitry Andric
expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst * CI)948*b5893f02SDimitry Andric void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
949*b5893f02SDimitry Andric IRBuilder<> Builder(CI);
950*b5893f02SDimitry Andric
951*b5893f02SDimitry Andric PartwordMaskValues PMV = createMaskInstrs(
952*b5893f02SDimitry Andric Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
953*b5893f02SDimitry Andric TLI->getMinCmpXchgSizeInBits() / 8);
954*b5893f02SDimitry Andric
955*b5893f02SDimitry Andric Value *CmpVal_Shifted = Builder.CreateShl(
956*b5893f02SDimitry Andric Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
957*b5893f02SDimitry Andric "CmpVal_Shifted");
958*b5893f02SDimitry Andric Value *NewVal_Shifted = Builder.CreateShl(
959*b5893f02SDimitry Andric Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
960*b5893f02SDimitry Andric "NewVal_Shifted");
961*b5893f02SDimitry Andric Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
962*b5893f02SDimitry Andric Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
963*b5893f02SDimitry Andric CI->getSuccessOrdering());
964*b5893f02SDimitry Andric Value *FinalOldVal = Builder.CreateTrunc(
965*b5893f02SDimitry Andric Builder.CreateLShr(OldVal, PMV.ShiftAmt), PMV.ValueType);
966*b5893f02SDimitry Andric
967*b5893f02SDimitry Andric Value *Res = UndefValue::get(CI->getType());
968*b5893f02SDimitry Andric Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
969*b5893f02SDimitry Andric Value *Success = Builder.CreateICmpEQ(
970*b5893f02SDimitry Andric CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
971*b5893f02SDimitry Andric Res = Builder.CreateInsertValue(Res, Success, 1);
972*b5893f02SDimitry Andric
973*b5893f02SDimitry Andric CI->replaceAllUsesWith(Res);
974*b5893f02SDimitry Andric CI->eraseFromParent();
975*b5893f02SDimitry Andric }
976*b5893f02SDimitry Andric
insertRMWLLSCLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)9773ca95b02SDimitry Andric Value *AtomicExpand::insertRMWLLSCLoop(
9783ca95b02SDimitry Andric IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
9793ca95b02SDimitry Andric AtomicOrdering MemOpOrder,
9803ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
9813ca95b02SDimitry Andric LLVMContext &Ctx = Builder.getContext();
9823ca95b02SDimitry Andric BasicBlock *BB = Builder.GetInsertBlock();
9833ca95b02SDimitry Andric Function *F = BB->getParent();
98439d628a0SDimitry Andric
98539d628a0SDimitry Andric // Given: atomicrmw some_op iN* %addr, iN %incr ordering
98639d628a0SDimitry Andric //
98739d628a0SDimitry Andric // The standard expansion we produce is:
98839d628a0SDimitry Andric // [...]
98939d628a0SDimitry Andric // atomicrmw.start:
99039d628a0SDimitry Andric // %loaded = @load.linked(%addr)
99139d628a0SDimitry Andric // %new = some_op iN %loaded, %incr
99239d628a0SDimitry Andric // %stored = @store_conditional(%new, %addr)
99339d628a0SDimitry Andric // %try_again = icmp i32 ne %stored, 0
99439d628a0SDimitry Andric // br i1 %try_again, label %loop, label %atomicrmw.end
99539d628a0SDimitry Andric // atomicrmw.end:
99639d628a0SDimitry Andric // [...]
9973ca95b02SDimitry Andric BasicBlock *ExitBB =
9983ca95b02SDimitry Andric BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
99939d628a0SDimitry Andric BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
100039d628a0SDimitry Andric
100139d628a0SDimitry Andric // The split call above "helpfully" added a branch at the end of BB (to the
10023ca95b02SDimitry Andric // wrong place).
100339d628a0SDimitry Andric std::prev(BB->end())->eraseFromParent();
100439d628a0SDimitry Andric Builder.SetInsertPoint(BB);
100539d628a0SDimitry Andric Builder.CreateBr(LoopBB);
100639d628a0SDimitry Andric
100739d628a0SDimitry Andric // Start the main loop block now that we've taken care of the preliminaries.
100839d628a0SDimitry Andric Builder.SetInsertPoint(LoopBB);
100939d628a0SDimitry Andric Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
101039d628a0SDimitry Andric
10117d523365SDimitry Andric Value *NewVal = PerformOp(Builder, Loaded);
101239d628a0SDimitry Andric
101339d628a0SDimitry Andric Value *StoreSuccess =
101439d628a0SDimitry Andric TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
101539d628a0SDimitry Andric Value *TryAgain = Builder.CreateICmpNE(
101639d628a0SDimitry Andric StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
101739d628a0SDimitry Andric Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
101839d628a0SDimitry Andric
101939d628a0SDimitry Andric Builder.SetInsertPoint(ExitBB, ExitBB->begin());
10203ca95b02SDimitry Andric return Loaded;
102139d628a0SDimitry Andric }
102239d628a0SDimitry Andric
10233ca95b02SDimitry Andric /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
10243ca95b02SDimitry Andric /// the equivalent bitwidth. We used to not support pointer cmpxchg in the
10253ca95b02SDimitry Andric /// IR. As a migration step, we convert back to what use to be the standard
10263ca95b02SDimitry Andric /// way to represent a pointer cmpxchg so that we can update backends one by
10273ca95b02SDimitry Andric /// one.
convertCmpXchgToIntegerType(AtomicCmpXchgInst * CI)10283ca95b02SDimitry Andric AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
10293ca95b02SDimitry Andric auto *M = CI->getModule();
10303ca95b02SDimitry Andric Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
10313ca95b02SDimitry Andric M->getDataLayout());
10323ca95b02SDimitry Andric
10333ca95b02SDimitry Andric IRBuilder<> Builder(CI);
10343ca95b02SDimitry Andric
10353ca95b02SDimitry Andric Value *Addr = CI->getPointerOperand();
10363ca95b02SDimitry Andric Type *PT = PointerType::get(NewTy,
10373ca95b02SDimitry Andric Addr->getType()->getPointerAddressSpace());
10383ca95b02SDimitry Andric Value *NewAddr = Builder.CreateBitCast(Addr, PT);
10393ca95b02SDimitry Andric
10403ca95b02SDimitry Andric Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
10413ca95b02SDimitry Andric Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
10423ca95b02SDimitry Andric
10433ca95b02SDimitry Andric
10443ca95b02SDimitry Andric auto *NewCI = Builder.CreateAtomicCmpXchg(NewAddr, NewCmp, NewNewVal,
10453ca95b02SDimitry Andric CI->getSuccessOrdering(),
10463ca95b02SDimitry Andric CI->getFailureOrdering(),
1047c4394386SDimitry Andric CI->getSyncScopeID());
10483ca95b02SDimitry Andric NewCI->setVolatile(CI->isVolatile());
10493ca95b02SDimitry Andric NewCI->setWeak(CI->isWeak());
10504ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
10513ca95b02SDimitry Andric
10523ca95b02SDimitry Andric Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
10533ca95b02SDimitry Andric Value *Succ = Builder.CreateExtractValue(NewCI, 1);
10543ca95b02SDimitry Andric
10553ca95b02SDimitry Andric OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
10563ca95b02SDimitry Andric
10573ca95b02SDimitry Andric Value *Res = UndefValue::get(CI->getType());
10583ca95b02SDimitry Andric Res = Builder.CreateInsertValue(Res, OldVal, 0);
10593ca95b02SDimitry Andric Res = Builder.CreateInsertValue(Res, Succ, 1);
10603ca95b02SDimitry Andric
10613ca95b02SDimitry Andric CI->replaceAllUsesWith(Res);
10623ca95b02SDimitry Andric CI->eraseFromParent();
10633ca95b02SDimitry Andric return NewCI;
10643ca95b02SDimitry Andric }
10653ca95b02SDimitry Andric
expandAtomicCmpXchg(AtomicCmpXchgInst * CI)106639d628a0SDimitry Andric bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
106739d628a0SDimitry Andric AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
106839d628a0SDimitry Andric AtomicOrdering FailureOrder = CI->getFailureOrdering();
106939d628a0SDimitry Andric Value *Addr = CI->getPointerOperand();
107039d628a0SDimitry Andric BasicBlock *BB = CI->getParent();
107139d628a0SDimitry Andric Function *F = BB->getParent();
107239d628a0SDimitry Andric LLVMContext &Ctx = F->getContext();
10733ca95b02SDimitry Andric // If shouldInsertFencesForAtomic() returns true, then the target does not
10743ca95b02SDimitry Andric // want to deal with memory orders, and emitLeading/TrailingFence should take
10753ca95b02SDimitry Andric // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
107639d628a0SDimitry Andric // should preserve the ordering.
10773ca95b02SDimitry Andric bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
107839d628a0SDimitry Andric AtomicOrdering MemOpOrder =
10793ca95b02SDimitry Andric ShouldInsertFencesForAtomic ? AtomicOrdering::Monotonic : SuccessOrder;
10803ca95b02SDimitry Andric
10813ca95b02SDimitry Andric // In implementations which use a barrier to achieve release semantics, we can
10823ca95b02SDimitry Andric // delay emitting this barrier until we know a store is actually going to be
10833ca95b02SDimitry Andric // attempted. The cost of this delay is that we need 2 copies of the block
10843ca95b02SDimitry Andric // emitting the load-linked, affecting code size.
10853ca95b02SDimitry Andric //
10863ca95b02SDimitry Andric // Ideally, this logic would be unconditional except for the minsize check
10873ca95b02SDimitry Andric // since in other cases the extra blocks naturally collapse down to the
10883ca95b02SDimitry Andric // minimal loop. Unfortunately, this puts too much stress on later
10893ca95b02SDimitry Andric // optimisations so we avoid emitting the extra logic in those cases too.
10903ca95b02SDimitry Andric bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
10913ca95b02SDimitry Andric SuccessOrder != AtomicOrdering::Monotonic &&
10923ca95b02SDimitry Andric SuccessOrder != AtomicOrdering::Acquire &&
10933ca95b02SDimitry Andric !F->optForMinSize();
10943ca95b02SDimitry Andric
10953ca95b02SDimitry Andric // There's no overhead for sinking the release barrier in a weak cmpxchg, so
10963ca95b02SDimitry Andric // do it even on minsize.
10973ca95b02SDimitry Andric bool UseUnconditionalReleaseBarrier = F->optForMinSize() && !CI->isWeak();
109839d628a0SDimitry Andric
109939d628a0SDimitry Andric // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
110039d628a0SDimitry Andric //
110139d628a0SDimitry Andric // The full expansion we produce is:
110239d628a0SDimitry Andric // [...]
110339d628a0SDimitry Andric // cmpxchg.start:
11043ca95b02SDimitry Andric // %unreleasedload = @load.linked(%addr)
11053ca95b02SDimitry Andric // %should_store = icmp eq %unreleasedload, %desired
11063ca95b02SDimitry Andric // br i1 %should_store, label %cmpxchg.fencedstore,
11077d523365SDimitry Andric // label %cmpxchg.nostore
11083ca95b02SDimitry Andric // cmpxchg.releasingstore:
11093ca95b02SDimitry Andric // fence?
11103ca95b02SDimitry Andric // br label cmpxchg.trystore
111139d628a0SDimitry Andric // cmpxchg.trystore:
11123ca95b02SDimitry Andric // %loaded.trystore = phi [%unreleasedload, %releasingstore],
11133ca95b02SDimitry Andric // [%releasedload, %cmpxchg.releasedload]
111439d628a0SDimitry Andric // %stored = @store_conditional(%new, %addr)
111539d628a0SDimitry Andric // %success = icmp eq i32 %stored, 0
11163ca95b02SDimitry Andric // br i1 %success, label %cmpxchg.success,
11173ca95b02SDimitry Andric // label %cmpxchg.releasedload/%cmpxchg.failure
11183ca95b02SDimitry Andric // cmpxchg.releasedload:
11193ca95b02SDimitry Andric // %releasedload = @load.linked(%addr)
11203ca95b02SDimitry Andric // %should_store = icmp eq %releasedload, %desired
11213ca95b02SDimitry Andric // br i1 %should_store, label %cmpxchg.trystore,
11223ca95b02SDimitry Andric // label %cmpxchg.failure
112339d628a0SDimitry Andric // cmpxchg.success:
112439d628a0SDimitry Andric // fence?
112539d628a0SDimitry Andric // br label %cmpxchg.end
11267d523365SDimitry Andric // cmpxchg.nostore:
11273ca95b02SDimitry Andric // %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
11283ca95b02SDimitry Andric // [%releasedload,
11293ca95b02SDimitry Andric // %cmpxchg.releasedload/%cmpxchg.trystore]
11307d523365SDimitry Andric // @load_linked_fail_balance()?
11317d523365SDimitry Andric // br label %cmpxchg.failure
113239d628a0SDimitry Andric // cmpxchg.failure:
113339d628a0SDimitry Andric // fence?
113439d628a0SDimitry Andric // br label %cmpxchg.end
113539d628a0SDimitry Andric // cmpxchg.end:
11363ca95b02SDimitry Andric // %loaded = phi [%loaded.nostore, %cmpxchg.failure],
11373ca95b02SDimitry Andric // [%loaded.trystore, %cmpxchg.trystore]
113839d628a0SDimitry Andric // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
113939d628a0SDimitry Andric // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
114039d628a0SDimitry Andric // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
114139d628a0SDimitry Andric // [...]
11427d523365SDimitry Andric BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
114339d628a0SDimitry Andric auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
11447d523365SDimitry Andric auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
11457d523365SDimitry Andric auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
11463ca95b02SDimitry Andric auto ReleasedLoadBB =
11473ca95b02SDimitry Andric BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
11483ca95b02SDimitry Andric auto TryStoreBB =
11493ca95b02SDimitry Andric BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
11503ca95b02SDimitry Andric auto ReleasingStoreBB =
11513ca95b02SDimitry Andric BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
11523ca95b02SDimitry Andric auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
115339d628a0SDimitry Andric
115439d628a0SDimitry Andric // This grabs the DebugLoc from CI
115539d628a0SDimitry Andric IRBuilder<> Builder(CI);
115639d628a0SDimitry Andric
115739d628a0SDimitry Andric // The split call above "helpfully" added a branch at the end of BB (to the
115839d628a0SDimitry Andric // wrong place), but we might want a fence too. It's easiest to just remove
115939d628a0SDimitry Andric // the branch entirely.
116039d628a0SDimitry Andric std::prev(BB->end())->eraseFromParent();
116139d628a0SDimitry Andric Builder.SetInsertPoint(BB);
11623ca95b02SDimitry Andric if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
11635517e702SDimitry Andric TLI->emitLeadingFence(Builder, CI, SuccessOrder);
11643ca95b02SDimitry Andric Builder.CreateBr(StartBB);
116539d628a0SDimitry Andric
116639d628a0SDimitry Andric // Start the main loop block now that we've taken care of the preliminaries.
11673ca95b02SDimitry Andric Builder.SetInsertPoint(StartBB);
11683ca95b02SDimitry Andric Value *UnreleasedLoad = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
11693ca95b02SDimitry Andric Value *ShouldStore = Builder.CreateICmpEQ(
11703ca95b02SDimitry Andric UnreleasedLoad, CI->getCompareOperand(), "should_store");
117139d628a0SDimitry Andric
11728f0fd8f6SDimitry Andric // If the cmpxchg doesn't actually need any ordering when it fails, we can
117339d628a0SDimitry Andric // jump straight past that fence instruction (if it exists).
11743ca95b02SDimitry Andric Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
11753ca95b02SDimitry Andric
11763ca95b02SDimitry Andric Builder.SetInsertPoint(ReleasingStoreBB);
11773ca95b02SDimitry Andric if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
11785517e702SDimitry Andric TLI->emitLeadingFence(Builder, CI, SuccessOrder);
11793ca95b02SDimitry Andric Builder.CreateBr(TryStoreBB);
118039d628a0SDimitry Andric
118139d628a0SDimitry Andric Builder.SetInsertPoint(TryStoreBB);
118239d628a0SDimitry Andric Value *StoreSuccess = TLI->emitStoreConditional(
118339d628a0SDimitry Andric Builder, CI->getNewValOperand(), Addr, MemOpOrder);
118439d628a0SDimitry Andric StoreSuccess = Builder.CreateICmpEQ(
118539d628a0SDimitry Andric StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
11863ca95b02SDimitry Andric BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
118739d628a0SDimitry Andric Builder.CreateCondBr(StoreSuccess, SuccessBB,
11883ca95b02SDimitry Andric CI->isWeak() ? FailureBB : RetryBB);
118939d628a0SDimitry Andric
11903ca95b02SDimitry Andric Builder.SetInsertPoint(ReleasedLoadBB);
11913ca95b02SDimitry Andric Value *SecondLoad;
11923ca95b02SDimitry Andric if (HasReleasedLoadBB) {
11933ca95b02SDimitry Andric SecondLoad = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
11943ca95b02SDimitry Andric ShouldStore = Builder.CreateICmpEQ(SecondLoad, CI->getCompareOperand(),
11953ca95b02SDimitry Andric "should_store");
11963ca95b02SDimitry Andric
11973ca95b02SDimitry Andric // If the cmpxchg doesn't actually need any ordering when it fails, we can
11983ca95b02SDimitry Andric // jump straight past that fence instruction (if it exists).
11993ca95b02SDimitry Andric Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
12003ca95b02SDimitry Andric } else
12013ca95b02SDimitry Andric Builder.CreateUnreachable();
12023ca95b02SDimitry Andric
12033ca95b02SDimitry Andric // Make sure later instructions don't get reordered with a fence if
12043ca95b02SDimitry Andric // necessary.
120539d628a0SDimitry Andric Builder.SetInsertPoint(SuccessBB);
12063ca95b02SDimitry Andric if (ShouldInsertFencesForAtomic)
12075517e702SDimitry Andric TLI->emitTrailingFence(Builder, CI, SuccessOrder);
120839d628a0SDimitry Andric Builder.CreateBr(ExitBB);
120939d628a0SDimitry Andric
12107d523365SDimitry Andric Builder.SetInsertPoint(NoStoreBB);
12117d523365SDimitry Andric // In the failing case, where we don't execute the store-conditional, the
12127d523365SDimitry Andric // target might want to balance out the load-linked with a dedicated
12137d523365SDimitry Andric // instruction (e.g., on ARM, clearing the exclusive monitor).
12147d523365SDimitry Andric TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
12157d523365SDimitry Andric Builder.CreateBr(FailureBB);
12167d523365SDimitry Andric
121739d628a0SDimitry Andric Builder.SetInsertPoint(FailureBB);
12183ca95b02SDimitry Andric if (ShouldInsertFencesForAtomic)
12195517e702SDimitry Andric TLI->emitTrailingFence(Builder, CI, FailureOrder);
122039d628a0SDimitry Andric Builder.CreateBr(ExitBB);
122139d628a0SDimitry Andric
122239d628a0SDimitry Andric // Finally, we have control-flow based knowledge of whether the cmpxchg
122339d628a0SDimitry Andric // succeeded or not. We expose this to later passes by converting any
12243ca95b02SDimitry Andric // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
12253ca95b02SDimitry Andric // PHI.
122639d628a0SDimitry Andric Builder.SetInsertPoint(ExitBB, ExitBB->begin());
122739d628a0SDimitry Andric PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
122839d628a0SDimitry Andric Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
122939d628a0SDimitry Andric Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
123039d628a0SDimitry Andric
12313ca95b02SDimitry Andric // Setup the builder so we can create any PHIs we need.
12323ca95b02SDimitry Andric Value *Loaded;
12333ca95b02SDimitry Andric if (!HasReleasedLoadBB)
12343ca95b02SDimitry Andric Loaded = UnreleasedLoad;
12353ca95b02SDimitry Andric else {
12363ca95b02SDimitry Andric Builder.SetInsertPoint(TryStoreBB, TryStoreBB->begin());
12373ca95b02SDimitry Andric PHINode *TryStoreLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
12383ca95b02SDimitry Andric TryStoreLoaded->addIncoming(UnreleasedLoad, ReleasingStoreBB);
12393ca95b02SDimitry Andric TryStoreLoaded->addIncoming(SecondLoad, ReleasedLoadBB);
12403ca95b02SDimitry Andric
12413ca95b02SDimitry Andric Builder.SetInsertPoint(NoStoreBB, NoStoreBB->begin());
12423ca95b02SDimitry Andric PHINode *NoStoreLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
12433ca95b02SDimitry Andric NoStoreLoaded->addIncoming(UnreleasedLoad, StartBB);
12443ca95b02SDimitry Andric NoStoreLoaded->addIncoming(SecondLoad, ReleasedLoadBB);
12453ca95b02SDimitry Andric
12463ca95b02SDimitry Andric Builder.SetInsertPoint(ExitBB, ++ExitBB->begin());
12473ca95b02SDimitry Andric PHINode *ExitLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
12483ca95b02SDimitry Andric ExitLoaded->addIncoming(TryStoreLoaded, SuccessBB);
12493ca95b02SDimitry Andric ExitLoaded->addIncoming(NoStoreLoaded, FailureBB);
12503ca95b02SDimitry Andric
12513ca95b02SDimitry Andric Loaded = ExitLoaded;
12523ca95b02SDimitry Andric }
12533ca95b02SDimitry Andric
125439d628a0SDimitry Andric // Look for any users of the cmpxchg that are just comparing the loaded value
125539d628a0SDimitry Andric // against the desired one, and replace them with the CFG-derived version.
125639d628a0SDimitry Andric SmallVector<ExtractValueInst *, 2> PrunedInsts;
125739d628a0SDimitry Andric for (auto User : CI->users()) {
125839d628a0SDimitry Andric ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
125939d628a0SDimitry Andric if (!EV)
126039d628a0SDimitry Andric continue;
126139d628a0SDimitry Andric
126239d628a0SDimitry Andric assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
126339d628a0SDimitry Andric "weird extraction from { iN, i1 }");
126439d628a0SDimitry Andric
126539d628a0SDimitry Andric if (EV->getIndices()[0] == 0)
126639d628a0SDimitry Andric EV->replaceAllUsesWith(Loaded);
126739d628a0SDimitry Andric else
126839d628a0SDimitry Andric EV->replaceAllUsesWith(Success);
126939d628a0SDimitry Andric
127039d628a0SDimitry Andric PrunedInsts.push_back(EV);
127139d628a0SDimitry Andric }
127239d628a0SDimitry Andric
127339d628a0SDimitry Andric // We can remove the instructions now we're no longer iterating through them.
127439d628a0SDimitry Andric for (auto EV : PrunedInsts)
127539d628a0SDimitry Andric EV->eraseFromParent();
127639d628a0SDimitry Andric
127739d628a0SDimitry Andric if (!CI->use_empty()) {
127839d628a0SDimitry Andric // Some use of the full struct return that we don't understand has happened,
127939d628a0SDimitry Andric // so we've got to reconstruct it properly.
128039d628a0SDimitry Andric Value *Res;
128139d628a0SDimitry Andric Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
128239d628a0SDimitry Andric Res = Builder.CreateInsertValue(Res, Success, 1);
128339d628a0SDimitry Andric
128439d628a0SDimitry Andric CI->replaceAllUsesWith(Res);
128539d628a0SDimitry Andric }
128639d628a0SDimitry Andric
128739d628a0SDimitry Andric CI->eraseFromParent();
128839d628a0SDimitry Andric return true;
128939d628a0SDimitry Andric }
129039d628a0SDimitry Andric
isIdempotentRMW(AtomicRMWInst * RMWI)129139d628a0SDimitry Andric bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
129239d628a0SDimitry Andric auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
129339d628a0SDimitry Andric if(!C)
129439d628a0SDimitry Andric return false;
129539d628a0SDimitry Andric
129639d628a0SDimitry Andric AtomicRMWInst::BinOp Op = RMWI->getOperation();
129739d628a0SDimitry Andric switch(Op) {
129839d628a0SDimitry Andric case AtomicRMWInst::Add:
129939d628a0SDimitry Andric case AtomicRMWInst::Sub:
130039d628a0SDimitry Andric case AtomicRMWInst::Or:
130139d628a0SDimitry Andric case AtomicRMWInst::Xor:
130239d628a0SDimitry Andric return C->isZero();
130339d628a0SDimitry Andric case AtomicRMWInst::And:
130439d628a0SDimitry Andric return C->isMinusOne();
130539d628a0SDimitry Andric // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
130639d628a0SDimitry Andric default:
130739d628a0SDimitry Andric return false;
130839d628a0SDimitry Andric }
130939d628a0SDimitry Andric }
131039d628a0SDimitry Andric
simplifyIdempotentRMW(AtomicRMWInst * RMWI)131139d628a0SDimitry Andric bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
131239d628a0SDimitry Andric if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
13137d523365SDimitry Andric tryExpandAtomicLoad(ResultingLoad);
131439d628a0SDimitry Andric return true;
131539d628a0SDimitry Andric }
131639d628a0SDimitry Andric return false;
131739d628a0SDimitry Andric }
13187d523365SDimitry Andric
insertRMWCmpXchgLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp,CreateCmpXchgInstFun CreateCmpXchg)13193ca95b02SDimitry Andric Value *AtomicExpand::insertRMWCmpXchgLoop(
13203ca95b02SDimitry Andric IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
13213ca95b02SDimitry Andric AtomicOrdering MemOpOrder,
13223ca95b02SDimitry Andric function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
13237d523365SDimitry Andric CreateCmpXchgInstFun CreateCmpXchg) {
13243ca95b02SDimitry Andric LLVMContext &Ctx = Builder.getContext();
13253ca95b02SDimitry Andric BasicBlock *BB = Builder.GetInsertBlock();
13267d523365SDimitry Andric Function *F = BB->getParent();
13277d523365SDimitry Andric
13287d523365SDimitry Andric // Given: atomicrmw some_op iN* %addr, iN %incr ordering
13297d523365SDimitry Andric //
13307d523365SDimitry Andric // The standard expansion we produce is:
13317d523365SDimitry Andric // [...]
13327d523365SDimitry Andric // %init_loaded = load atomic iN* %addr
13337d523365SDimitry Andric // br label %loop
13347d523365SDimitry Andric // loop:
13357d523365SDimitry Andric // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
13367d523365SDimitry Andric // %new = some_op iN %loaded, %incr
13377d523365SDimitry Andric // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
13387d523365SDimitry Andric // %new_loaded = extractvalue { iN, i1 } %pair, 0
13397d523365SDimitry Andric // %success = extractvalue { iN, i1 } %pair, 1
13407d523365SDimitry Andric // br i1 %success, label %atomicrmw.end, label %loop
13417d523365SDimitry Andric // atomicrmw.end:
13427d523365SDimitry Andric // [...]
13433ca95b02SDimitry Andric BasicBlock *ExitBB =
13443ca95b02SDimitry Andric BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
13457d523365SDimitry Andric BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
13467d523365SDimitry Andric
13477d523365SDimitry Andric // The split call above "helpfully" added a branch at the end of BB (to the
13487d523365SDimitry Andric // wrong place), but we want a load. It's easiest to just remove
13497d523365SDimitry Andric // the branch entirely.
13507d523365SDimitry Andric std::prev(BB->end())->eraseFromParent();
13517d523365SDimitry Andric Builder.SetInsertPoint(BB);
13523ca95b02SDimitry Andric LoadInst *InitLoaded = Builder.CreateLoad(ResultTy, Addr);
13537d523365SDimitry Andric // Atomics require at least natural alignment.
13543ca95b02SDimitry Andric InitLoaded->setAlignment(ResultTy->getPrimitiveSizeInBits() / 8);
13557d523365SDimitry Andric Builder.CreateBr(LoopBB);
13567d523365SDimitry Andric
13577d523365SDimitry Andric // Start the main loop block now that we've taken care of the preliminaries.
13587d523365SDimitry Andric Builder.SetInsertPoint(LoopBB);
13593ca95b02SDimitry Andric PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
13607d523365SDimitry Andric Loaded->addIncoming(InitLoaded, BB);
13617d523365SDimitry Andric
13623ca95b02SDimitry Andric Value *NewVal = PerformOp(Builder, Loaded);
13637d523365SDimitry Andric
13647d523365SDimitry Andric Value *NewLoaded = nullptr;
13657d523365SDimitry Andric Value *Success = nullptr;
13667d523365SDimitry Andric
13673ca95b02SDimitry Andric CreateCmpXchg(Builder, Addr, Loaded, NewVal,
13683ca95b02SDimitry Andric MemOpOrder == AtomicOrdering::Unordered
13693ca95b02SDimitry Andric ? AtomicOrdering::Monotonic
13703ca95b02SDimitry Andric : MemOpOrder,
13717d523365SDimitry Andric Success, NewLoaded);
13727d523365SDimitry Andric assert(Success && NewLoaded);
13737d523365SDimitry Andric
13747d523365SDimitry Andric Loaded->addIncoming(NewLoaded, LoopBB);
13757d523365SDimitry Andric
13767d523365SDimitry Andric Builder.CreateCondBr(Success, ExitBB, LoopBB);
13777d523365SDimitry Andric
13787d523365SDimitry Andric Builder.SetInsertPoint(ExitBB, ExitBB->begin());
13793ca95b02SDimitry Andric return NewLoaded;
13803ca95b02SDimitry Andric }
13817d523365SDimitry Andric
tryExpandAtomicCmpXchg(AtomicCmpXchgInst * CI)1382*b5893f02SDimitry Andric bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1383*b5893f02SDimitry Andric unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1384*b5893f02SDimitry Andric unsigned ValueSize = getAtomicOpSize(CI);
1385*b5893f02SDimitry Andric
1386*b5893f02SDimitry Andric switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1387*b5893f02SDimitry Andric default:
1388*b5893f02SDimitry Andric llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1389*b5893f02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::None:
1390*b5893f02SDimitry Andric if (ValueSize < MinCASSize)
1391*b5893f02SDimitry Andric expandPartwordCmpXchg(CI);
1392*b5893f02SDimitry Andric return false;
1393*b5893f02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::LLSC: {
1394*b5893f02SDimitry Andric assert(ValueSize >= MinCASSize &&
1395*b5893f02SDimitry Andric "MinCmpXchgSizeInBits not yet supported for LL/SC expansions.");
1396*b5893f02SDimitry Andric return expandAtomicCmpXchg(CI);
1397*b5893f02SDimitry Andric }
1398*b5893f02SDimitry Andric case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
1399*b5893f02SDimitry Andric expandAtomicCmpXchgToMaskedIntrinsic(CI);
1400*b5893f02SDimitry Andric return true;
1401*b5893f02SDimitry Andric }
1402*b5893f02SDimitry Andric }
1403*b5893f02SDimitry Andric
14043ca95b02SDimitry Andric // Note: This function is exposed externally by AtomicExpandUtils.h
expandAtomicRMWToCmpXchg(AtomicRMWInst * AI,CreateCmpXchgInstFun CreateCmpXchg)14053ca95b02SDimitry Andric bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
14063ca95b02SDimitry Andric CreateCmpXchgInstFun CreateCmpXchg) {
14073ca95b02SDimitry Andric IRBuilder<> Builder(AI);
14083ca95b02SDimitry Andric Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
14093ca95b02SDimitry Andric Builder, AI->getType(), AI->getPointerOperand(), AI->getOrdering(),
14103ca95b02SDimitry Andric [&](IRBuilder<> &Builder, Value *Loaded) {
14113ca95b02SDimitry Andric return performAtomicOp(AI->getOperation(), Builder, Loaded,
14123ca95b02SDimitry Andric AI->getValOperand());
14133ca95b02SDimitry Andric },
14143ca95b02SDimitry Andric CreateCmpXchg);
14153ca95b02SDimitry Andric
14163ca95b02SDimitry Andric AI->replaceAllUsesWith(Loaded);
14177d523365SDimitry Andric AI->eraseFromParent();
14183ca95b02SDimitry Andric return true;
14193ca95b02SDimitry Andric }
14207d523365SDimitry Andric
14213ca95b02SDimitry Andric // In order to use one of the sized library calls such as
14223ca95b02SDimitry Andric // __atomic_fetch_add_4, the alignment must be sufficient, the size
14233ca95b02SDimitry Andric // must be one of the potentially-specialized sizes, and the value
14243ca95b02SDimitry Andric // type must actually exist in C on the target (otherwise, the
14253ca95b02SDimitry Andric // function wouldn't actually be defined.)
canUseSizedAtomicCall(unsigned Size,unsigned Align,const DataLayout & DL)14263ca95b02SDimitry Andric static bool canUseSizedAtomicCall(unsigned Size, unsigned Align,
14273ca95b02SDimitry Andric const DataLayout &DL) {
14283ca95b02SDimitry Andric // TODO: "LargestSize" is an approximation for "largest type that
14293ca95b02SDimitry Andric // you can express in C". It seems to be the case that int128 is
14303ca95b02SDimitry Andric // supported on all 64-bit platforms, otherwise only up to 64-bit
14313ca95b02SDimitry Andric // integers are supported. If we get this wrong, then we'll try to
14323ca95b02SDimitry Andric // call a sized libcall that doesn't actually exist. There should
14333ca95b02SDimitry Andric // really be some more reliable way in LLVM of determining integer
14343ca95b02SDimitry Andric // sizes which are valid in the target's C ABI...
14353ca95b02SDimitry Andric unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
14363ca95b02SDimitry Andric return Align >= Size &&
14373ca95b02SDimitry Andric (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
14383ca95b02SDimitry Andric Size <= LargestSize;
14393ca95b02SDimitry Andric }
14403ca95b02SDimitry Andric
expandAtomicLoadToLibcall(LoadInst * I)14413ca95b02SDimitry Andric void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
14423ca95b02SDimitry Andric static const RTLIB::Libcall Libcalls[6] = {
14433ca95b02SDimitry Andric RTLIB::ATOMIC_LOAD, RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
14443ca95b02SDimitry Andric RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
14453ca95b02SDimitry Andric unsigned Size = getAtomicOpSize(I);
14463ca95b02SDimitry Andric unsigned Align = getAtomicOpAlign(I);
14473ca95b02SDimitry Andric
14483ca95b02SDimitry Andric bool expanded = expandAtomicOpToLibcall(
14493ca95b02SDimitry Andric I, Size, Align, I->getPointerOperand(), nullptr, nullptr,
14503ca95b02SDimitry Andric I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
14513ca95b02SDimitry Andric (void)expanded;
14523ca95b02SDimitry Andric assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Load");
14533ca95b02SDimitry Andric }
14543ca95b02SDimitry Andric
expandAtomicStoreToLibcall(StoreInst * I)14553ca95b02SDimitry Andric void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
14563ca95b02SDimitry Andric static const RTLIB::Libcall Libcalls[6] = {
14573ca95b02SDimitry Andric RTLIB::ATOMIC_STORE, RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
14583ca95b02SDimitry Andric RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
14593ca95b02SDimitry Andric unsigned Size = getAtomicOpSize(I);
14603ca95b02SDimitry Andric unsigned Align = getAtomicOpAlign(I);
14613ca95b02SDimitry Andric
14623ca95b02SDimitry Andric bool expanded = expandAtomicOpToLibcall(
14633ca95b02SDimitry Andric I, Size, Align, I->getPointerOperand(), I->getValueOperand(), nullptr,
14643ca95b02SDimitry Andric I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
14653ca95b02SDimitry Andric (void)expanded;
14663ca95b02SDimitry Andric assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Store");
14673ca95b02SDimitry Andric }
14683ca95b02SDimitry Andric
expandAtomicCASToLibcall(AtomicCmpXchgInst * I)14693ca95b02SDimitry Andric void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
14703ca95b02SDimitry Andric static const RTLIB::Libcall Libcalls[6] = {
14713ca95b02SDimitry Andric RTLIB::ATOMIC_COMPARE_EXCHANGE, RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
14723ca95b02SDimitry Andric RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
14733ca95b02SDimitry Andric RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
14743ca95b02SDimitry Andric unsigned Size = getAtomicOpSize(I);
14753ca95b02SDimitry Andric unsigned Align = getAtomicOpAlign(I);
14763ca95b02SDimitry Andric
14773ca95b02SDimitry Andric bool expanded = expandAtomicOpToLibcall(
14783ca95b02SDimitry Andric I, Size, Align, I->getPointerOperand(), I->getNewValOperand(),
14793ca95b02SDimitry Andric I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
14803ca95b02SDimitry Andric Libcalls);
14813ca95b02SDimitry Andric (void)expanded;
14823ca95b02SDimitry Andric assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor CAS");
14833ca95b02SDimitry Andric }
14843ca95b02SDimitry Andric
GetRMWLibcall(AtomicRMWInst::BinOp Op)14853ca95b02SDimitry Andric static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
14863ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsXchg[6] = {
14873ca95b02SDimitry Andric RTLIB::ATOMIC_EXCHANGE, RTLIB::ATOMIC_EXCHANGE_1,
14883ca95b02SDimitry Andric RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
14893ca95b02SDimitry Andric RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
14903ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsAdd[6] = {
14913ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_ADD_1,
14923ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
14933ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
14943ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsSub[6] = {
14953ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_SUB_1,
14963ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
14973ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
14983ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsAnd[6] = {
14993ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_AND_1,
15003ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
15013ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
15023ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsOr[6] = {
15033ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_OR_1,
15043ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
15053ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
15063ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsXor[6] = {
15073ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_XOR_1,
15083ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
15093ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
15103ca95b02SDimitry Andric static const RTLIB::Libcall LibcallsNand[6] = {
15113ca95b02SDimitry Andric RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_NAND_1,
15123ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
15133ca95b02SDimitry Andric RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
15143ca95b02SDimitry Andric
15153ca95b02SDimitry Andric switch (Op) {
15163ca95b02SDimitry Andric case AtomicRMWInst::BAD_BINOP:
15173ca95b02SDimitry Andric llvm_unreachable("Should not have BAD_BINOP.");
15183ca95b02SDimitry Andric case AtomicRMWInst::Xchg:
15193ca95b02SDimitry Andric return makeArrayRef(LibcallsXchg);
15203ca95b02SDimitry Andric case AtomicRMWInst::Add:
15213ca95b02SDimitry Andric return makeArrayRef(LibcallsAdd);
15223ca95b02SDimitry Andric case AtomicRMWInst::Sub:
15233ca95b02SDimitry Andric return makeArrayRef(LibcallsSub);
15243ca95b02SDimitry Andric case AtomicRMWInst::And:
15253ca95b02SDimitry Andric return makeArrayRef(LibcallsAnd);
15263ca95b02SDimitry Andric case AtomicRMWInst::Or:
15273ca95b02SDimitry Andric return makeArrayRef(LibcallsOr);
15283ca95b02SDimitry Andric case AtomicRMWInst::Xor:
15293ca95b02SDimitry Andric return makeArrayRef(LibcallsXor);
15303ca95b02SDimitry Andric case AtomicRMWInst::Nand:
15313ca95b02SDimitry Andric return makeArrayRef(LibcallsNand);
15323ca95b02SDimitry Andric case AtomicRMWInst::Max:
15333ca95b02SDimitry Andric case AtomicRMWInst::Min:
15343ca95b02SDimitry Andric case AtomicRMWInst::UMax:
15353ca95b02SDimitry Andric case AtomicRMWInst::UMin:
15363ca95b02SDimitry Andric // No atomic libcalls are available for max/min/umax/umin.
15373ca95b02SDimitry Andric return {};
15383ca95b02SDimitry Andric }
15393ca95b02SDimitry Andric llvm_unreachable("Unexpected AtomicRMW operation.");
15403ca95b02SDimitry Andric }
15413ca95b02SDimitry Andric
expandAtomicRMWToLibcall(AtomicRMWInst * I)15423ca95b02SDimitry Andric void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
15433ca95b02SDimitry Andric ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
15443ca95b02SDimitry Andric
15453ca95b02SDimitry Andric unsigned Size = getAtomicOpSize(I);
15463ca95b02SDimitry Andric unsigned Align = getAtomicOpAlign(I);
15473ca95b02SDimitry Andric
15483ca95b02SDimitry Andric bool Success = false;
15493ca95b02SDimitry Andric if (!Libcalls.empty())
15503ca95b02SDimitry Andric Success = expandAtomicOpToLibcall(
15513ca95b02SDimitry Andric I, Size, Align, I->getPointerOperand(), I->getValOperand(), nullptr,
15523ca95b02SDimitry Andric I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
15533ca95b02SDimitry Andric
15543ca95b02SDimitry Andric // The expansion failed: either there were no libcalls at all for
15553ca95b02SDimitry Andric // the operation (min/max), or there were only size-specialized
15563ca95b02SDimitry Andric // libcalls (add/sub/etc) and we needed a generic. So, expand to a
15573ca95b02SDimitry Andric // CAS libcall, via a CAS loop, instead.
15583ca95b02SDimitry Andric if (!Success) {
15593ca95b02SDimitry Andric expandAtomicRMWToCmpXchg(I, [this](IRBuilder<> &Builder, Value *Addr,
15603ca95b02SDimitry Andric Value *Loaded, Value *NewVal,
15613ca95b02SDimitry Andric AtomicOrdering MemOpOrder,
15623ca95b02SDimitry Andric Value *&Success, Value *&NewLoaded) {
15633ca95b02SDimitry Andric // Create the CAS instruction normally...
15643ca95b02SDimitry Andric AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
15653ca95b02SDimitry Andric Addr, Loaded, NewVal, MemOpOrder,
15663ca95b02SDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
15673ca95b02SDimitry Andric Success = Builder.CreateExtractValue(Pair, 1, "success");
15683ca95b02SDimitry Andric NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
15693ca95b02SDimitry Andric
15703ca95b02SDimitry Andric // ...and then expand the CAS into a libcall.
15713ca95b02SDimitry Andric expandAtomicCASToLibcall(Pair);
15723ca95b02SDimitry Andric });
15733ca95b02SDimitry Andric }
15743ca95b02SDimitry Andric }
15753ca95b02SDimitry Andric
15763ca95b02SDimitry Andric // A helper routine for the above expandAtomic*ToLibcall functions.
15773ca95b02SDimitry Andric //
15783ca95b02SDimitry Andric // 'Libcalls' contains an array of enum values for the particular
15793ca95b02SDimitry Andric // ATOMIC libcalls to be emitted. All of the other arguments besides
15803ca95b02SDimitry Andric // 'I' are extracted from the Instruction subclass by the
15813ca95b02SDimitry Andric // caller. Depending on the particular call, some will be null.
expandAtomicOpToLibcall(Instruction * I,unsigned Size,unsigned Align,Value * PointerOperand,Value * ValueOperand,Value * CASExpected,AtomicOrdering Ordering,AtomicOrdering Ordering2,ArrayRef<RTLIB::Libcall> Libcalls)15823ca95b02SDimitry Andric bool AtomicExpand::expandAtomicOpToLibcall(
15833ca95b02SDimitry Andric Instruction *I, unsigned Size, unsigned Align, Value *PointerOperand,
15843ca95b02SDimitry Andric Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
15853ca95b02SDimitry Andric AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
15863ca95b02SDimitry Andric assert(Libcalls.size() == 6);
15873ca95b02SDimitry Andric
15883ca95b02SDimitry Andric LLVMContext &Ctx = I->getContext();
15893ca95b02SDimitry Andric Module *M = I->getModule();
15903ca95b02SDimitry Andric const DataLayout &DL = M->getDataLayout();
15913ca95b02SDimitry Andric IRBuilder<> Builder(I);
15923ca95b02SDimitry Andric IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
15933ca95b02SDimitry Andric
15943ca95b02SDimitry Andric bool UseSizedLibcall = canUseSizedAtomicCall(Size, Align, DL);
15953ca95b02SDimitry Andric Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
15963ca95b02SDimitry Andric
15973ca95b02SDimitry Andric unsigned AllocaAlignment = DL.getPrefTypeAlignment(SizedIntTy);
15983ca95b02SDimitry Andric
15993ca95b02SDimitry Andric // TODO: the "order" argument type is "int", not int32. So
16003ca95b02SDimitry Andric // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
16013ca95b02SDimitry Andric ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
16023ca95b02SDimitry Andric assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
16033ca95b02SDimitry Andric Constant *OrderingVal =
16043ca95b02SDimitry Andric ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
16053ca95b02SDimitry Andric Constant *Ordering2Val = nullptr;
16063ca95b02SDimitry Andric if (CASExpected) {
16073ca95b02SDimitry Andric assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
16083ca95b02SDimitry Andric Ordering2Val =
16093ca95b02SDimitry Andric ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
16103ca95b02SDimitry Andric }
16113ca95b02SDimitry Andric bool HasResult = I->getType() != Type::getVoidTy(Ctx);
16123ca95b02SDimitry Andric
16133ca95b02SDimitry Andric RTLIB::Libcall RTLibType;
16143ca95b02SDimitry Andric if (UseSizedLibcall) {
16153ca95b02SDimitry Andric switch (Size) {
16163ca95b02SDimitry Andric case 1: RTLibType = Libcalls[1]; break;
16173ca95b02SDimitry Andric case 2: RTLibType = Libcalls[2]; break;
16183ca95b02SDimitry Andric case 4: RTLibType = Libcalls[3]; break;
16193ca95b02SDimitry Andric case 8: RTLibType = Libcalls[4]; break;
16203ca95b02SDimitry Andric case 16: RTLibType = Libcalls[5]; break;
16213ca95b02SDimitry Andric }
16223ca95b02SDimitry Andric } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
16233ca95b02SDimitry Andric RTLibType = Libcalls[0];
16243ca95b02SDimitry Andric } else {
16253ca95b02SDimitry Andric // Can't use sized function, and there's no generic for this
16263ca95b02SDimitry Andric // operation, so give up.
16273ca95b02SDimitry Andric return false;
16283ca95b02SDimitry Andric }
16293ca95b02SDimitry Andric
16303ca95b02SDimitry Andric // Build up the function call. There's two kinds. First, the sized
16313ca95b02SDimitry Andric // variants. These calls are going to be one of the following (with
16323ca95b02SDimitry Andric // N=1,2,4,8,16):
16333ca95b02SDimitry Andric // iN __atomic_load_N(iN *ptr, int ordering)
16343ca95b02SDimitry Andric // void __atomic_store_N(iN *ptr, iN val, int ordering)
16353ca95b02SDimitry Andric // iN __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
16363ca95b02SDimitry Andric // bool __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
16373ca95b02SDimitry Andric // int success_order, int failure_order)
16383ca95b02SDimitry Andric //
16393ca95b02SDimitry Andric // Note that these functions can be used for non-integer atomic
16403ca95b02SDimitry Andric // operations, the values just need to be bitcast to integers on the
16413ca95b02SDimitry Andric // way in and out.
16423ca95b02SDimitry Andric //
16433ca95b02SDimitry Andric // And, then, the generic variants. They look like the following:
16443ca95b02SDimitry Andric // void __atomic_load(size_t size, void *ptr, void *ret, int ordering)
16453ca95b02SDimitry Andric // void __atomic_store(size_t size, void *ptr, void *val, int ordering)
16463ca95b02SDimitry Andric // void __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
16473ca95b02SDimitry Andric // int ordering)
16483ca95b02SDimitry Andric // bool __atomic_compare_exchange(size_t size, void *ptr, void *expected,
16493ca95b02SDimitry Andric // void *desired, int success_order,
16503ca95b02SDimitry Andric // int failure_order)
16513ca95b02SDimitry Andric //
16523ca95b02SDimitry Andric // The different signatures are built up depending on the
16533ca95b02SDimitry Andric // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
16543ca95b02SDimitry Andric // variables.
16553ca95b02SDimitry Andric
16563ca95b02SDimitry Andric AllocaInst *AllocaCASExpected = nullptr;
16573ca95b02SDimitry Andric Value *AllocaCASExpected_i8 = nullptr;
16583ca95b02SDimitry Andric AllocaInst *AllocaValue = nullptr;
16593ca95b02SDimitry Andric Value *AllocaValue_i8 = nullptr;
16603ca95b02SDimitry Andric AllocaInst *AllocaResult = nullptr;
16613ca95b02SDimitry Andric Value *AllocaResult_i8 = nullptr;
16623ca95b02SDimitry Andric
16633ca95b02SDimitry Andric Type *ResultTy;
16643ca95b02SDimitry Andric SmallVector<Value *, 6> Args;
16657a7e6055SDimitry Andric AttributeList Attr;
16663ca95b02SDimitry Andric
16673ca95b02SDimitry Andric // 'size' argument.
16683ca95b02SDimitry Andric if (!UseSizedLibcall) {
16693ca95b02SDimitry Andric // Note, getIntPtrType is assumed equivalent to size_t.
16703ca95b02SDimitry Andric Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
16713ca95b02SDimitry Andric }
16723ca95b02SDimitry Andric
16733ca95b02SDimitry Andric // 'ptr' argument.
16743ca95b02SDimitry Andric Value *PtrVal =
16753ca95b02SDimitry Andric Builder.CreateBitCast(PointerOperand, Type::getInt8PtrTy(Ctx));
16763ca95b02SDimitry Andric Args.push_back(PtrVal);
16773ca95b02SDimitry Andric
16783ca95b02SDimitry Andric // 'expected' argument, if present.
16793ca95b02SDimitry Andric if (CASExpected) {
16803ca95b02SDimitry Andric AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
16813ca95b02SDimitry Andric AllocaCASExpected->setAlignment(AllocaAlignment);
16823ca95b02SDimitry Andric AllocaCASExpected_i8 =
16833ca95b02SDimitry Andric Builder.CreateBitCast(AllocaCASExpected, Type::getInt8PtrTy(Ctx));
16843ca95b02SDimitry Andric Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
16853ca95b02SDimitry Andric Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
16863ca95b02SDimitry Andric Args.push_back(AllocaCASExpected_i8);
16873ca95b02SDimitry Andric }
16883ca95b02SDimitry Andric
16893ca95b02SDimitry Andric // 'val' argument ('desired' for cas), if present.
16903ca95b02SDimitry Andric if (ValueOperand) {
16913ca95b02SDimitry Andric if (UseSizedLibcall) {
16923ca95b02SDimitry Andric Value *IntValue =
16933ca95b02SDimitry Andric Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
16943ca95b02SDimitry Andric Args.push_back(IntValue);
16953ca95b02SDimitry Andric } else {
16963ca95b02SDimitry Andric AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
16973ca95b02SDimitry Andric AllocaValue->setAlignment(AllocaAlignment);
16983ca95b02SDimitry Andric AllocaValue_i8 =
16993ca95b02SDimitry Andric Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
17003ca95b02SDimitry Andric Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
17013ca95b02SDimitry Andric Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
17023ca95b02SDimitry Andric Args.push_back(AllocaValue_i8);
17033ca95b02SDimitry Andric }
17043ca95b02SDimitry Andric }
17053ca95b02SDimitry Andric
17063ca95b02SDimitry Andric // 'ret' argument.
17073ca95b02SDimitry Andric if (!CASExpected && HasResult && !UseSizedLibcall) {
17083ca95b02SDimitry Andric AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
17093ca95b02SDimitry Andric AllocaResult->setAlignment(AllocaAlignment);
17103ca95b02SDimitry Andric AllocaResult_i8 =
17113ca95b02SDimitry Andric Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx));
17123ca95b02SDimitry Andric Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
17133ca95b02SDimitry Andric Args.push_back(AllocaResult_i8);
17143ca95b02SDimitry Andric }
17153ca95b02SDimitry Andric
17163ca95b02SDimitry Andric // 'ordering' ('success_order' for cas) argument.
17173ca95b02SDimitry Andric Args.push_back(OrderingVal);
17183ca95b02SDimitry Andric
17193ca95b02SDimitry Andric // 'failure_order' argument, if present.
17203ca95b02SDimitry Andric if (Ordering2Val)
17213ca95b02SDimitry Andric Args.push_back(Ordering2Val);
17223ca95b02SDimitry Andric
17233ca95b02SDimitry Andric // Now, the return type.
17243ca95b02SDimitry Andric if (CASExpected) {
17253ca95b02SDimitry Andric ResultTy = Type::getInt1Ty(Ctx);
17267a7e6055SDimitry Andric Attr = Attr.addAttribute(Ctx, AttributeList::ReturnIndex, Attribute::ZExt);
17273ca95b02SDimitry Andric } else if (HasResult && UseSizedLibcall)
17283ca95b02SDimitry Andric ResultTy = SizedIntTy;
17293ca95b02SDimitry Andric else
17303ca95b02SDimitry Andric ResultTy = Type::getVoidTy(Ctx);
17313ca95b02SDimitry Andric
17323ca95b02SDimitry Andric // Done with setting up arguments and return types, create the call:
17333ca95b02SDimitry Andric SmallVector<Type *, 6> ArgTys;
17343ca95b02SDimitry Andric for (Value *Arg : Args)
17353ca95b02SDimitry Andric ArgTys.push_back(Arg->getType());
17363ca95b02SDimitry Andric FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
17373ca95b02SDimitry Andric Constant *LibcallFn =
17383ca95b02SDimitry Andric M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
17393ca95b02SDimitry Andric CallInst *Call = Builder.CreateCall(LibcallFn, Args);
17403ca95b02SDimitry Andric Call->setAttributes(Attr);
17413ca95b02SDimitry Andric Value *Result = Call;
17423ca95b02SDimitry Andric
17433ca95b02SDimitry Andric // And then, extract the results...
17443ca95b02SDimitry Andric if (ValueOperand && !UseSizedLibcall)
17453ca95b02SDimitry Andric Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
17463ca95b02SDimitry Andric
17473ca95b02SDimitry Andric if (CASExpected) {
17483ca95b02SDimitry Andric // The final result from the CAS is {load of 'expected' alloca, bool result
17493ca95b02SDimitry Andric // from call}
17503ca95b02SDimitry Andric Type *FinalResultTy = I->getType();
17513ca95b02SDimitry Andric Value *V = UndefValue::get(FinalResultTy);
17523ca95b02SDimitry Andric Value *ExpectedOut =
17533ca95b02SDimitry Andric Builder.CreateAlignedLoad(AllocaCASExpected, AllocaAlignment);
17543ca95b02SDimitry Andric Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
17553ca95b02SDimitry Andric V = Builder.CreateInsertValue(V, ExpectedOut, 0);
17563ca95b02SDimitry Andric V = Builder.CreateInsertValue(V, Result, 1);
17573ca95b02SDimitry Andric I->replaceAllUsesWith(V);
17583ca95b02SDimitry Andric } else if (HasResult) {
17593ca95b02SDimitry Andric Value *V;
17603ca95b02SDimitry Andric if (UseSizedLibcall)
17613ca95b02SDimitry Andric V = Builder.CreateBitOrPointerCast(Result, I->getType());
17623ca95b02SDimitry Andric else {
17633ca95b02SDimitry Andric V = Builder.CreateAlignedLoad(AllocaResult, AllocaAlignment);
17643ca95b02SDimitry Andric Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
17653ca95b02SDimitry Andric }
17663ca95b02SDimitry Andric I->replaceAllUsesWith(V);
17673ca95b02SDimitry Andric }
17683ca95b02SDimitry Andric I->eraseFromParent();
17697d523365SDimitry Andric return true;
17707d523365SDimitry Andric }
1771