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.failure
248 // %stored = @store_conditional(%new, %addr)
249 // %success = icmp eq i32 %stored, 0
250 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
253 // br label %cmpxchg.end
256 // br label %cmpxchg.end
258 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
259 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
260 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
262 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
263 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
264 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
265 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
266 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
268 // This grabs the DebugLoc from CI
269 IRBuilder<> Builder(CI);
271 // The split call above "helpfully" added a branch at the end of BB (to the
272 // wrong place), but we might want a fence too. It's easiest to just remove
273 // the branch entirely.
274 std::prev(BB->end())->eraseFromParent();
275 Builder.SetInsertPoint(BB);
276 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
277 Builder.CreateBr(LoopBB);
279 // Start the main loop block now that we've taken care of the preliminaries.
280 Builder.SetInsertPoint(LoopBB);
281 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
283 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
285 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
286 // jump straight past that fence instruction (if it exists).
287 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
289 Builder.SetInsertPoint(TryStoreBB);
290 Value *StoreSuccess = TLI->emitStoreConditional(
291 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
292 StoreSuccess = Builder.CreateICmpEQ(
293 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
294 Builder.CreateCondBr(StoreSuccess, SuccessBB,
295 CI->isWeak() ? FailureBB : LoopBB);
297 // Make sure later instructions don't get reordered with a fence if necessary.
298 Builder.SetInsertPoint(SuccessBB);
299 insertTrailingFence(Builder, SuccessOrder);
300 Builder.CreateBr(ExitBB);
302 Builder.SetInsertPoint(FailureBB);
303 insertTrailingFence(Builder, FailureOrder);
304 Builder.CreateBr(ExitBB);
306 // Finally, we have control-flow based knowledge of whether the cmpxchg
307 // succeeded or not. We expose this to later passes by converting any
308 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
310 // Setup the builder so we can create any PHIs we need.
311 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
312 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
313 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
314 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
316 // Look for any users of the cmpxchg that are just comparing the loaded value
317 // against the desired one, and replace them with the CFG-derived version.
318 SmallVector<ExtractValueInst *, 2> PrunedInsts;
319 for (auto User : CI->users()) {
320 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
324 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
325 "weird extraction from { iN, i1 }");
327 if (EV->getIndices()[0] == 0)
328 EV->replaceAllUsesWith(Loaded);
330 EV->replaceAllUsesWith(Success);
332 PrunedInsts.push_back(EV);
335 // We can remove the instructions now we're no longer iterating through them.
336 for (auto EV : PrunedInsts)
337 EV->eraseFromParent();
339 if (!CI->use_empty()) {
340 // Some use of the full struct return that we don't understand has happened,
341 // so we've got to reconstruct it properly.
343 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
344 Res = Builder.CreateInsertValue(Res, Success, 1);
346 CI->replaceAllUsesWith(Res);
349 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);