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;
54 static void *initializeAtomicExpandLoadLinkedPassOnce(PassRegistry &Registry) {
55 PassInfo *PI = new PassInfo(
56 "Expand Atomic calls in terms of load-linked & store-conditional",
57 "atomic-ll-sc", &AtomicExpandLoadLinked::ID,
58 PassInfo::NormalCtor_t(callDefaultCtor<AtomicExpandLoadLinked>), false,
59 false, PassInfo::TargetMachineCtor_t(
60 callTargetMachineCtor<AtomicExpandLoadLinked>));
61 Registry.registerPass(*PI, true);
65 void llvm::initializeAtomicExpandLoadLinkedPass(PassRegistry &Registry) {
66 CALL_ONCE_INITIALIZATION(initializeAtomicExpandLoadLinkedPassOnce)
70 FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
71 return new AtomicExpandLoadLinked(TM);
74 bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
78 SmallVector<Instruction *, 1> AtomicInsts;
80 // Changing control-flow while iterating through it is a bad idea, so gather a
81 // list of all atomic instructions before we start.
82 for (BasicBlock &BB : F)
83 for (Instruction &Inst : BB) {
84 if (isa<AtomicRMWInst>(&Inst) || isa<AtomicCmpXchgInst>(&Inst) ||
85 (isa<LoadInst>(&Inst) && cast<LoadInst>(&Inst)->isAtomic()) ||
86 (isa<StoreInst>(&Inst) && cast<StoreInst>(&Inst)->isAtomic()))
87 AtomicInsts.push_back(&Inst);
90 bool MadeChange = false;
91 for (Instruction *Inst : AtomicInsts) {
92 if (!TLI->shouldExpandAtomicInIR(Inst))
95 if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst))
96 MadeChange |= expandAtomicRMW(AI);
97 else if (AtomicCmpXchgInst *CI = dyn_cast<AtomicCmpXchgInst>(Inst))
98 MadeChange |= expandAtomicCmpXchg(CI);
99 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
100 MadeChange |= expandAtomicLoad(LI);
101 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
102 MadeChange |= expandAtomicStore(SI);
104 llvm_unreachable("Unknown atomic instruction");
110 bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
111 // Load instructions don't actually need a leading fence, even in the
112 // SequentiallyConsistent case.
113 AtomicOrdering MemOpOrder =
114 TLI->getInsertFencesForAtomic() ? Monotonic : LI->getOrdering();
116 // The only 64-bit load guaranteed to be single-copy atomic by the ARM ARM is
117 // an ldrexd (A3.5.3).
118 IRBuilder<> Builder(LI);
120 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
122 insertTrailingFence(Builder, LI->getOrdering());
124 LI->replaceAllUsesWith(Val);
125 LI->eraseFromParent();
130 bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
131 // The only atomic 64-bit store on ARM is an strexd that succeeds, which means
132 // we need a loop and the entire instruction is essentially an "atomicrmw
133 // xchg" that ignores the value loaded.
134 IRBuilder<> Builder(SI);
136 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
137 SI->getValueOperand(), SI->getOrdering());
138 SI->eraseFromParent();
140 // Now we have an appropriate swap instruction, lower it as usual.
141 return expandAtomicRMW(AI);
144 bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
145 AtomicOrdering Order = AI->getOrdering();
146 Value *Addr = AI->getPointerOperand();
147 BasicBlock *BB = AI->getParent();
148 Function *F = BB->getParent();
149 LLVMContext &Ctx = F->getContext();
151 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
153 // The standard expansion we produce is:
157 // %loaded = @load.linked(%addr)
158 // %new = some_op iN %loaded, %incr
159 // %stored = @store_conditional(%new, %addr)
160 // %try_again = icmp i32 ne %stored, 0
161 // br i1 %try_again, label %loop, label %atomicrmw.end
165 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
166 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
168 // This grabs the DebugLoc from AI.
169 IRBuilder<> Builder(AI);
171 // The split call above "helpfully" added a branch at the end of BB (to the
172 // wrong place), but we might want a fence too. It's easiest to just remove
173 // the branch entirely.
174 std::prev(BB->end())->eraseFromParent();
175 Builder.SetInsertPoint(BB);
176 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, Order);
177 Builder.CreateBr(LoopBB);
179 // Start the main loop block now that we've taken care of the preliminaries.
180 Builder.SetInsertPoint(LoopBB);
181 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
184 switch (AI->getOperation()) {
185 case AtomicRMWInst::Xchg:
186 NewVal = AI->getValOperand();
188 case AtomicRMWInst::Add:
189 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
191 case AtomicRMWInst::Sub:
192 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
194 case AtomicRMWInst::And:
195 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
197 case AtomicRMWInst::Nand:
198 NewVal = Builder.CreateAnd(Loaded, Builder.CreateNot(AI->getValOperand()),
201 case AtomicRMWInst::Or:
202 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
204 case AtomicRMWInst::Xor:
205 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
207 case AtomicRMWInst::Max:
208 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
209 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
211 case AtomicRMWInst::Min:
212 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
213 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
215 case AtomicRMWInst::UMax:
216 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
217 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
219 case AtomicRMWInst::UMin:
220 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
221 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
224 llvm_unreachable("Unknown atomic op");
227 Value *StoreSuccess =
228 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
229 Value *TryAgain = Builder.CreateICmpNE(
230 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
231 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
233 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
234 insertTrailingFence(Builder, Order);
236 AI->replaceAllUsesWith(Loaded);
237 AI->eraseFromParent();
242 bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
243 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
244 AtomicOrdering FailureOrder = CI->getFailureOrdering();
245 Value *Addr = CI->getPointerOperand();
246 BasicBlock *BB = CI->getParent();
247 Function *F = BB->getParent();
248 LLVMContext &Ctx = F->getContext();
250 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
252 // The full expansion we produce is:
256 // %loaded = @load.linked(%addr)
257 // %should_store = icmp eq %loaded, %desired
258 // br i1 %should_store, label %cmpxchg.trystore,
259 // label %cmpxchg.end/%cmpxchg.barrier
261 // %stored = @store_conditional(%new, %addr)
262 // %try_again = icmp i32 ne %stored, 0
263 // br i1 %try_again, label %loop, label %cmpxchg.end
266 // br label %cmpxchg.end
269 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
270 auto BarrierBB = BasicBlock::Create(Ctx, "cmpxchg.barrier", F, ExitBB);
271 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, BarrierBB);
272 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
274 // This grabs the DebugLoc from CI
275 IRBuilder<> Builder(CI);
277 // The split call above "helpfully" added a branch at the end of BB (to the
278 // wrong place), but we might want a fence too. It's easiest to just remove
279 // the branch entirely.
280 std::prev(BB->end())->eraseFromParent();
281 Builder.SetInsertPoint(BB);
282 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
283 Builder.CreateBr(LoopBB);
285 // Start the main loop block now that we've taken care of the preliminaries.
286 Builder.SetInsertPoint(LoopBB);
287 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
289 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
291 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
292 // jump straight past that fence instruction (if it exists).
293 BasicBlock *FailureBB = FailureOrder == Monotonic ? ExitBB : BarrierBB;
294 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
296 Builder.SetInsertPoint(TryStoreBB);
297 Value *StoreSuccess = TLI->emitStoreConditional(
298 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
299 Value *TryAgain = Builder.CreateICmpNE(
300 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
301 Builder.CreateCondBr(TryAgain, LoopBB, BarrierBB);
303 // Make sure later instructions don't get reordered with a fence if necessary.
304 Builder.SetInsertPoint(BarrierBB);
305 insertTrailingFence(Builder, SuccessOrder);
306 Builder.CreateBr(ExitBB);
308 // Finally, we have control-flow based knowledge of whether the cmpxchg
309 // succeeded or not. We expose this to later passes by converting any
310 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
312 // Setup the builder so we can create any PHIs we need.
313 Builder.SetInsertPoint(FailureBB, FailureBB->begin());
314 BasicBlock *SuccessBB = FailureOrder == Monotonic ? BarrierBB : TryStoreBB;
315 PHINode *Success = 0, *Failure = 0;
317 // Look for any users of the cmpxchg that are just comparing the loaded value
318 // against the desired one, and replace them with the CFG-derived version.
319 for (auto User : CI->users()) {
320 ICmpInst *ICmp = dyn_cast<ICmpInst>(User);
324 // Because we know ICmp uses CI, we only need one operand to be the old
326 if (ICmp->getOperand(0) != CI->getCompareOperand() &&
327 ICmp->getOperand(1) != CI->getCompareOperand())
330 if (ICmp->getPredicate() == CmpInst::ICMP_EQ) {
332 Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
333 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
334 Success->addIncoming(ConstantInt::getFalse(Ctx), LoopBB);
336 ICmp->replaceAllUsesWith(Success);
337 } else if (ICmp->getPredicate() == CmpInst::ICMP_NE) {
339 Failure = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
340 Failure->addIncoming(ConstantInt::getFalse(Ctx), SuccessBB);
341 Failure->addIncoming(ConstantInt::getTrue(Ctx), LoopBB);
343 ICmp->replaceAllUsesWith(Failure);
347 CI->replaceAllUsesWith(Loaded);
348 CI->eraseFromParent();
353 AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
354 AtomicOrdering Ord) {
355 if (!TLI->getInsertFencesForAtomic())
358 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
359 Builder.CreateFence(Release);
361 // The exclusive operations don't need any barrier if we're adding separate
366 void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
367 AtomicOrdering Ord) {
368 if (!TLI->getInsertFencesForAtomic())
371 if (Ord == Acquire || Ord == AcquireRelease)
372 Builder.CreateFence(Acquire);
373 else if (Ord == SequentiallyConsistent)
374 Builder.CreateFence(SequentiallyConsistent);