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