Modifies AtomicExpandPass to transform relaxed loads/RMW/AtomicXchg to acquire
[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 // target specific instruction which implement the same semantics in a way
12 // which better fits the target backend.  This can include the use of either
13 // (intrinsic-based) load-linked/store-conditional loops, AtomicCmpXchg, or
14 // type coercions.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/CodeGen/AtomicExpandUtils.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/InstIterator.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31
32 using namespace llvm;
33
34 #define DEBUG_TYPE "atomic-expand"
35
36 namespace {
37   class AtomicExpand: public FunctionPass {
38     const TargetMachine *TM;
39     const TargetLowering *TLI;
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     explicit AtomicExpand(const TargetMachine *TM = nullptr)
43       : FunctionPass(ID), TM(TM), TLI(nullptr) {
44       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
45     }
46
47     bool runOnFunction(Function &F) override;
48
49   private:
50     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
51                                bool IsStore, bool IsLoad);
52     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
53     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
54     bool tryExpandAtomicLoad(LoadInst *LI);
55     bool expandAtomicLoadToLL(LoadInst *LI);
56     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
57     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
58     bool expandAtomicStore(StoreInst *SI);
59     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
60     bool expandAtomicOpToLLSC(
61         Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
62         std::function<Value *(IRBuilder<> &, Value *)> PerformOp);
63     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
64     bool isIdempotentRMW(AtomicRMWInst *AI);
65     bool simplifyIdempotentRMW(AtomicRMWInst *AI);
66   };
67 }
68
69 char AtomicExpand::ID = 0;
70 char &llvm::AtomicExpandID = AtomicExpand::ID;
71 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
72     "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
73     false, false)
74
75 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
76   return new AtomicExpand(TM);
77 }
78
79 bool AtomicExpand::runOnFunction(Function &F) {
80   if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
81     return false;
82   TLI = TM->getSubtargetImpl(F)->getTargetLowering();
83
84   SmallVector<Instruction *, 1> AtomicInsts;
85
86   // Changing control-flow while iterating through it is a bad idea, so gather a
87   // list of all atomic instructions before we start.
88   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
89     // XXX-update: For relaxed loads, change them to acquire. This includes
90     // relaxed loads, relaxed atomic RMW & relaxed atomic compare exchange.
91     if (I->isAtomic()) {
92       switch (I->getOpcode()) {
93         case Instruction::AtomicCmpXchg: {
94           auto* CmpXchg = dyn_cast<AtomicCmpXchgInst>(&*I);
95           auto SuccOrdering = CmpXchg->getSuccessOrdering();
96           if (SuccOrdering == Monotonic) {
97             CmpXchg->setSuccessOrdering(Acquire);
98           } else if (SuccOrdering == Release) {
99             CmpXchg->setSuccessOrdering(AcquireRelease);
100           }
101           break;
102         }
103         case Instruction::AtomicRMW: {
104           auto* RMW = dyn_cast<AtomicRMWInst>(&*I);
105           if (RMW->getOrdering() == Monotonic) {
106             RMW->setOrdering(Acquire);
107           }
108           break;
109         }
110         case Instruction::Load: {
111           auto* LI = dyn_cast<LoadInst>(&*I);
112           if (LI->getOrdering() == Monotonic) {
113             LI->setOrdering(Acquire);
114           }
115           break;
116         }
117         default: {
118           break;
119         }
120       }
121       AtomicInsts.push_back(&*I);
122     }
123   }
124
125   bool MadeChange = false;
126   for (auto I : AtomicInsts) {
127     auto LI = dyn_cast<LoadInst>(I);
128     auto SI = dyn_cast<StoreInst>(I);
129     auto RMWI = dyn_cast<AtomicRMWInst>(I);
130     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
131     assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
132            "Unknown atomic instruction");
133
134     auto FenceOrdering = Monotonic;
135     bool IsStore, IsLoad;
136     if (TLI->getInsertFencesForAtomic()) {
137       if (LI && isAtLeastAcquire(LI->getOrdering())) {
138         FenceOrdering = LI->getOrdering();
139         LI->setOrdering(Monotonic);
140         IsStore = false;
141         IsLoad = true;
142       } else if (SI && isAtLeastRelease(SI->getOrdering())) {
143         FenceOrdering = SI->getOrdering();
144         SI->setOrdering(Monotonic);
145         IsStore = true;
146         IsLoad = false;
147       } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
148                           isAtLeastAcquire(RMWI->getOrdering()))) {
149         FenceOrdering = RMWI->getOrdering();
150         RMWI->setOrdering(Monotonic);
151         IsStore = IsLoad = true;
152       } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
153                  (isAtLeastRelease(CASI->getSuccessOrdering()) ||
154                   isAtLeastAcquire(CASI->getSuccessOrdering()))) {
155         // If a compare and swap is lowered to LL/SC, we can do smarter fence
156         // insertion, with a stronger one on the success path than on the
157         // failure path. As a result, fence insertion is directly done by
158         // expandAtomicCmpXchg in that case.
159         FenceOrdering = CASI->getSuccessOrdering();
160         CASI->setSuccessOrdering(Monotonic);
161         CASI->setFailureOrdering(Monotonic);
162         IsStore = IsLoad = true;
163       }
164
165       if (FenceOrdering != Monotonic) {
166         MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
167       }
168     }
169
170     if (LI) {
171       if (LI->getType()->isFloatingPointTy()) {
172         // TODO: add a TLI hook to control this so that each target can
173         // convert to lowering the original type one at a time.
174         LI = convertAtomicLoadToIntegerType(LI);
175         assert(LI->getType()->isIntegerTy() && "invariant broken");
176         MadeChange = true;
177       }
178       
179       MadeChange |= tryExpandAtomicLoad(LI);
180     } else if (SI) {
181       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
182         // TODO: add a TLI hook to control this so that each target can
183         // convert to lowering the original type one at a time.
184         SI = convertAtomicStoreToIntegerType(SI);
185         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
186                "invariant broken");
187         MadeChange = true;
188       }
189
190       if (TLI->shouldExpandAtomicStoreInIR(SI))
191         MadeChange |= expandAtomicStore(SI);
192     } else if (RMWI) {
193       // There are two different ways of expanding RMW instructions:
194       // - into a load if it is idempotent
195       // - into a Cmpxchg/LL-SC loop otherwise
196       // we try them in that order.
197
198       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
199         MadeChange = true;
200       } else {
201         MadeChange |= tryExpandAtomicRMW(RMWI);
202       }
203     } else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI)) {
204       MadeChange |= expandAtomicCmpXchg(CASI);
205     }
206   }
207   return MadeChange;
208 }
209
210 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
211                                          bool IsStore, bool IsLoad) {
212   IRBuilder<> Builder(I);
213
214   auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
215
216   auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
217   // The trailing fence is emitted before the instruction instead of after
218   // because there is no easy way of setting Builder insertion point after
219   // an instruction. So we must erase it from the BB, and insert it back
220   // in the right place.
221   // We have a guard here because not every atomic operation generates a
222   // trailing fence.
223   if (TrailingFence) {
224     TrailingFence->removeFromParent();
225     TrailingFence->insertAfter(I);
226   }
227
228   return (LeadingFence || TrailingFence);
229 }
230
231 /// Get the iX type with the same bitwidth as T.
232 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
233                                                        const DataLayout &DL) {
234   EVT VT = TLI->getValueType(DL, T);
235   unsigned BitWidth = VT.getStoreSizeInBits();
236   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
237   return IntegerType::get(T->getContext(), BitWidth);
238 }
239
240 /// Convert an atomic load of a non-integral type to an integer load of the
241 /// equivelent bitwidth.  See the function comment on
242 /// convertAtomicStoreToIntegerType for background.  
243 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
244   auto *M = LI->getModule();
245   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
246                                             M->getDataLayout());
247
248   IRBuilder<> Builder(LI);
249   
250   Value *Addr = LI->getPointerOperand();
251   Type *PT = PointerType::get(NewTy,
252                               Addr->getType()->getPointerAddressSpace());
253   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
254   
255   auto *NewLI = Builder.CreateLoad(NewAddr);
256   NewLI->setAlignment(LI->getAlignment());
257   NewLI->setVolatile(LI->isVolatile());
258   NewLI->setAtomic(LI->getOrdering(), LI->getSynchScope());
259   DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
260   
261   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
262   LI->replaceAllUsesWith(NewVal);
263   LI->eraseFromParent();
264   return NewLI;
265 }
266
267 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
268   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
269   case TargetLoweringBase::AtomicExpansionKind::None:
270     return false;
271   case TargetLoweringBase::AtomicExpansionKind::LLSC:
272     return expandAtomicOpToLLSC(
273         LI, LI->getPointerOperand(), LI->getOrdering(),
274         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
275   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
276     return expandAtomicLoadToLL(LI);
277   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
278     return expandAtomicLoadToCmpXchg(LI);
279   }
280   llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
281 }
282
283 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
284   IRBuilder<> Builder(LI);
285
286   // On some architectures, load-linked instructions are atomic for larger
287   // sizes than normal loads. For example, the only 64-bit load guaranteed
288   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
289   Value *Val =
290       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
291   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
292
293   LI->replaceAllUsesWith(Val);
294   LI->eraseFromParent();
295
296   return true;
297 }
298
299 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
300   IRBuilder<> Builder(LI);
301   AtomicOrdering Order = LI->getOrdering();
302   Value *Addr = LI->getPointerOperand();
303   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
304   Constant *DummyVal = Constant::getNullValue(Ty);
305
306   Value *Pair = Builder.CreateAtomicCmpXchg(
307       Addr, DummyVal, DummyVal, Order,
308       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
309   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
310
311   LI->replaceAllUsesWith(Loaded);
312   LI->eraseFromParent();
313
314   return true;
315 }
316
317 /// Convert an atomic store of a non-integral type to an integer store of the
318 /// equivelent bitwidth.  We used to not support floating point or vector
319 /// atomics in the IR at all.  The backends learned to deal with the bitcast
320 /// idiom because that was the only way of expressing the notion of a atomic
321 /// float or vector store.  The long term plan is to teach each backend to
322 /// instruction select from the original atomic store, but as a migration
323 /// mechanism, we convert back to the old format which the backends understand.
324 /// Each backend will need individual work to recognize the new format.
325 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
326   IRBuilder<> Builder(SI);
327   auto *M = SI->getModule();
328   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
329                                             M->getDataLayout());
330   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
331   
332   Value *Addr = SI->getPointerOperand();
333   Type *PT = PointerType::get(NewTy,
334                               Addr->getType()->getPointerAddressSpace());
335   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
336
337   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
338   NewSI->setAlignment(SI->getAlignment());
339   NewSI->setVolatile(SI->isVolatile());
340   NewSI->setAtomic(SI->getOrdering(), SI->getSynchScope());
341   DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
342   SI->eraseFromParent();
343   return NewSI;
344 }
345
346 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
347   // This function is only called on atomic stores that are too large to be
348   // atomic if implemented as a native store. So we replace them by an
349   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
350   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
351   // It is the responsibility of the target to only signal expansion via
352   // shouldExpandAtomicRMW in cases where this is required and possible.
353   IRBuilder<> Builder(SI);
354   AtomicRMWInst *AI =
355       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
356                               SI->getValueOperand(), SI->getOrdering());
357   SI->eraseFromParent();
358
359   // Now we have an appropriate swap instruction, lower it as usual.
360   return tryExpandAtomicRMW(AI);
361 }
362
363 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
364                                  Value *Loaded, Value *NewVal,
365                                  AtomicOrdering MemOpOrder,
366                                  Value *&Success, Value *&NewLoaded) {
367   Value* Pair = Builder.CreateAtomicCmpXchg(
368       Addr, Loaded, NewVal, MemOpOrder,
369       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
370   Success = Builder.CreateExtractValue(Pair, 1, "success");
371   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
372 }
373
374 /// Emit IR to implement the given atomicrmw operation on values in registers,
375 /// returning the new value.
376 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
377                               Value *Loaded, Value *Inc) {
378   Value *NewVal;
379   switch (Op) {
380   case AtomicRMWInst::Xchg:
381     return Inc;
382   case AtomicRMWInst::Add:
383     return Builder.CreateAdd(Loaded, Inc, "new");
384   case AtomicRMWInst::Sub:
385     return Builder.CreateSub(Loaded, Inc, "new");
386   case AtomicRMWInst::And:
387     return Builder.CreateAnd(Loaded, Inc, "new");
388   case AtomicRMWInst::Nand:
389     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
390   case AtomicRMWInst::Or:
391     return Builder.CreateOr(Loaded, Inc, "new");
392   case AtomicRMWInst::Xor:
393     return Builder.CreateXor(Loaded, Inc, "new");
394   case AtomicRMWInst::Max:
395     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
396     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
397   case AtomicRMWInst::Min:
398     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
399     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
400   case AtomicRMWInst::UMax:
401     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
402     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
403   case AtomicRMWInst::UMin:
404     NewVal = Builder.CreateICmpULE(Loaded, Inc);
405     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
406   default:
407     llvm_unreachable("Unknown atomic op");
408   }
409 }
410
411 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
412   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
413   case TargetLoweringBase::AtomicExpansionKind::None:
414     return false;
415   case TargetLoweringBase::AtomicExpansionKind::LLSC:
416     return expandAtomicOpToLLSC(AI, AI->getPointerOperand(), AI->getOrdering(),
417                                 [&](IRBuilder<> &Builder, Value *Loaded) {
418                                   return performAtomicOp(AI->getOperation(),
419                                                          Builder, Loaded,
420                                                          AI->getValOperand());
421                                 });
422   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
423     return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
424   default:
425     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
426   }
427 }
428
429 bool AtomicExpand::expandAtomicOpToLLSC(
430     Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
431     std::function<Value *(IRBuilder<> &, Value *)> PerformOp) {
432   BasicBlock *BB = I->getParent();
433   Function *F = BB->getParent();
434   LLVMContext &Ctx = F->getContext();
435
436   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
437   //
438   // The standard expansion we produce is:
439   //     [...]
440   //     fence?
441   // atomicrmw.start:
442   //     %loaded = @load.linked(%addr)
443   //     %new = some_op iN %loaded, %incr
444   //     %stored = @store_conditional(%new, %addr)
445   //     %try_again = icmp i32 ne %stored, 0
446   //     br i1 %try_again, label %loop, label %atomicrmw.end
447   // atomicrmw.end:
448   //     fence?
449   //     [...]
450   BasicBlock *ExitBB = BB->splitBasicBlock(I->getIterator(), "atomicrmw.end");
451   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
452
453   // This grabs the DebugLoc from I.
454   IRBuilder<> Builder(I);
455
456   // The split call above "helpfully" added a branch at the end of BB (to the
457   // wrong place), but we might want a fence too. It's easiest to just remove
458   // the branch entirely.
459   std::prev(BB->end())->eraseFromParent();
460   Builder.SetInsertPoint(BB);
461   Builder.CreateBr(LoopBB);
462
463   // Start the main loop block now that we've taken care of the preliminaries.
464   Builder.SetInsertPoint(LoopBB);
465   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
466
467   Value *NewVal = PerformOp(Builder, Loaded);
468
469   Value *StoreSuccess =
470       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
471   Value *TryAgain = Builder.CreateICmpNE(
472       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
473   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
474
475   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
476
477   I->replaceAllUsesWith(Loaded);
478   I->eraseFromParent();
479
480   return true;
481 }
482
483 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
484   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
485   AtomicOrdering FailureOrder = CI->getFailureOrdering();
486   Value *Addr = CI->getPointerOperand();
487   BasicBlock *BB = CI->getParent();
488   Function *F = BB->getParent();
489   LLVMContext &Ctx = F->getContext();
490   // If getInsertFencesForAtomic() returns true, then the target does not want
491   // to deal with memory orders, and emitLeading/TrailingFence should take care
492   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
493   // should preserve the ordering.
494   AtomicOrdering MemOpOrder =
495       TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
496
497   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
498   //
499   // The full expansion we produce is:
500   //     [...]
501   //     fence?
502   // cmpxchg.start:
503   //     %loaded = @load.linked(%addr)
504   //     %should_store = icmp eq %loaded, %desired
505   //     br i1 %should_store, label %cmpxchg.trystore,
506   //                          label %cmpxchg.nostore
507   // cmpxchg.trystore:
508   //     %stored = @store_conditional(%new, %addr)
509   //     %success = icmp eq i32 %stored, 0
510   //     br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
511   // cmpxchg.success:
512   //     fence?
513   //     br label %cmpxchg.end
514   // cmpxchg.nostore:
515   //     @load_linked_fail_balance()?
516   //     br label %cmpxchg.failure
517   // cmpxchg.failure:
518   //     fence?
519   //     br label %cmpxchg.end
520   // cmpxchg.end:
521   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
522   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
523   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
524   //     [...]
525   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
526   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
527   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
528   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
529   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
530   auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
531
532   // This grabs the DebugLoc from CI
533   IRBuilder<> Builder(CI);
534
535   // The split call above "helpfully" added a branch at the end of BB (to the
536   // wrong place), but we might want a fence too. It's easiest to just remove
537   // the branch entirely.
538   std::prev(BB->end())->eraseFromParent();
539   Builder.SetInsertPoint(BB);
540   TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
541                         /*IsLoad=*/true);
542   Builder.CreateBr(LoopBB);
543
544   // Start the main loop block now that we've taken care of the preliminaries.
545   Builder.SetInsertPoint(LoopBB);
546   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
547   Value *ShouldStore =
548       Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
549
550   // If the cmpxchg doesn't actually need any ordering when it fails, we can
551   // jump straight past that fence instruction (if it exists).
552   Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
553
554   Builder.SetInsertPoint(TryStoreBB);
555   Value *StoreSuccess = TLI->emitStoreConditional(
556       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
557   StoreSuccess = Builder.CreateICmpEQ(
558       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
559   Builder.CreateCondBr(StoreSuccess, SuccessBB,
560                        CI->isWeak() ? FailureBB : LoopBB);
561
562   // Make sure later instructions don't get reordered with a fence if necessary.
563   Builder.SetInsertPoint(SuccessBB);
564   TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
565                          /*IsLoad=*/true);
566   Builder.CreateBr(ExitBB);
567
568   Builder.SetInsertPoint(NoStoreBB);
569   // In the failing case, where we don't execute the store-conditional, the
570   // target might want to balance out the load-linked with a dedicated
571   // instruction (e.g., on ARM, clearing the exclusive monitor).
572   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
573   Builder.CreateBr(FailureBB);
574
575   Builder.SetInsertPoint(FailureBB);
576   TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
577                          /*IsLoad=*/true);
578   Builder.CreateBr(ExitBB);
579
580   // Finally, we have control-flow based knowledge of whether the cmpxchg
581   // succeeded or not. We expose this to later passes by converting any
582   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
583
584   // Setup the builder so we can create any PHIs we need.
585   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
586   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
587   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
588   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
589
590   // Look for any users of the cmpxchg that are just comparing the loaded value
591   // against the desired one, and replace them with the CFG-derived version.
592   SmallVector<ExtractValueInst *, 2> PrunedInsts;
593   for (auto User : CI->users()) {
594     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
595     if (!EV)
596       continue;
597
598     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
599            "weird extraction from { iN, i1 }");
600
601     if (EV->getIndices()[0] == 0)
602       EV->replaceAllUsesWith(Loaded);
603     else
604       EV->replaceAllUsesWith(Success);
605
606     PrunedInsts.push_back(EV);
607   }
608
609   // We can remove the instructions now we're no longer iterating through them.
610   for (auto EV : PrunedInsts)
611     EV->eraseFromParent();
612
613   if (!CI->use_empty()) {
614     // Some use of the full struct return that we don't understand has happened,
615     // so we've got to reconstruct it properly.
616     Value *Res;
617     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
618     Res = Builder.CreateInsertValue(Res, Success, 1);
619
620     CI->replaceAllUsesWith(Res);
621   }
622
623   CI->eraseFromParent();
624   return true;
625 }
626
627 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
628   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
629   if(!C)
630     return false;
631
632   AtomicRMWInst::BinOp Op = RMWI->getOperation();
633   switch(Op) {
634     case AtomicRMWInst::Add:
635     case AtomicRMWInst::Sub:
636     case AtomicRMWInst::Or:
637     case AtomicRMWInst::Xor:
638       return C->isZero();
639     case AtomicRMWInst::And:
640       return C->isMinusOne();
641     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
642     default:
643       return false;
644   }
645 }
646
647 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
648   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
649     tryExpandAtomicLoad(ResultingLoad);
650     return true;
651   }
652   return false;
653 }
654
655 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
656                                     CreateCmpXchgInstFun CreateCmpXchg) {
657   assert(AI);
658
659   AtomicOrdering MemOpOrder =
660       AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
661   Value *Addr = AI->getPointerOperand();
662   BasicBlock *BB = AI->getParent();
663   Function *F = BB->getParent();
664   LLVMContext &Ctx = F->getContext();
665
666   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
667   //
668   // The standard expansion we produce is:
669   //     [...]
670   //     %init_loaded = load atomic iN* %addr
671   //     br label %loop
672   // loop:
673   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
674   //     %new = some_op iN %loaded, %incr
675   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
676   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
677   //     %success = extractvalue { iN, i1 } %pair, 1
678   //     br i1 %success, label %atomicrmw.end, label %loop
679   // atomicrmw.end:
680   //     [...]
681   BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
682   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
683
684   // This grabs the DebugLoc from AI.
685   IRBuilder<> Builder(AI);
686
687   // The split call above "helpfully" added a branch at the end of BB (to the
688   // wrong place), but we want a load. It's easiest to just remove
689   // the branch entirely.
690   std::prev(BB->end())->eraseFromParent();
691   Builder.SetInsertPoint(BB);
692   LoadInst *InitLoaded = Builder.CreateLoad(Addr);
693   // Atomics require at least natural alignment.
694   InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits() / 8);
695   Builder.CreateBr(LoopBB);
696
697   // Start the main loop block now that we've taken care of the preliminaries.
698   Builder.SetInsertPoint(LoopBB);
699   PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
700   Loaded->addIncoming(InitLoaded, BB);
701
702   Value *NewVal =
703       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
704
705   Value *NewLoaded = nullptr;
706   Value *Success = nullptr;
707
708   CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
709                 Success, NewLoaded);
710   assert(Success && NewLoaded);
711
712   Loaded->addIncoming(NewLoaded, LoopBB);
713
714   Builder.CreateCondBr(Success, ExitBB, LoopBB);
715
716   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
717
718   AI->replaceAllUsesWith(NewLoaded);
719   AI->eraseFromParent();
720
721   return true;
722 }