blob: 7e65a20deee288ad42ace2a73b90854d1e612fe7 [file] [log] [blame]
Robin Morisset59c23cd2014-08-21 21:50:01 +00001//===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
Tim Northoverc882eb02014-04-03 11:44:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass (at IR level) to replace atomic instructions with
Robin Morissetdedef332014-09-23 20:31:14 +000011// either (intrinsic-based) load-linked/store-conditional loops or AtomicCmpXchg.
Tim Northoverc882eb02014-04-03 11:44:58 +000012//
13//===----------------------------------------------------------------------===//
14
JF Bastiene8aad292015-08-03 15:29:47 +000015#include "llvm/CodeGen/AtomicExpandUtils.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/IR/Function.h"
18#include "llvm/IR/IRBuilder.h"
Robin Morisseted3d48f2014-09-03 21:29:59 +000019#include "llvm/IR/InstIterator.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000020#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Module.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Target/TargetLowering.h"
25#include "llvm/Target/TargetMachine.h"
Eric Christopherc40e5ed2014-06-19 21:03:04 +000026#include "llvm/Target/TargetSubtargetInfo.h"
27
Tim Northoverc882eb02014-04-03 11:44:58 +000028using namespace llvm;
29
Robin Morisset59c23cd2014-08-21 21:50:01 +000030#define DEBUG_TYPE "atomic-expand"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000031
Tim Northoverc882eb02014-04-03 11:44:58 +000032namespace {
Robin Morisset59c23cd2014-08-21 21:50:01 +000033 class AtomicExpand: public FunctionPass {
Eric Christopherc40e5ed2014-06-19 21:03:04 +000034 const TargetMachine *TM;
Eric Christopherb11a1b72015-01-26 19:45:40 +000035 const TargetLowering *TLI;
Tim Northoverc882eb02014-04-03 11:44:58 +000036 public:
37 static char ID; // Pass identification, replacement for typeid
Robin Morisset59c23cd2014-08-21 21:50:01 +000038 explicit AtomicExpand(const TargetMachine *TM = nullptr)
Eric Christopherb11a1b72015-01-26 19:45:40 +000039 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Robin Morisset59c23cd2014-08-21 21:50:01 +000040 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
Tim Northover037f26f22014-04-17 18:22:47 +000041 }
Tim Northoverc882eb02014-04-03 11:44:58 +000042
43 bool runOnFunction(Function &F) override;
Tim Northoverc882eb02014-04-03 11:44:58 +000044
Robin Morisseted3d48f2014-09-03 21:29:59 +000045 private:
Robin Morissetdedef332014-09-23 20:31:14 +000046 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
47 bool IsStore, bool IsLoad);
Tim Northoverc882eb02014-04-03 11:44:58 +000048 bool expandAtomicLoad(LoadInst *LI);
Robin Morisset6dbbbc22014-09-23 20:59:25 +000049 bool expandAtomicLoadToLL(LoadInst *LI);
50 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
Robin Morisseted3d48f2014-09-03 21:29:59 +000051 bool expandAtomicStore(StoreInst *SI);
JF Bastienf14889e2015-03-04 15:47:57 +000052 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
Robin Morisset25c8e312014-09-17 00:06:58 +000053 bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
Tim Northoverc882eb02014-04-03 11:44:58 +000054 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
Robin Morisset810739d2014-09-25 17:27:43 +000055 bool isIdempotentRMW(AtomicRMWInst *AI);
56 bool simplifyIdempotentRMW(AtomicRMWInst *AI);
Tim Northoverc882eb02014-04-03 11:44:58 +000057 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000058}
Tim Northoverc882eb02014-04-03 11:44:58 +000059
Robin Morisset59c23cd2014-08-21 21:50:01 +000060char AtomicExpand::ID = 0;
61char &llvm::AtomicExpandID = AtomicExpand::ID;
62INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
63 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
Jiangning Liud623c522014-06-11 07:04:37 +000064 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +000065
Robin Morisset59c23cd2014-08-21 21:50:01 +000066FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
67 return new AtomicExpand(TM);
Tim Northover037f26f22014-04-17 18:22:47 +000068}
69
Robin Morisset59c23cd2014-08-21 21:50:01 +000070bool AtomicExpand::runOnFunction(Function &F) {
Eric Christopher4e048eeb2015-01-27 01:04:42 +000071 if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
Tim Northover037f26f22014-04-17 18:22:47 +000072 return false;
Eric Christopher4e048eeb2015-01-27 01:04:42 +000073 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Tim Northover037f26f22014-04-17 18:22:47 +000074
Tim Northoverc882eb02014-04-03 11:44:58 +000075 SmallVector<Instruction *, 1> AtomicInsts;
76
77 // Changing control-flow while iterating through it is a bad idea, so gather a
78 // list of all atomic instructions before we start.
Robin Morisseted3d48f2014-09-03 21:29:59 +000079 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
80 if (I->isAtomic())
81 AtomicInsts.push_back(&*I);
Tim Northoverc882eb02014-04-03 11:44:58 +000082 }
83
Robin Morisseted3d48f2014-09-03 21:29:59 +000084 bool MadeChange = false;
85 for (auto I : AtomicInsts) {
86 auto LI = dyn_cast<LoadInst>(I);
87 auto SI = dyn_cast<StoreInst>(I);
88 auto RMWI = dyn_cast<AtomicRMWInst>(I);
89 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
Robin Morisseted3d48f2014-09-03 21:29:59 +000090 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
91 "Unknown atomic instruction");
92
Robin Morissetdedef332014-09-23 20:31:14 +000093 auto FenceOrdering = Monotonic;
94 bool IsStore, IsLoad;
Eric Christopherb11a1b72015-01-26 19:45:40 +000095 if (TLI->getInsertFencesForAtomic()) {
Robin Morissetdedef332014-09-23 20:31:14 +000096 if (LI && isAtLeastAcquire(LI->getOrdering())) {
97 FenceOrdering = LI->getOrdering();
98 LI->setOrdering(Monotonic);
99 IsStore = false;
100 IsLoad = true;
101 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
102 FenceOrdering = SI->getOrdering();
103 SI->setOrdering(Monotonic);
104 IsStore = true;
105 IsLoad = false;
106 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
107 isAtLeastAcquire(RMWI->getOrdering()))) {
108 FenceOrdering = RMWI->getOrdering();
109 RMWI->setOrdering(Monotonic);
110 IsStore = IsLoad = true;
Eric Christopherb11a1b72015-01-26 19:45:40 +0000111 } else if (CASI && !TLI->hasLoadLinkedStoreConditional() &&
112 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
113 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
Robin Morissetdedef332014-09-23 20:31:14 +0000114 // If a compare and swap is lowered to LL/SC, we can do smarter fence
115 // insertion, with a stronger one on the success path than on the
116 // failure path. As a result, fence insertion is directly done by
117 // expandAtomicCmpXchg in that case.
118 FenceOrdering = CASI->getSuccessOrdering();
119 CASI->setSuccessOrdering(Monotonic);
120 CASI->setFailureOrdering(Monotonic);
121 IsStore = IsLoad = true;
122 }
123
124 if (FenceOrdering != Monotonic) {
125 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
126 }
127 }
128
Eric Christopherb11a1b72015-01-26 19:45:40 +0000129 if (LI && TLI->shouldExpandAtomicLoadInIR(LI)) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000130 MadeChange |= expandAtomicLoad(LI);
Eric Christopherb11a1b72015-01-26 19:45:40 +0000131 } else if (SI && TLI->shouldExpandAtomicStoreInIR(SI)) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000132 MadeChange |= expandAtomicStore(SI);
Robin Morisset810739d2014-09-25 17:27:43 +0000133 } else if (RMWI) {
134 // There are two different ways of expanding RMW instructions:
135 // - into a load if it is idempotent
136 // - into a Cmpxchg/LL-SC loop otherwise
137 // we try them in that order.
JF Bastienf14889e2015-03-04 15:47:57 +0000138
139 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
140 MadeChange = true;
141 } else {
142 MadeChange |= tryExpandAtomicRMW(RMWI);
143 }
Eric Christopherb11a1b72015-01-26 19:45:40 +0000144 } else if (CASI && TLI->hasLoadLinkedStoreConditional()) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000145 MadeChange |= expandAtomicCmpXchg(CASI);
146 }
147 }
Tim Northoverc882eb02014-04-03 11:44:58 +0000148 return MadeChange;
149}
150
Robin Morissetdedef332014-09-23 20:31:14 +0000151bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
152 bool IsStore, bool IsLoad) {
153 IRBuilder<> Builder(I);
154
Eric Christopherb11a1b72015-01-26 19:45:40 +0000155 auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000156
Eric Christopherb11a1b72015-01-26 19:45:40 +0000157 auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000158 // The trailing fence is emitted before the instruction instead of after
159 // because there is no easy way of setting Builder insertion point after
160 // an instruction. So we must erase it from the BB, and insert it back
161 // in the right place.
162 // We have a guard here because not every atomic operation generates a
163 // trailing fence.
164 if (TrailingFence) {
165 TrailingFence->removeFromParent();
166 TrailingFence->insertAfter(I);
167 }
168
169 return (LeadingFence || TrailingFence);
170}
171
Robin Morisset59c23cd2014-08-21 21:50:01 +0000172bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
Eric Christopherb11a1b72015-01-26 19:45:40 +0000173 if (TLI->hasLoadLinkedStoreConditional())
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000174 return expandAtomicLoadToLL(LI);
175 else
176 return expandAtomicLoadToCmpXchg(LI);
177}
178
179bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000180 IRBuilder<> Builder(LI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000181
Robin Morissetdedef332014-09-23 20:31:14 +0000182 // On some architectures, load-linked instructions are atomic for larger
183 // sizes than normal loads. For example, the only 64-bit load guaranteed
184 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
Robin Morisseta47cb412014-09-03 21:01:03 +0000185 Value *Val =
Robin Morissetdedef332014-09-23 20:31:14 +0000186 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
Tim Northoverc882eb02014-04-03 11:44:58 +0000187
188 LI->replaceAllUsesWith(Val);
189 LI->eraseFromParent();
190
191 return true;
192}
193
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000194bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
195 IRBuilder<> Builder(LI);
196 AtomicOrdering Order = LI->getOrdering();
197 Value *Addr = LI->getPointerOperand();
198 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
199 Constant *DummyVal = Constant::getNullValue(Ty);
200
201 Value *Pair = Builder.CreateAtomicCmpXchg(
202 Addr, DummyVal, DummyVal, Order,
203 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
204 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
205
206 LI->replaceAllUsesWith(Loaded);
207 LI->eraseFromParent();
208
209 return true;
210}
211
Robin Morisset59c23cd2014-08-21 21:50:01 +0000212bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
Robin Morisset25c8e312014-09-17 00:06:58 +0000213 // This function is only called on atomic stores that are too large to be
214 // atomic if implemented as a native store. So we replace them by an
215 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
216 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
JF Bastienf14889e2015-03-04 15:47:57 +0000217 // It is the responsibility of the target to only signal expansion via
Robin Morisset25c8e312014-09-17 00:06:58 +0000218 // shouldExpandAtomicRMW in cases where this is required and possible.
Tim Northoverc882eb02014-04-03 11:44:58 +0000219 IRBuilder<> Builder(SI);
220 AtomicRMWInst *AI =
221 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
222 SI->getValueOperand(), SI->getOrdering());
223 SI->eraseFromParent();
224
225 // Now we have an appropriate swap instruction, lower it as usual.
JF Bastienf14889e2015-03-04 15:47:57 +0000226 return tryExpandAtomicRMW(AI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000227}
228
JF Bastiene8aad292015-08-03 15:29:47 +0000229static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
230 Value *Loaded, Value *NewVal,
231 AtomicOrdering MemOpOrder,
232 Value *&Success, Value *&NewLoaded) {
233 Value* Pair = Builder.CreateAtomicCmpXchg(
234 Addr, Loaded, NewVal, MemOpOrder,
235 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
236 Success = Builder.CreateExtractValue(Pair, 1, "success");
237 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
238}
239
JF Bastienf14889e2015-03-04 15:47:57 +0000240bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
241 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
242 case TargetLoweringBase::AtomicRMWExpansionKind::None:
243 return false;
244 case TargetLoweringBase::AtomicRMWExpansionKind::LLSC: {
245 assert(TLI->hasLoadLinkedStoreConditional() &&
246 "TargetLowering requested we expand AtomicRMW instruction into "
247 "load-linked/store-conditional combos, but such instructions aren't "
248 "supported");
249
Robin Morisset25c8e312014-09-17 00:06:58 +0000250 return expandAtomicRMWToLLSC(AI);
JF Bastienf14889e2015-03-04 15:47:57 +0000251 }
252 case TargetLoweringBase::AtomicRMWExpansionKind::CmpXChg: {
JF Bastiene8aad292015-08-03 15:29:47 +0000253 return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
JF Bastienf14889e2015-03-04 15:47:57 +0000254 }
255 }
256 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
Robin Morisset25c8e312014-09-17 00:06:58 +0000257}
258
259/// Emit IR to implement the given atomicrmw operation on values in registers,
260/// returning the new value.
261static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
262 Value *Loaded, Value *Inc) {
263 Value *NewVal;
264 switch (Op) {
265 case AtomicRMWInst::Xchg:
266 return Inc;
267 case AtomicRMWInst::Add:
268 return Builder.CreateAdd(Loaded, Inc, "new");
269 case AtomicRMWInst::Sub:
270 return Builder.CreateSub(Loaded, Inc, "new");
271 case AtomicRMWInst::And:
272 return Builder.CreateAnd(Loaded, Inc, "new");
273 case AtomicRMWInst::Nand:
274 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
275 case AtomicRMWInst::Or:
276 return Builder.CreateOr(Loaded, Inc, "new");
277 case AtomicRMWInst::Xor:
278 return Builder.CreateXor(Loaded, Inc, "new");
279 case AtomicRMWInst::Max:
280 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
281 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
282 case AtomicRMWInst::Min:
283 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
284 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
285 case AtomicRMWInst::UMax:
286 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
287 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
288 case AtomicRMWInst::UMin:
289 NewVal = Builder.CreateICmpULE(Loaded, Inc);
290 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
291 default:
292 llvm_unreachable("Unknown atomic op");
293 }
294}
295
296bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
Robin Morissetdedef332014-09-23 20:31:14 +0000297 AtomicOrdering MemOpOrder = AI->getOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000298 Value *Addr = AI->getPointerOperand();
299 BasicBlock *BB = AI->getParent();
300 Function *F = BB->getParent();
301 LLVMContext &Ctx = F->getContext();
302
303 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
304 //
305 // The standard expansion we produce is:
306 // [...]
307 // fence?
308 // atomicrmw.start:
309 // %loaded = @load.linked(%addr)
310 // %new = some_op iN %loaded, %incr
311 // %stored = @store_conditional(%new, %addr)
312 // %try_again = icmp i32 ne %stored, 0
313 // br i1 %try_again, label %loop, label %atomicrmw.end
314 // atomicrmw.end:
315 // fence?
316 // [...]
317 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
318 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
319
320 // This grabs the DebugLoc from AI.
321 IRBuilder<> Builder(AI);
322
323 // The split call above "helpfully" added a branch at the end of BB (to the
324 // wrong place), but we might want a fence too. It's easiest to just remove
325 // the branch entirely.
326 std::prev(BB->end())->eraseFromParent();
327 Builder.SetInsertPoint(BB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000328 Builder.CreateBr(LoopBB);
329
330 // Start the main loop block now that we've taken care of the preliminaries.
331 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000332 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000333
Robin Morisset25c8e312014-09-17 00:06:58 +0000334 Value *NewVal =
335 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
Tim Northoverc882eb02014-04-03 11:44:58 +0000336
Eric Christopherd9134482014-08-04 21:25:23 +0000337 Value *StoreSuccess =
Robin Morisseta47cb412014-09-03 21:01:03 +0000338 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000339 Value *TryAgain = Builder.CreateICmpNE(
340 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
341 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
342
343 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northoverc882eb02014-04-03 11:44:58 +0000344
345 AI->replaceAllUsesWith(Loaded);
346 AI->eraseFromParent();
347
348 return true;
349}
350
Robin Morisset59c23cd2014-08-21 21:50:01 +0000351bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +0000352 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
353 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000354 Value *Addr = CI->getPointerOperand();
355 BasicBlock *BB = CI->getParent();
356 Function *F = BB->getParent();
357 LLVMContext &Ctx = F->getContext();
Robin Morisseted3d48f2014-09-03 21:29:59 +0000358 // If getInsertFencesForAtomic() returns true, then the target does not want
359 // to deal with memory orders, and emitLeading/TrailingFence should take care
360 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
361 // should preserve the ordering.
Robin Morisseta47cb412014-09-03 21:01:03 +0000362 AtomicOrdering MemOpOrder =
363 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
Tim Northoverc882eb02014-04-03 11:44:58 +0000364
365 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
366 //
Tim Northover70450c52014-04-03 13:06:54 +0000367 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +0000368 // [...]
369 // fence?
370 // cmpxchg.start:
371 // %loaded = @load.linked(%addr)
372 // %should_store = icmp eq %loaded, %desired
Tim Northover70450c52014-04-03 13:06:54 +0000373 // br i1 %should_store, label %cmpxchg.trystore,
Tim Northover20b9f732014-06-13 16:45:52 +0000374 // label %cmpxchg.failure
Tim Northoverc882eb02014-04-03 11:44:58 +0000375 // cmpxchg.trystore:
376 // %stored = @store_conditional(%new, %addr)
Tim Northover20b9f732014-06-13 16:45:52 +0000377 // %success = icmp eq i32 %stored, 0
378 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
379 // cmpxchg.success:
380 // fence?
381 // br label %cmpxchg.end
382 // cmpxchg.failure:
Tim Northoverc882eb02014-04-03 11:44:58 +0000383 // fence?
Tim Northover70450c52014-04-03 13:06:54 +0000384 // br label %cmpxchg.end
385 // cmpxchg.end:
Tim Northover20b9f732014-06-13 16:45:52 +0000386 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
387 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
388 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
Tim Northoverc882eb02014-04-03 11:44:58 +0000389 // [...]
390 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
Tim Northover20b9f732014-06-13 16:45:52 +0000391 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
392 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
393 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
Tim Northover70450c52014-04-03 13:06:54 +0000394 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000395
396 // This grabs the DebugLoc from CI
397 IRBuilder<> Builder(CI);
398
399 // The split call above "helpfully" added a branch at the end of BB (to the
400 // wrong place), but we might want a fence too. It's easiest to just remove
401 // the branch entirely.
402 std::prev(BB->end())->eraseFromParent();
403 Builder.SetInsertPoint(BB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000404 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
405 /*IsLoad=*/true);
Tim Northoverc882eb02014-04-03 11:44:58 +0000406 Builder.CreateBr(LoopBB);
407
408 // Start the main loop block now that we've taken care of the preliminaries.
409 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000410 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000411 Value *ShouldStore =
412 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +0000413
Eric Christopher572e03a2015-06-19 01:53:21 +0000414 // If the cmpxchg doesn't actually need any ordering when it fails, we can
Tim Northover70450c52014-04-03 13:06:54 +0000415 // jump straight past that fence instruction (if it exists).
Tim Northover70450c52014-04-03 13:06:54 +0000416 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000417
418 Builder.SetInsertPoint(TryStoreBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000419 Value *StoreSuccess = TLI->emitStoreConditional(
420 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
Tim Northoverd039abd2014-06-13 16:45:36 +0000421 StoreSuccess = Builder.CreateICmpEQ(
Tim Northoverc882eb02014-04-03 11:44:58 +0000422 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northover20b9f732014-06-13 16:45:52 +0000423 Builder.CreateCondBr(StoreSuccess, SuccessBB,
424 CI->isWeak() ? FailureBB : LoopBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000425
Tim Northoverb4ddc082014-05-30 10:09:59 +0000426 // Make sure later instructions don't get reordered with a fence if necessary.
Tim Northover20b9f732014-06-13 16:45:52 +0000427 Builder.SetInsertPoint(SuccessBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000428 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
429 /*IsLoad=*/true);
Tim Northover70450c52014-04-03 13:06:54 +0000430 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000431
Tim Northover20b9f732014-06-13 16:45:52 +0000432 Builder.SetInsertPoint(FailureBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000433 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
434 /*IsLoad=*/true);
Tim Northover20b9f732014-06-13 16:45:52 +0000435 Builder.CreateBr(ExitBB);
436
Tim Northoverb4ddc082014-05-30 10:09:59 +0000437 // Finally, we have control-flow based knowledge of whether the cmpxchg
438 // succeeded or not. We expose this to later passes by converting any
439 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
440
441 // Setup the builder so we can create any PHIs we need.
Tim Northover20b9f732014-06-13 16:45:52 +0000442 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northover420a2162014-06-13 14:24:07 +0000443 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
444 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
Tim Northover20b9f732014-06-13 16:45:52 +0000445 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000446
447 // Look for any users of the cmpxchg that are just comparing the loaded value
448 // against the desired one, and replace them with the CFG-derived version.
Tim Northover420a2162014-06-13 14:24:07 +0000449 SmallVector<ExtractValueInst *, 2> PrunedInsts;
Tim Northoverb4ddc082014-05-30 10:09:59 +0000450 for (auto User : CI->users()) {
Tim Northover420a2162014-06-13 14:24:07 +0000451 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
452 if (!EV)
Tim Northoverb4ddc082014-05-30 10:09:59 +0000453 continue;
454
Tim Northover420a2162014-06-13 14:24:07 +0000455 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
456 "weird extraction from { iN, i1 }");
Tim Northoverb4ddc082014-05-30 10:09:59 +0000457
Tim Northover420a2162014-06-13 14:24:07 +0000458 if (EV->getIndices()[0] == 0)
459 EV->replaceAllUsesWith(Loaded);
460 else
461 EV->replaceAllUsesWith(Success);
462
463 PrunedInsts.push_back(EV);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000464 }
465
Tim Northover420a2162014-06-13 14:24:07 +0000466 // We can remove the instructions now we're no longer iterating through them.
467 for (auto EV : PrunedInsts)
468 EV->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000469
Tim Northover420a2162014-06-13 14:24:07 +0000470 if (!CI->use_empty()) {
471 // Some use of the full struct return that we don't understand has happened,
472 // so we've got to reconstruct it properly.
473 Value *Res;
474 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
475 Res = Builder.CreateInsertValue(Res, Success, 1);
476
477 CI->replaceAllUsesWith(Res);
478 }
479
480 CI->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000481 return true;
482}
Robin Morisset810739d2014-09-25 17:27:43 +0000483
484bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
485 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
486 if(!C)
487 return false;
488
489 AtomicRMWInst::BinOp Op = RMWI->getOperation();
490 switch(Op) {
491 case AtomicRMWInst::Add:
492 case AtomicRMWInst::Sub:
493 case AtomicRMWInst::Or:
494 case AtomicRMWInst::Xor:
495 return C->isZero();
496 case AtomicRMWInst::And:
497 return C->isMinusOne();
498 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
499 default:
500 return false;
501 }
502}
503
504bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
Robin Morisset810739d2014-09-25 17:27:43 +0000505 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
506 if (TLI->shouldExpandAtomicLoadInIR(ResultingLoad))
507 expandAtomicLoad(ResultingLoad);
508 return true;
509 }
Robin Morisset810739d2014-09-25 17:27:43 +0000510 return false;
511}
JF Bastiene8aad292015-08-03 15:29:47 +0000512
513bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
514 CreateCmpXchgInstFun CreateCmpXchg) {
515 assert(AI);
516
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();
523
524 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
525 //
526 // The standard expansion we produce is:
527 // [...]
528 // %init_loaded = load atomic iN* %addr
529 // br label %loop
530 // loop:
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
537 // atomicrmw.end:
538 // [...]
539 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
540 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
541
542 // This grabs the DebugLoc from AI.
543 IRBuilder<> Builder(AI);
544
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());
553 Builder.CreateBr(LoopBB);
554
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);
559
560 Value *NewVal =
561 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
562
563 Value *NewLoaded = nullptr;
564 Value *Success = nullptr;
565
566 CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
567 Success, NewLoaded);
568 assert(Success && NewLoaded);
569
570 Loaded->addIncoming(NewLoaded, LoopBB);
571
572 Builder.CreateCondBr(Success, ExitBB, LoopBB);
573
574 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
575
576 AI->replaceAllUsesWith(NewLoaded);
577 AI->eraseFromParent();
578
579 return true;
580}