1 //===-- AtomicExpandPass.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/InstIterator.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetSubtargetInfo.h"
29 #define DEBUG_TYPE "atomic-expand"
32 class AtomicExpand: public FunctionPass {
33 const TargetMachine *TM;
35 static char ID; // Pass identification, replacement for typeid
36 explicit AtomicExpand(const TargetMachine *TM = nullptr)
37 : FunctionPass(ID), TM(TM) {
38 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
41 bool runOnFunction(Function &F) override;
44 bool expandAtomicLoad(LoadInst *LI);
45 bool expandAtomicStore(StoreInst *SI);
46 bool expandAtomicRMW(AtomicRMWInst *AI);
47 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
51 char AtomicExpand::ID = 0;
52 char &llvm::AtomicExpandID = AtomicExpand::ID;
53 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
54 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
57 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
58 return new AtomicExpand(TM);
61 bool AtomicExpand::runOnFunction(Function &F) {
62 if (!TM || !TM->getSubtargetImpl()->enableAtomicExpand())
64 auto TargetLowering = TM->getSubtargetImpl()->getTargetLowering();
66 SmallVector<Instruction *, 1> AtomicInsts;
68 // Changing control-flow while iterating through it is a bad idea, so gather a
69 // list of all atomic instructions before we start.
70 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
72 AtomicInsts.push_back(&*I);
75 bool MadeChange = false;
76 for (auto I : AtomicInsts) {
77 auto LI = dyn_cast<LoadInst>(I);
78 auto SI = dyn_cast<StoreInst>(I);
79 auto RMWI = dyn_cast<AtomicRMWInst>(I);
80 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
82 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
83 "Unknown atomic instruction");
85 if (LI && TargetLowering->shouldExpandAtomicLoadInIR(LI)) {
86 MadeChange |= expandAtomicLoad(LI);
87 } else if (SI && TargetLowering->shouldExpandAtomicStoreInIR(SI)) {
88 MadeChange |= expandAtomicStore(SI);
89 } else if (RMWI && TargetLowering->shouldExpandAtomicRMWInIR(RMWI)) {
90 MadeChange |= expandAtomicRMW(RMWI);
92 MadeChange |= expandAtomicCmpXchg(CASI);
98 bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
99 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
100 // If getInsertFencesForAtomic() returns true, then the target does not want
101 // to deal with memory orders, and emitLeading/TrailingFence should take care
102 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
103 // should preserve the ordering.
104 AtomicOrdering MemOpOrder =
105 TLI->getInsertFencesForAtomic() ? Monotonic : LI->getOrdering();
106 IRBuilder<> Builder(LI);
108 // Note that although no fence is required before atomic load on ARM, it is
109 // required before SequentiallyConsistent loads for the recommended Power
110 // mapping (see http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html).
111 // So we let the target choose what to emit.
112 TLI->emitLeadingFence(Builder, LI->getOrdering(),
113 /*IsStore=*/false, /*IsLoad=*/true);
115 // The only 64-bit load guaranteed to be single-copy atomic by ARM is
116 // an ldrexd (A3.5.3).
118 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
120 TLI->emitTrailingFence(Builder, LI->getOrdering(),
121 /*IsStore=*/false, /*IsLoad=*/true);
123 LI->replaceAllUsesWith(Val);
124 LI->eraseFromParent();
129 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
130 // The only atomic 64-bit store on ARM is an strexd that succeeds, which means
131 // we need a loop and the entire instruction is essentially an "atomicrmw
132 // xchg" that ignores the value loaded.
133 IRBuilder<> Builder(SI);
135 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
136 SI->getValueOperand(), SI->getOrdering());
137 SI->eraseFromParent();
139 // Now we have an appropriate swap instruction, lower it as usual.
140 return expandAtomicRMW(AI);
143 bool AtomicExpand::expandAtomicRMW(AtomicRMWInst *AI) {
144 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
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();
150 // If getInsertFencesForAtomic() returns true, then the target does not want
151 // to deal with memory orders, and emitLeading/TrailingFence should take care
152 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
153 // should preserve the ordering.
154 AtomicOrdering MemOpOrder =
155 TLI->getInsertFencesForAtomic() ? Monotonic : Order;
157 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
159 // The standard expansion we produce is:
163 // %loaded = @load.linked(%addr)
164 // %new = some_op iN %loaded, %incr
165 // %stored = @store_conditional(%new, %addr)
166 // %try_again = icmp i32 ne %stored, 0
167 // br i1 %try_again, label %loop, label %atomicrmw.end
171 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
172 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
174 // This grabs the DebugLoc from AI.
175 IRBuilder<> Builder(AI);
177 // The split call above "helpfully" added a branch at the end of BB (to the
178 // wrong place), but we might want a fence too. It's easiest to just remove
179 // the branch entirely.
180 std::prev(BB->end())->eraseFromParent();
181 Builder.SetInsertPoint(BB);
182 TLI->emitLeadingFence(Builder, Order, /*IsStore=*/true, /*IsLoad=*/true);
183 Builder.CreateBr(LoopBB);
185 // Start the main loop block now that we've taken care of the preliminaries.
186 Builder.SetInsertPoint(LoopBB);
187 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
190 switch (AI->getOperation()) {
191 case AtomicRMWInst::Xchg:
192 NewVal = AI->getValOperand();
194 case AtomicRMWInst::Add:
195 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
197 case AtomicRMWInst::Sub:
198 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
200 case AtomicRMWInst::And:
201 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
203 case AtomicRMWInst::Nand:
204 NewVal = Builder.CreateNot(Builder.CreateAnd(Loaded, AI->getValOperand()),
207 case AtomicRMWInst::Or:
208 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
210 case AtomicRMWInst::Xor:
211 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
213 case AtomicRMWInst::Max:
214 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
215 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
217 case AtomicRMWInst::Min:
218 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
219 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
221 case AtomicRMWInst::UMax:
222 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
223 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
225 case AtomicRMWInst::UMin:
226 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
227 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
230 llvm_unreachable("Unknown atomic op");
233 Value *StoreSuccess =
234 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
235 Value *TryAgain = Builder.CreateICmpNE(
236 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
237 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
239 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
240 TLI->emitTrailingFence(Builder, Order, /*IsStore=*/true, /*IsLoad=*/true);
242 AI->replaceAllUsesWith(Loaded);
243 AI->eraseFromParent();
248 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
249 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
250 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
251 AtomicOrdering FailureOrder = CI->getFailureOrdering();
252 Value *Addr = CI->getPointerOperand();
253 BasicBlock *BB = CI->getParent();
254 Function *F = BB->getParent();
255 LLVMContext &Ctx = F->getContext();
256 // If getInsertFencesForAtomic() returns true, then the target does not want
257 // to deal with memory orders, and emitLeading/TrailingFence should take care
258 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
259 // should preserve the ordering.
260 AtomicOrdering MemOpOrder =
261 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
263 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
265 // The full expansion we produce is:
269 // %loaded = @load.linked(%addr)
270 // %should_store = icmp eq %loaded, %desired
271 // br i1 %should_store, label %cmpxchg.trystore,
272 // label %cmpxchg.failure
274 // %stored = @store_conditional(%new, %addr)
275 // %success = icmp eq i32 %stored, 0
276 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
279 // br label %cmpxchg.end
282 // br label %cmpxchg.end
284 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
285 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
286 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
288 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
289 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
290 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
291 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
292 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
294 // This grabs the DebugLoc from CI
295 IRBuilder<> Builder(CI);
297 // The split call above "helpfully" added a branch at the end of BB (to the
298 // wrong place), but we might want a fence too. It's easiest to just remove
299 // the branch entirely.
300 std::prev(BB->end())->eraseFromParent();
301 Builder.SetInsertPoint(BB);
302 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
304 Builder.CreateBr(LoopBB);
306 // Start the main loop block now that we've taken care of the preliminaries.
307 Builder.SetInsertPoint(LoopBB);
308 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
310 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
312 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
313 // jump straight past that fence instruction (if it exists).
314 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
316 Builder.SetInsertPoint(TryStoreBB);
317 Value *StoreSuccess = TLI->emitStoreConditional(
318 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
319 StoreSuccess = Builder.CreateICmpEQ(
320 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
321 Builder.CreateCondBr(StoreSuccess, SuccessBB,
322 CI->isWeak() ? FailureBB : LoopBB);
324 // Make sure later instructions don't get reordered with a fence if necessary.
325 Builder.SetInsertPoint(SuccessBB);
326 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
328 Builder.CreateBr(ExitBB);
330 Builder.SetInsertPoint(FailureBB);
331 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
333 Builder.CreateBr(ExitBB);
335 // Finally, we have control-flow based knowledge of whether the cmpxchg
336 // succeeded or not. We expose this to later passes by converting any
337 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
339 // Setup the builder so we can create any PHIs we need.
340 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
341 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
342 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
343 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
345 // Look for any users of the cmpxchg that are just comparing the loaded value
346 // against the desired one, and replace them with the CFG-derived version.
347 SmallVector<ExtractValueInst *, 2> PrunedInsts;
348 for (auto User : CI->users()) {
349 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
353 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
354 "weird extraction from { iN, i1 }");
356 if (EV->getIndices()[0] == 0)
357 EV->replaceAllUsesWith(Loaded);
359 EV->replaceAllUsesWith(Success);
361 PrunedInsts.push_back(EV);
364 // We can remove the instructions now we're no longer iterating through them.
365 for (auto EV : PrunedInsts)
366 EV->eraseFromParent();
368 if (!CI->use_empty()) {
369 // Some use of the full struct return that we don't understand has happened,
370 // so we've got to reconstruct it properly.
372 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
373 Res = Builder.CreateInsertValue(Res, Success, 1);
375 CI->replaceAllUsesWith(Res);
378 CI->eraseFromParent();