Add AtomicExpandPass::bracketInstWithFences, and use it whenever getInsertFencesForAt...
[oota-llvm.git] / lib / CodeGen / AtomicExpandPass.cpp
1 //===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
2 //
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
11 // either (intrinsic-based) load-linked/store-conditional loops or AtomicCmpXchg.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
26
27 using namespace llvm;
28
29 #define DEBUG_TYPE "atomic-expand"
30
31 namespace {
32   class AtomicExpand: public FunctionPass {
33     const TargetMachine *TM;
34   public:
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());
39     }
40
41     bool runOnFunction(Function &F) override;
42
43   private:
44     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
45                                bool IsStore, bool IsLoad);
46     bool expandAtomicLoad(LoadInst *LI);
47     bool expandAtomicStore(StoreInst *SI);
48     bool expandAtomicRMW(AtomicRMWInst *AI);
49     bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
50     bool expandAtomicRMWToCmpXchg(AtomicRMWInst *AI);
51     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
52   };
53 }
54
55 char AtomicExpand::ID = 0;
56 char &llvm::AtomicExpandID = AtomicExpand::ID;
57 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
58     "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
59     false, false)
60
61 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
62   return new AtomicExpand(TM);
63 }
64
65 bool AtomicExpand::runOnFunction(Function &F) {
66   if (!TM || !TM->getSubtargetImpl()->enableAtomicExpand())
67     return false;
68   auto TargetLowering = TM->getSubtargetImpl()->getTargetLowering();
69
70   SmallVector<Instruction *, 1> AtomicInsts;
71
72   // Changing control-flow while iterating through it is a bad idea, so gather a
73   // list of all atomic instructions before we start.
74   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
75     if (I->isAtomic())
76       AtomicInsts.push_back(&*I);
77   }
78
79   bool MadeChange = false;
80   for (auto I : AtomicInsts) {
81     auto LI = dyn_cast<LoadInst>(I);
82     auto SI = dyn_cast<StoreInst>(I);
83     auto RMWI = dyn_cast<AtomicRMWInst>(I);
84     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
85     assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
86            "Unknown atomic instruction");
87
88     auto FenceOrdering = Monotonic;
89     bool IsStore, IsLoad;
90     if (TargetLowering->getInsertFencesForAtomic()) {
91       if (LI && isAtLeastAcquire(LI->getOrdering())) {
92         FenceOrdering = LI->getOrdering();
93         LI->setOrdering(Monotonic);
94         IsStore = false;
95         IsLoad = true;
96       } else if (SI && isAtLeastRelease(SI->getOrdering())) {
97         FenceOrdering = SI->getOrdering();
98         SI->setOrdering(Monotonic);
99         IsStore = true;
100         IsLoad = false;
101       } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
102                           isAtLeastAcquire(RMWI->getOrdering()))) {
103         FenceOrdering = RMWI->getOrdering();
104         RMWI->setOrdering(Monotonic);
105         IsStore = IsLoad = true;
106       } else if (CASI && !TargetLowering->hasLoadLinkedStoreConditional() &&
107                     (isAtLeastRelease(CASI->getSuccessOrdering()) ||
108                      isAtLeastAcquire(CASI->getSuccessOrdering()))) {
109         // If a compare and swap is lowered to LL/SC, we can do smarter fence
110         // insertion, with a stronger one on the success path than on the
111         // failure path. As a result, fence insertion is directly done by
112         // expandAtomicCmpXchg in that case.
113         FenceOrdering = CASI->getSuccessOrdering();
114         CASI->setSuccessOrdering(Monotonic);
115         CASI->setFailureOrdering(Monotonic);
116         IsStore = IsLoad = true;
117       }
118
119       if (FenceOrdering != Monotonic) {
120         MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
121       }
122     }
123
124     if (LI && TargetLowering->shouldExpandAtomicLoadInIR(LI)) {
125       MadeChange |= expandAtomicLoad(LI);
126     } else if (SI && TargetLowering->shouldExpandAtomicStoreInIR(SI)) {
127       MadeChange |= expandAtomicStore(SI);
128     } else if (RMWI && TargetLowering->shouldExpandAtomicRMWInIR(RMWI)) {
129       MadeChange |= expandAtomicRMW(RMWI);
130     } else if (CASI && TargetLowering->hasLoadLinkedStoreConditional()) {
131       MadeChange |= expandAtomicCmpXchg(CASI);
132     }
133   }
134   return MadeChange;
135 }
136
137 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
138                                          bool IsStore, bool IsLoad) {
139   IRBuilder<> Builder(I);
140
141   auto LeadingFence =
142       TM->getSubtargetImpl()->getTargetLowering()->emitLeadingFence(
143       Builder, Order, IsStore, IsLoad);
144
145   auto TrailingFence =
146       TM->getSubtargetImpl()->getTargetLowering()->emitTrailingFence(
147       Builder, Order, IsStore, IsLoad);
148   // The trailing fence is emitted before the instruction instead of after
149   // because there is no easy way of setting Builder insertion point after
150   // an instruction. So we must erase it from the BB, and insert it back
151   // in the right place.
152   // We have a guard here because not every atomic operation generates a
153   // trailing fence.
154   if (TrailingFence) {
155     TrailingFence->removeFromParent();
156     TrailingFence->insertAfter(I);
157   }
158
159   return (LeadingFence || TrailingFence);
160 }
161
162 bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
163   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
164   IRBuilder<> Builder(LI);
165
166   // On some architectures, load-linked instructions are atomic for larger
167   // sizes than normal loads. For example, the only 64-bit load guaranteed
168   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
169   Value *Val =
170       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
171
172   LI->replaceAllUsesWith(Val);
173   LI->eraseFromParent();
174
175   return true;
176 }
177
178 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
179   // This function is only called on atomic stores that are too large to be
180   // atomic if implemented as a native store. So we replace them by an
181   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
182   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
183   // It is the responsibility of the target to only return true in
184   // shouldExpandAtomicRMW in cases where this is required and possible.
185   IRBuilder<> Builder(SI);
186   AtomicRMWInst *AI =
187       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
188                               SI->getValueOperand(), SI->getOrdering());
189   SI->eraseFromParent();
190
191   // Now we have an appropriate swap instruction, lower it as usual.
192   return expandAtomicRMW(AI);
193 }
194
195 bool AtomicExpand::expandAtomicRMW(AtomicRMWInst *AI) {
196   if (TM->getSubtargetImpl()
197           ->getTargetLowering()
198           ->hasLoadLinkedStoreConditional())
199     return expandAtomicRMWToLLSC(AI);
200   else
201     return expandAtomicRMWToCmpXchg(AI);
202 }
203
204 /// Emit IR to implement the given atomicrmw operation on values in registers,
205 /// returning the new value.
206 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
207                               Value *Loaded, Value *Inc) {
208   Value *NewVal;
209   switch (Op) {
210   case AtomicRMWInst::Xchg:
211     return Inc;
212   case AtomicRMWInst::Add:
213     return Builder.CreateAdd(Loaded, Inc, "new");
214   case AtomicRMWInst::Sub:
215     return Builder.CreateSub(Loaded, Inc, "new");
216   case AtomicRMWInst::And:
217     return Builder.CreateAnd(Loaded, Inc, "new");
218   case AtomicRMWInst::Nand:
219     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
220   case AtomicRMWInst::Or:
221     return Builder.CreateOr(Loaded, Inc, "new");
222   case AtomicRMWInst::Xor:
223     return Builder.CreateXor(Loaded, Inc, "new");
224   case AtomicRMWInst::Max:
225     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
226     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
227   case AtomicRMWInst::Min:
228     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
229     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
230   case AtomicRMWInst::UMax:
231     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
232     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
233   case AtomicRMWInst::UMin:
234     NewVal = Builder.CreateICmpULE(Loaded, Inc);
235     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
236   default:
237     llvm_unreachable("Unknown atomic op");
238   }
239 }
240
241 bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
242   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
243   AtomicOrdering MemOpOrder = AI->getOrdering();
244   Value *Addr = AI->getPointerOperand();
245   BasicBlock *BB = AI->getParent();
246   Function *F = BB->getParent();
247   LLVMContext &Ctx = F->getContext();
248
249   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
250   //
251   // The standard expansion we produce is:
252   //     [...]
253   //     fence?
254   // atomicrmw.start:
255   //     %loaded = @load.linked(%addr)
256   //     %new = some_op iN %loaded, %incr
257   //     %stored = @store_conditional(%new, %addr)
258   //     %try_again = icmp i32 ne %stored, 0
259   //     br i1 %try_again, label %loop, label %atomicrmw.end
260   // atomicrmw.end:
261   //     fence?
262   //     [...]
263   BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
264   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
265
266   // This grabs the DebugLoc from AI.
267   IRBuilder<> Builder(AI);
268
269   // The split call above "helpfully" added a branch at the end of BB (to the
270   // wrong place), but we might want a fence too. It's easiest to just remove
271   // the branch entirely.
272   std::prev(BB->end())->eraseFromParent();
273   Builder.SetInsertPoint(BB);
274   Builder.CreateBr(LoopBB);
275
276   // Start the main loop block now that we've taken care of the preliminaries.
277   Builder.SetInsertPoint(LoopBB);
278   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
279
280   Value *NewVal =
281       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
282
283   Value *StoreSuccess =
284       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
285   Value *TryAgain = Builder.CreateICmpNE(
286       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
287   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
288
289   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
290
291   AI->replaceAllUsesWith(Loaded);
292   AI->eraseFromParent();
293
294   return true;
295 }
296
297 bool AtomicExpand::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI) {
298   AtomicOrdering MemOpOrder =
299       AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
300   Value *Addr = AI->getPointerOperand();
301   BasicBlock *BB = AI->getParent();
302   Function *F = BB->getParent();
303   LLVMContext &Ctx = F->getContext();
304
305   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
306   //
307   // The standard expansion we produce is:
308   //     [...]
309   //     %init_loaded = load atomic iN* %addr
310   //     br label %loop
311   // loop:
312   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
313   //     %new = some_op iN %loaded, %incr
314   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
315   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
316   //     %success = extractvalue { iN, i1 } %pair, 1
317   //     br i1 %success, label %atomicrmw.end, label %loop
318   // atomicrmw.end:
319   //     [...]
320   BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
321   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
322
323   // This grabs the DebugLoc from AI.
324   IRBuilder<> Builder(AI);
325
326   // The split call above "helpfully" added a branch at the end of BB (to the
327   // wrong place), but we want a load. It's easiest to just remove
328   // the branch entirely.
329   std::prev(BB->end())->eraseFromParent();
330   Builder.SetInsertPoint(BB);
331   LoadInst *InitLoaded = Builder.CreateLoad(Addr);
332   // Atomics require at least natural alignment.
333   InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits());
334   Builder.CreateBr(LoopBB);
335
336   // Start the main loop block now that we've taken care of the preliminaries.
337   Builder.SetInsertPoint(LoopBB);
338   PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
339   Loaded->addIncoming(InitLoaded, BB);
340
341   Value *NewVal =
342       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
343
344   Value *Pair = Builder.CreateAtomicCmpXchg(
345       Addr, Loaded, NewVal, MemOpOrder,
346       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
347   Value *NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
348   Loaded->addIncoming(NewLoaded, LoopBB);
349
350   Value *Success = Builder.CreateExtractValue(Pair, 1, "success");
351   Builder.CreateCondBr(Success, ExitBB, LoopBB);
352
353   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
354
355   AI->replaceAllUsesWith(NewLoaded);
356   AI->eraseFromParent();
357
358   return true;
359 }
360
361 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
362   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
363   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
364   AtomicOrdering FailureOrder = CI->getFailureOrdering();
365   Value *Addr = CI->getPointerOperand();
366   BasicBlock *BB = CI->getParent();
367   Function *F = BB->getParent();
368   LLVMContext &Ctx = F->getContext();
369   // If getInsertFencesForAtomic() returns true, then the target does not want
370   // to deal with memory orders, and emitLeading/TrailingFence should take care
371   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
372   // should preserve the ordering.
373   AtomicOrdering MemOpOrder =
374       TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
375
376   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
377   //
378   // The full expansion we produce is:
379   //     [...]
380   //     fence?
381   // cmpxchg.start:
382   //     %loaded = @load.linked(%addr)
383   //     %should_store = icmp eq %loaded, %desired
384   //     br i1 %should_store, label %cmpxchg.trystore,
385   //                          label %cmpxchg.failure
386   // cmpxchg.trystore:
387   //     %stored = @store_conditional(%new, %addr)
388   //     %success = icmp eq i32 %stored, 0
389   //     br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
390   // cmpxchg.success:
391   //     fence?
392   //     br label %cmpxchg.end
393   // cmpxchg.failure:
394   //     fence?
395   //     br label %cmpxchg.end
396   // cmpxchg.end:
397   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
398   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
399   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
400   //     [...]
401   BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
402   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
403   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
404   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
405   auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
406
407   // This grabs the DebugLoc from CI
408   IRBuilder<> Builder(CI);
409
410   // The split call above "helpfully" added a branch at the end of BB (to the
411   // wrong place), but we might want a fence too. It's easiest to just remove
412   // the branch entirely.
413   std::prev(BB->end())->eraseFromParent();
414   Builder.SetInsertPoint(BB);
415   TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
416                         /*IsLoad=*/true);
417   Builder.CreateBr(LoopBB);
418
419   // Start the main loop block now that we've taken care of the preliminaries.
420   Builder.SetInsertPoint(LoopBB);
421   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
422   Value *ShouldStore =
423       Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
424
425   // If the the cmpxchg doesn't actually need any ordering when it fails, we can
426   // jump straight past that fence instruction (if it exists).
427   Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
428
429   Builder.SetInsertPoint(TryStoreBB);
430   Value *StoreSuccess = TLI->emitStoreConditional(
431       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
432   StoreSuccess = Builder.CreateICmpEQ(
433       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
434   Builder.CreateCondBr(StoreSuccess, SuccessBB,
435                        CI->isWeak() ? FailureBB : LoopBB);
436
437   // Make sure later instructions don't get reordered with a fence if necessary.
438   Builder.SetInsertPoint(SuccessBB);
439   TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
440                          /*IsLoad=*/true);
441   Builder.CreateBr(ExitBB);
442
443   Builder.SetInsertPoint(FailureBB);
444   TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
445                          /*IsLoad=*/true);
446   Builder.CreateBr(ExitBB);
447
448   // Finally, we have control-flow based knowledge of whether the cmpxchg
449   // succeeded or not. We expose this to later passes by converting any
450   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
451
452   // Setup the builder so we can create any PHIs we need.
453   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
454   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
455   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
456   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
457
458   // Look for any users of the cmpxchg that are just comparing the loaded value
459   // against the desired one, and replace them with the CFG-derived version.
460   SmallVector<ExtractValueInst *, 2> PrunedInsts;
461   for (auto User : CI->users()) {
462     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
463     if (!EV)
464       continue;
465
466     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
467            "weird extraction from { iN, i1 }");
468
469     if (EV->getIndices()[0] == 0)
470       EV->replaceAllUsesWith(Loaded);
471     else
472       EV->replaceAllUsesWith(Success);
473
474     PrunedInsts.push_back(EV);
475   }
476
477   // We can remove the instructions now we're no longer iterating through them.
478   for (auto EV : PrunedInsts)
479     EV->eraseFromParent();
480
481   if (!CI->use_empty()) {
482     // Some use of the full struct return that we don't understand has happened,
483     // so we've got to reconstruct it properly.
484     Value *Res;
485     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
486     Res = Builder.CreateInsertValue(Res, Success, 1);
487
488     CI->replaceAllUsesWith(Res);
489   }
490
491   CI->eraseFromParent();
492   return true;
493 }