1 //===-- AtomicExpandLoadLinkedPass.cpp - Expand atomic instructions -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass (at IR level) to replace atomic instructions with
11 // appropriate (intrinsic-based) ldrex/strex loops.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetMachine.h"
26 #define DEBUG_TYPE "arm-atomic-expand"
29 class AtomicExpandLoadLinked : public FunctionPass {
30 const TargetLowering *TLI;
32 static char ID; // Pass identification, replacement for typeid
33 explicit AtomicExpandLoadLinked(const TargetMachine *TM = nullptr)
34 : FunctionPass(ID), TLI(TM ? TM->getTargetLowering() : nullptr) {
35 initializeAtomicExpandLoadLinkedPass(*PassRegistry::getPassRegistry());
38 bool runOnFunction(Function &F) override;
39 bool expandAtomicInsts(Function &F);
41 bool expandAtomicLoad(LoadInst *LI);
42 bool expandAtomicStore(StoreInst *LI);
43 bool expandAtomicRMW(AtomicRMWInst *AI);
44 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
46 AtomicOrdering insertLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
47 void insertTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
51 char AtomicExpandLoadLinked::ID = 0;
52 char &llvm::AtomicExpandLoadLinkedID = AtomicExpandLoadLinked::ID;
53 INITIALIZE_TM_PASS(AtomicExpandLoadLinked, "atomic-ll-sc",
54 "Expand Atomic calls in terms of load-linked & store-conditional",
57 FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
58 return new AtomicExpandLoadLinked(TM);
61 bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
65 SmallVector<Instruction *, 1> AtomicInsts;
67 // Changing control-flow while iterating through it is a bad idea, so gather a
68 // list of all atomic instructions before we start.
69 for (BasicBlock &BB : F)
70 for (Instruction &Inst : BB) {
71 if (isa<AtomicRMWInst>(&Inst) || isa<AtomicCmpXchgInst>(&Inst) ||
72 (isa<LoadInst>(&Inst) && cast<LoadInst>(&Inst)->isAtomic()) ||
73 (isa<StoreInst>(&Inst) && cast<StoreInst>(&Inst)->isAtomic()))
74 AtomicInsts.push_back(&Inst);
77 bool MadeChange = false;
78 for (Instruction *Inst : AtomicInsts) {
79 if (!TLI->shouldExpandAtomicInIR(Inst))
82 if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst))
83 MadeChange |= expandAtomicRMW(AI);
84 else if (AtomicCmpXchgInst *CI = dyn_cast<AtomicCmpXchgInst>(Inst))
85 MadeChange |= expandAtomicCmpXchg(CI);
86 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
87 MadeChange |= expandAtomicLoad(LI);
88 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
89 MadeChange |= expandAtomicStore(SI);
91 llvm_unreachable("Unknown atomic instruction");
97 bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
98 // Load instructions don't actually need a leading fence, even in the
99 // SequentiallyConsistent case.
100 AtomicOrdering MemOpOrder =
101 TLI->getInsertFencesForAtomic() ? Monotonic : LI->getOrdering();
103 // The only 64-bit load guaranteed to be single-copy atomic by the ARM ARM is
104 // an ldrexd (A3.5.3).
105 IRBuilder<> Builder(LI);
107 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
109 insertTrailingFence(Builder, LI->getOrdering());
111 LI->replaceAllUsesWith(Val);
112 LI->eraseFromParent();
117 bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
118 // The only atomic 64-bit store on ARM is an strexd that succeeds, which means
119 // we need a loop and the entire instruction is essentially an "atomicrmw
120 // xchg" that ignores the value loaded.
121 IRBuilder<> Builder(SI);
123 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
124 SI->getValueOperand(), SI->getOrdering());
125 SI->eraseFromParent();
127 // Now we have an appropriate swap instruction, lower it as usual.
128 return expandAtomicRMW(AI);
131 bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
132 AtomicOrdering Order = AI->getOrdering();
133 Value *Addr = AI->getPointerOperand();
134 BasicBlock *BB = AI->getParent();
135 Function *F = BB->getParent();
136 LLVMContext &Ctx = F->getContext();
138 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
140 // The standard expansion we produce is:
144 // %loaded = @load.linked(%addr)
145 // %new = some_op iN %loaded, %incr
146 // %stored = @store_conditional(%new, %addr)
147 // %try_again = icmp i32 ne %stored, 0
148 // br i1 %try_again, label %loop, label %atomicrmw.end
152 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
153 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
155 // This grabs the DebugLoc from AI.
156 IRBuilder<> Builder(AI);
158 // The split call above "helpfully" added a branch at the end of BB (to the
159 // wrong place), but we might want a fence too. It's easiest to just remove
160 // the branch entirely.
161 std::prev(BB->end())->eraseFromParent();
162 Builder.SetInsertPoint(BB);
163 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, Order);
164 Builder.CreateBr(LoopBB);
166 // Start the main loop block now that we've taken care of the preliminaries.
167 Builder.SetInsertPoint(LoopBB);
168 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
171 switch (AI->getOperation()) {
172 case AtomicRMWInst::Xchg:
173 NewVal = AI->getValOperand();
175 case AtomicRMWInst::Add:
176 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
178 case AtomicRMWInst::Sub:
179 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
181 case AtomicRMWInst::And:
182 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
184 case AtomicRMWInst::Nand:
185 NewVal = Builder.CreateAnd(Loaded, Builder.CreateNot(AI->getValOperand()),
188 case AtomicRMWInst::Or:
189 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
191 case AtomicRMWInst::Xor:
192 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
194 case AtomicRMWInst::Max:
195 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
196 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
198 case AtomicRMWInst::Min:
199 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
200 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
202 case AtomicRMWInst::UMax:
203 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
204 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
206 case AtomicRMWInst::UMin:
207 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
208 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
211 llvm_unreachable("Unknown atomic op");
214 Value *StoreSuccess =
215 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
216 Value *TryAgain = Builder.CreateICmpNE(
217 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
218 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
220 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
221 insertTrailingFence(Builder, Order);
223 AI->replaceAllUsesWith(Loaded);
224 AI->eraseFromParent();
229 bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
230 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
231 AtomicOrdering FailureOrder = CI->getFailureOrdering();
232 Value *Addr = CI->getPointerOperand();
233 BasicBlock *BB = CI->getParent();
234 Function *F = BB->getParent();
235 LLVMContext &Ctx = F->getContext();
237 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
239 // The full expansion we produce is:
243 // %loaded = @load.linked(%addr)
244 // %should_store = icmp eq %loaded, %desired
245 // br i1 %should_store, label %cmpxchg.trystore,
246 // label %cmpxchg.end/%cmpxchg.barrier
248 // %stored = @store_conditional(%new, %addr)
249 // %try_again = icmp i32 ne %stored, 0
250 // br i1 %try_again, label %loop, label %cmpxchg.end
253 // br label %cmpxchg.end
256 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
257 auto BarrierBB = BasicBlock::Create(Ctx, "cmpxchg.barrier", F, ExitBB);
258 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, BarrierBB);
259 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
261 // This grabs the DebugLoc from CI
262 IRBuilder<> Builder(CI);
264 // The split call above "helpfully" added a branch at the end of BB (to the
265 // wrong place), but we might want a fence too. It's easiest to just remove
266 // the branch entirely.
267 std::prev(BB->end())->eraseFromParent();
268 Builder.SetInsertPoint(BB);
269 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
270 Builder.CreateBr(LoopBB);
272 // Start the main loop block now that we've taken care of the preliminaries.
273 Builder.SetInsertPoint(LoopBB);
274 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
276 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
278 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
279 // jump straight past that fence instruction (if it exists).
280 BasicBlock *FailureBB = FailureOrder == Monotonic ? ExitBB : BarrierBB;
281 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
283 Builder.SetInsertPoint(TryStoreBB);
284 Value *StoreSuccess = TLI->emitStoreConditional(
285 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
286 Value *TryAgain = Builder.CreateICmpNE(
287 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
288 Builder.CreateCondBr(TryAgain, LoopBB, BarrierBB);
290 // Make sure later instructions don't get reordered with a fence if necessary.
291 Builder.SetInsertPoint(BarrierBB);
292 insertTrailingFence(Builder, SuccessOrder);
293 Builder.CreateBr(ExitBB);
295 // Finally, we have control-flow based knowledge of whether the cmpxchg
296 // succeeded or not. We expose this to later passes by converting any
297 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
299 // Setup the builder so we can create any PHIs we need.
300 Builder.SetInsertPoint(FailureBB, FailureBB->begin());
301 BasicBlock *SuccessBB = FailureOrder == Monotonic ? BarrierBB : TryStoreBB;
302 PHINode *Success = nullptr, *Failure = nullptr;
304 // Look for any users of the cmpxchg that are just comparing the loaded value
305 // against the desired one, and replace them with the CFG-derived version.
306 for (auto User : CI->users()) {
307 ICmpInst *ICmp = dyn_cast<ICmpInst>(User);
311 // Because we know ICmp uses CI, we only need one operand to be the old
313 if (ICmp->getOperand(0) != CI->getCompareOperand() &&
314 ICmp->getOperand(1) != CI->getCompareOperand())
317 if (ICmp->getPredicate() == CmpInst::ICMP_EQ) {
319 Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
320 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
321 Success->addIncoming(ConstantInt::getFalse(Ctx), LoopBB);
323 ICmp->replaceAllUsesWith(Success);
324 } else if (ICmp->getPredicate() == CmpInst::ICMP_NE) {
326 Failure = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
327 Failure->addIncoming(ConstantInt::getFalse(Ctx), SuccessBB);
328 Failure->addIncoming(ConstantInt::getTrue(Ctx), LoopBB);
330 ICmp->replaceAllUsesWith(Failure);
334 CI->replaceAllUsesWith(Loaded);
335 CI->eraseFromParent();
340 AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
341 AtomicOrdering Ord) {
342 if (!TLI->getInsertFencesForAtomic())
345 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
346 Builder.CreateFence(Release);
348 // The exclusive operations don't need any barrier if we're adding separate
353 void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
354 AtomicOrdering Ord) {
355 if (!TLI->getInsertFencesForAtomic())
358 if (Ord == Acquire || Ord == AcquireRelease)
359 Builder.CreateFence(Acquire);
360 else if (Ord == SequentiallyConsistent)
361 Builder.CreateFence(SequentiallyConsistent);