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 // either (intrinsic-based) load-linked/store-conditional loops or
14 //===----------------------------------------------------------------------===//
16 #include "llvm/CodeGen/AtomicExpandUtils.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/InstIterator.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Intrinsics.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
31 #define DEBUG_TYPE "atomic-expand"
34 class AtomicExpand: public FunctionPass {
35 const TargetMachine *TM;
36 const TargetLowering *TLI;
38 static char ID; // Pass identification, replacement for typeid
39 explicit AtomicExpand(const TargetMachine *TM = nullptr)
40 : FunctionPass(ID), TM(TM), TLI(nullptr) {
41 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
44 bool runOnFunction(Function &F) override;
47 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
48 bool IsStore, bool IsLoad);
49 bool tryExpandAtomicLoad(LoadInst *LI);
50 bool expandAtomicLoadToLL(LoadInst *LI);
51 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
52 bool expandAtomicStore(StoreInst *SI);
53 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
54 bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
55 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
56 bool isIdempotentRMW(AtomicRMWInst *AI);
57 bool simplifyIdempotentRMW(AtomicRMWInst *AI);
61 char AtomicExpand::ID = 0;
62 char &llvm::AtomicExpandID = AtomicExpand::ID;
63 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
64 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
67 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
68 return new AtomicExpand(TM);
71 bool AtomicExpand::runOnFunction(Function &F) {
72 if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
74 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
76 SmallVector<Instruction *, 1> AtomicInsts;
78 // Changing control-flow while iterating through it is a bad idea, so gather a
79 // list of all atomic instructions before we start.
80 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
82 AtomicInsts.push_back(&*I);
85 bool MadeChange = false;
86 for (auto I : AtomicInsts) {
87 auto LI = dyn_cast<LoadInst>(I);
88 auto SI = dyn_cast<StoreInst>(I);
89 auto RMWI = dyn_cast<AtomicRMWInst>(I);
90 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
91 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
92 "Unknown atomic instruction");
94 auto FenceOrdering = Monotonic;
96 if (TLI->getInsertFencesForAtomic()) {
97 if (LI && isAtLeastAcquire(LI->getOrdering())) {
98 FenceOrdering = LI->getOrdering();
99 LI->setOrdering(Monotonic);
102 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
103 FenceOrdering = SI->getOrdering();
104 SI->setOrdering(Monotonic);
107 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
108 isAtLeastAcquire(RMWI->getOrdering()))) {
109 FenceOrdering = RMWI->getOrdering();
110 RMWI->setOrdering(Monotonic);
111 IsStore = IsLoad = true;
112 } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
113 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
114 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
115 // If a compare and swap is lowered to LL/SC, we can do smarter fence
116 // insertion, with a stronger one on the success path than on the
117 // failure path. As a result, fence insertion is directly done by
118 // expandAtomicCmpXchg in that case.
119 FenceOrdering = CASI->getSuccessOrdering();
120 CASI->setSuccessOrdering(Monotonic);
121 CASI->setFailureOrdering(Monotonic);
122 IsStore = IsLoad = true;
125 if (FenceOrdering != Monotonic) {
126 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
131 MadeChange |= tryExpandAtomicLoad(LI);
132 } else if (SI && TLI->shouldExpandAtomicStoreInIR(SI)) {
133 MadeChange |= expandAtomicStore(SI);
135 // There are two different ways of expanding RMW instructions:
136 // - into a load if it is idempotent
137 // - into a Cmpxchg/LL-SC loop otherwise
138 // we try them in that order.
140 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
143 MadeChange |= tryExpandAtomicRMW(RMWI);
145 } else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI)) {
146 MadeChange |= expandAtomicCmpXchg(CASI);
152 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
153 bool IsStore, bool IsLoad) {
154 IRBuilder<> Builder(I);
156 auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
158 auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
159 // The trailing fence is emitted before the instruction instead of after
160 // because there is no easy way of setting Builder insertion point after
161 // an instruction. So we must erase it from the BB, and insert it back
162 // in the right place.
163 // We have a guard here because not every atomic operation generates a
166 TrailingFence->removeFromParent();
167 TrailingFence->insertAfter(I);
170 return (LeadingFence || TrailingFence);
173 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
174 switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
175 case TargetLoweringBase::AtomicExpansionKind::None:
177 case TargetLoweringBase::AtomicExpansionKind::LLSC: {
178 return expandAtomicLoadToLL(LI);
180 case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
181 return expandAtomicLoadToCmpXchg(LI);
184 llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
187 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
188 IRBuilder<> Builder(LI);
190 // On some architectures, load-linked instructions are atomic for larger
191 // sizes than normal loads. For example, the only 64-bit load guaranteed
192 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
194 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
196 LI->replaceAllUsesWith(Val);
197 LI->eraseFromParent();
202 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
203 IRBuilder<> Builder(LI);
204 AtomicOrdering Order = LI->getOrdering();
205 Value *Addr = LI->getPointerOperand();
206 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
207 Constant *DummyVal = Constant::getNullValue(Ty);
209 Value *Pair = Builder.CreateAtomicCmpXchg(
210 Addr, DummyVal, DummyVal, Order,
211 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
212 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
214 LI->replaceAllUsesWith(Loaded);
215 LI->eraseFromParent();
220 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
221 // This function is only called on atomic stores that are too large to be
222 // atomic if implemented as a native store. So we replace them by an
223 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
224 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
225 // It is the responsibility of the target to only signal expansion via
226 // shouldExpandAtomicRMW in cases where this is required and possible.
227 IRBuilder<> Builder(SI);
229 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
230 SI->getValueOperand(), SI->getOrdering());
231 SI->eraseFromParent();
233 // Now we have an appropriate swap instruction, lower it as usual.
234 return tryExpandAtomicRMW(AI);
237 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
238 Value *Loaded, Value *NewVal,
239 AtomicOrdering MemOpOrder,
240 Value *&Success, Value *&NewLoaded) {
241 Value* Pair = Builder.CreateAtomicCmpXchg(
242 Addr, Loaded, NewVal, MemOpOrder,
243 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
244 Success = Builder.CreateExtractValue(Pair, 1, "success");
245 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
248 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
249 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
250 case TargetLoweringBase::AtomicExpansionKind::None:
252 case TargetLoweringBase::AtomicExpansionKind::LLSC: {
253 return expandAtomicRMWToLLSC(AI);
255 case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
256 return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
259 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
262 /// Emit IR to implement the given atomicrmw operation on values in registers,
263 /// returning the new value.
264 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
265 Value *Loaded, Value *Inc) {
268 case AtomicRMWInst::Xchg:
270 case AtomicRMWInst::Add:
271 return Builder.CreateAdd(Loaded, Inc, "new");
272 case AtomicRMWInst::Sub:
273 return Builder.CreateSub(Loaded, Inc, "new");
274 case AtomicRMWInst::And:
275 return Builder.CreateAnd(Loaded, Inc, "new");
276 case AtomicRMWInst::Nand:
277 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
278 case AtomicRMWInst::Or:
279 return Builder.CreateOr(Loaded, Inc, "new");
280 case AtomicRMWInst::Xor:
281 return Builder.CreateXor(Loaded, Inc, "new");
282 case AtomicRMWInst::Max:
283 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
284 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
285 case AtomicRMWInst::Min:
286 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
287 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
288 case AtomicRMWInst::UMax:
289 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
290 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
291 case AtomicRMWInst::UMin:
292 NewVal = Builder.CreateICmpULE(Loaded, Inc);
293 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
295 llvm_unreachable("Unknown atomic op");
299 bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
300 AtomicOrdering MemOpOrder = AI->getOrdering();
301 Value *Addr = AI->getPointerOperand();
302 BasicBlock *BB = AI->getParent();
303 Function *F = BB->getParent();
304 LLVMContext &Ctx = F->getContext();
306 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
308 // The standard expansion we produce is:
312 // %loaded = @load.linked(%addr)
313 // %new = some_op iN %loaded, %incr
314 // %stored = @store_conditional(%new, %addr)
315 // %try_again = icmp i32 ne %stored, 0
316 // br i1 %try_again, label %loop, label %atomicrmw.end
320 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
321 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
323 // This grabs the DebugLoc from AI.
324 IRBuilder<> Builder(AI);
326 // The split call above "helpfully" added a branch at the end of BB (to the
327 // wrong place), but we might want a fence too. It's easiest to just remove
328 // the branch entirely.
329 std::prev(BB->end())->eraseFromParent();
330 Builder.SetInsertPoint(BB);
331 Builder.CreateBr(LoopBB);
333 // Start the main loop block now that we've taken care of the preliminaries.
334 Builder.SetInsertPoint(LoopBB);
335 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
338 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
340 Value *StoreSuccess =
341 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
342 Value *TryAgain = Builder.CreateICmpNE(
343 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
344 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
346 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
348 AI->replaceAllUsesWith(Loaded);
349 AI->eraseFromParent();
354 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
355 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
356 AtomicOrdering FailureOrder = CI->getFailureOrdering();
357 Value *Addr = CI->getPointerOperand();
358 BasicBlock *BB = CI->getParent();
359 Function *F = BB->getParent();
360 LLVMContext &Ctx = F->getContext();
361 // If getInsertFencesForAtomic() returns true, then the target does not want
362 // to deal with memory orders, and emitLeading/TrailingFence should take care
363 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
364 // should preserve the ordering.
365 AtomicOrdering MemOpOrder =
366 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
368 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
370 // The full expansion we produce is:
374 // %loaded = @load.linked(%addr)
375 // %should_store = icmp eq %loaded, %desired
376 // br i1 %should_store, label %cmpxchg.trystore,
377 // label %cmpxchg.failure
379 // %stored = @store_conditional(%new, %addr)
380 // %success = icmp eq i32 %stored, 0
381 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
384 // br label %cmpxchg.end
387 // br label %cmpxchg.end
389 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
390 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
391 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
393 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
394 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
395 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
396 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
397 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
399 // This grabs the DebugLoc from CI
400 IRBuilder<> Builder(CI);
402 // The split call above "helpfully" added a branch at the end of BB (to the
403 // wrong place), but we might want a fence too. It's easiest to just remove
404 // the branch entirely.
405 std::prev(BB->end())->eraseFromParent();
406 Builder.SetInsertPoint(BB);
407 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
409 Builder.CreateBr(LoopBB);
411 // Start the main loop block now that we've taken care of the preliminaries.
412 Builder.SetInsertPoint(LoopBB);
413 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
415 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
417 // If the cmpxchg doesn't actually need any ordering when it fails, we can
418 // jump straight past that fence instruction (if it exists).
419 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
421 Builder.SetInsertPoint(TryStoreBB);
422 Value *StoreSuccess = TLI->emitStoreConditional(
423 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
424 StoreSuccess = Builder.CreateICmpEQ(
425 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
426 Builder.CreateCondBr(StoreSuccess, SuccessBB,
427 CI->isWeak() ? FailureBB : LoopBB);
429 // Make sure later instructions don't get reordered with a fence if necessary.
430 Builder.SetInsertPoint(SuccessBB);
431 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
433 Builder.CreateBr(ExitBB);
435 Builder.SetInsertPoint(FailureBB);
436 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
438 Builder.CreateBr(ExitBB);
440 // Finally, we have control-flow based knowledge of whether the cmpxchg
441 // succeeded or not. We expose this to later passes by converting any
442 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
444 // Setup the builder so we can create any PHIs we need.
445 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
446 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
447 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
448 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
450 // Look for any users of the cmpxchg that are just comparing the loaded value
451 // against the desired one, and replace them with the CFG-derived version.
452 SmallVector<ExtractValueInst *, 2> PrunedInsts;
453 for (auto User : CI->users()) {
454 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
458 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
459 "weird extraction from { iN, i1 }");
461 if (EV->getIndices()[0] == 0)
462 EV->replaceAllUsesWith(Loaded);
464 EV->replaceAllUsesWith(Success);
466 PrunedInsts.push_back(EV);
469 // We can remove the instructions now we're no longer iterating through them.
470 for (auto EV : PrunedInsts)
471 EV->eraseFromParent();
473 if (!CI->use_empty()) {
474 // Some use of the full struct return that we don't understand has happened,
475 // so we've got to reconstruct it properly.
477 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
478 Res = Builder.CreateInsertValue(Res, Success, 1);
480 CI->replaceAllUsesWith(Res);
483 CI->eraseFromParent();
487 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
488 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
492 AtomicRMWInst::BinOp Op = RMWI->getOperation();
494 case AtomicRMWInst::Add:
495 case AtomicRMWInst::Sub:
496 case AtomicRMWInst::Or:
497 case AtomicRMWInst::Xor:
499 case AtomicRMWInst::And:
500 return C->isMinusOne();
501 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
507 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
508 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI))
509 return tryExpandAtomicLoad(ResultingLoad);
513 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
514 CreateCmpXchgInstFun CreateCmpXchg) {
517 AtomicOrdering MemOpOrder =
518 AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
519 Value *Addr = AI->getPointerOperand();
520 BasicBlock *BB = AI->getParent();
521 Function *F = BB->getParent();
522 LLVMContext &Ctx = F->getContext();
524 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
526 // The standard expansion we produce is:
528 // %init_loaded = load atomic iN* %addr
531 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
532 // %new = some_op iN %loaded, %incr
533 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
534 // %new_loaded = extractvalue { iN, i1 } %pair, 0
535 // %success = extractvalue { iN, i1 } %pair, 1
536 // br i1 %success, label %atomicrmw.end, label %loop
539 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
540 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
542 // This grabs the DebugLoc from AI.
543 IRBuilder<> Builder(AI);
545 // The split call above "helpfully" added a branch at the end of BB (to the
546 // wrong place), but we want a load. It's easiest to just remove
547 // the branch entirely.
548 std::prev(BB->end())->eraseFromParent();
549 Builder.SetInsertPoint(BB);
550 LoadInst *InitLoaded = Builder.CreateLoad(Addr);
551 // Atomics require at least natural alignment.
552 InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits() / 8);
553 Builder.CreateBr(LoopBB);
555 // Start the main loop block now that we've taken care of the preliminaries.
556 Builder.SetInsertPoint(LoopBB);
557 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
558 Loaded->addIncoming(InitLoaded, BB);
561 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
563 Value *NewLoaded = nullptr;
564 Value *Success = nullptr;
566 CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
568 assert(Success && NewLoaded);
570 Loaded->addIncoming(NewLoaded, LoopBB);
572 Builder.CreateCondBr(Success, ExitBB, LoopBB);
574 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
576 AI->replaceAllUsesWith(NewLoaded);
577 AI->eraseFromParent();