1 //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass (at IR level) to replace atomic instructions with
10 // __atomic_* library calls, or target specific instruction which implement the
11 // same semantics in a way which better fits the target backend.  This can
12 // include the use of (intrinsic-based) load-linked/store-conditional loops,
13 // AtomicCmpXchg, or type coercions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/AtomicExpandUtils.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/User.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/AtomicOrdering.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include <cassert>
50 #include <cstdint>
51 #include <iterator>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "atomic-expand"
56 
57 namespace {
58 
59   class AtomicExpand: public FunctionPass {
60     const TargetLowering *TLI = nullptr;
61 
62   public:
63     static char ID; // Pass identification, replacement for typeid
64 
65     AtomicExpand() : FunctionPass(ID) {
66       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
67     }
68 
69     bool runOnFunction(Function &F) override;
70 
71   private:
72     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
73     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
74     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
75     bool tryExpandAtomicLoad(LoadInst *LI);
76     bool expandAtomicLoadToLL(LoadInst *LI);
77     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
78     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
79     bool expandAtomicStore(StoreInst *SI);
80     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
81     AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
82     Value *
83     insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
84                       Align AddrAlign, AtomicOrdering MemOpOrder,
85                       function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
86     void expandAtomicOpToLLSC(
87         Instruction *I, Type *ResultTy, Value *Addr, Align AddrAlign,
88         AtomicOrdering MemOpOrder,
89         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
90     void expandPartwordAtomicRMW(
91         AtomicRMWInst *I,
92         TargetLoweringBase::AtomicExpansionKind ExpansionKind);
93     AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
94     bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
95     void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
96     void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
97 
98     AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
99     static Value *insertRMWCmpXchgLoop(
100         IRBuilder<> &Builder, Type *ResultType, Value *Addr, Align AddrAlign,
101         AtomicOrdering MemOpOrder, SyncScope::ID SSID,
102         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
103         CreateCmpXchgInstFun CreateCmpXchg);
104     bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
105 
106     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
107     bool isIdempotentRMW(AtomicRMWInst *RMWI);
108     bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
109 
110     bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
111                                  Value *PointerOperand, Value *ValueOperand,
112                                  Value *CASExpected, AtomicOrdering Ordering,
113                                  AtomicOrdering Ordering2,
114                                  ArrayRef<RTLIB::Libcall> Libcalls);
115     void expandAtomicLoadToLibcall(LoadInst *LI);
116     void expandAtomicStoreToLibcall(StoreInst *LI);
117     void expandAtomicRMWToLibcall(AtomicRMWInst *I);
118     void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
119 
120     friend bool
121     llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
122                                    CreateCmpXchgInstFun CreateCmpXchg);
123   };
124 
125 } // end anonymous namespace
126 
127 char AtomicExpand::ID = 0;
128 
129 char &llvm::AtomicExpandID = AtomicExpand::ID;
130 
131 INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions",
132                 false, false)
133 
134 FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
135 
136 // Helper functions to retrieve the size of atomic instructions.
137 static unsigned getAtomicOpSize(LoadInst *LI) {
138   const DataLayout &DL = LI->getModule()->getDataLayout();
139   return DL.getTypeStoreSize(LI->getType());
140 }
141 
142 static unsigned getAtomicOpSize(StoreInst *SI) {
143   const DataLayout &DL = SI->getModule()->getDataLayout();
144   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
145 }
146 
147 static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
148   const DataLayout &DL = RMWI->getModule()->getDataLayout();
149   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
150 }
151 
152 static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
153   const DataLayout &DL = CASI->getModule()->getDataLayout();
154   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
155 }
156 
157 // Determine if a particular atomic operation has a supported size,
158 // and is of appropriate alignment, to be passed through for target
159 // lowering. (Versus turning into a __atomic libcall)
160 template <typename Inst>
161 static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
162   unsigned Size = getAtomicOpSize(I);
163   Align Alignment = I->getAlign();
164   return Alignment >= Size &&
165          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
166 }
167 
168 bool AtomicExpand::runOnFunction(Function &F) {
169   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
170   if (!TPC)
171     return false;
172 
173   auto &TM = TPC->getTM<TargetMachine>();
174   if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
175     return false;
176   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
177 
178   SmallVector<Instruction *, 1> AtomicInsts;
179 
180   // Changing control-flow while iterating through it is a bad idea, so gather a
181   // list of all atomic instructions before we start.
182   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
183     Instruction *I = &*II;
184     if (I->isAtomic() && !isa<FenceInst>(I))
185       AtomicInsts.push_back(I);
186   }
187 
188   bool MadeChange = false;
189   for (auto I : AtomicInsts) {
190     auto LI = dyn_cast<LoadInst>(I);
191     auto SI = dyn_cast<StoreInst>(I);
192     auto RMWI = dyn_cast<AtomicRMWInst>(I);
193     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
194     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
195 
196     // If the Size/Alignment is not supported, replace with a libcall.
197     if (LI) {
198       if (!atomicSizeSupported(TLI, LI)) {
199         expandAtomicLoadToLibcall(LI);
200         MadeChange = true;
201         continue;
202       }
203     } else if (SI) {
204       if (!atomicSizeSupported(TLI, SI)) {
205         expandAtomicStoreToLibcall(SI);
206         MadeChange = true;
207         continue;
208       }
209     } else if (RMWI) {
210       if (!atomicSizeSupported(TLI, RMWI)) {
211         expandAtomicRMWToLibcall(RMWI);
212         MadeChange = true;
213         continue;
214       }
215     } else if (CASI) {
216       if (!atomicSizeSupported(TLI, CASI)) {
217         expandAtomicCASToLibcall(CASI);
218         MadeChange = true;
219         continue;
220       }
221     }
222 
223     if (TLI->shouldInsertFencesForAtomic(I)) {
224       auto FenceOrdering = AtomicOrdering::Monotonic;
225       if (LI && isAcquireOrStronger(LI->getOrdering())) {
226         FenceOrdering = LI->getOrdering();
227         LI->setOrdering(AtomicOrdering::Monotonic);
228       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
229         FenceOrdering = SI->getOrdering();
230         SI->setOrdering(AtomicOrdering::Monotonic);
231       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
232                           isAcquireOrStronger(RMWI->getOrdering()))) {
233         FenceOrdering = RMWI->getOrdering();
234         RMWI->setOrdering(AtomicOrdering::Monotonic);
235       } else if (CASI &&
236                  TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
237                      TargetLoweringBase::AtomicExpansionKind::None &&
238                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
239                   isAcquireOrStronger(CASI->getSuccessOrdering()))) {
240         // If a compare and swap is lowered to LL/SC, we can do smarter fence
241         // insertion, with a stronger one on the success path than on the
242         // failure path. As a result, fence insertion is directly done by
243         // expandAtomicCmpXchg in that case.
244         FenceOrdering = CASI->getSuccessOrdering();
245         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
246         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
247       }
248 
249       if (FenceOrdering != AtomicOrdering::Monotonic) {
250         MadeChange |= bracketInstWithFences(I, FenceOrdering);
251       }
252     }
253 
254     if (LI) {
255       if (LI->getType()->isFloatingPointTy()) {
256         // TODO: add a TLI hook to control this so that each target can
257         // convert to lowering the original type one at a time.
258         LI = convertAtomicLoadToIntegerType(LI);
259         assert(LI->getType()->isIntegerTy() && "invariant broken");
260         MadeChange = true;
261       }
262 
263       MadeChange |= tryExpandAtomicLoad(LI);
264     } else if (SI) {
265       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
266         // TODO: add a TLI hook to control this so that each target can
267         // convert to lowering the original type one at a time.
268         SI = convertAtomicStoreToIntegerType(SI);
269         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
270                "invariant broken");
271         MadeChange = true;
272       }
273 
274       if (TLI->shouldExpandAtomicStoreInIR(SI))
275         MadeChange |= expandAtomicStore(SI);
276     } else if (RMWI) {
277       // There are two different ways of expanding RMW instructions:
278       // - into a load if it is idempotent
279       // - into a Cmpxchg/LL-SC loop otherwise
280       // we try them in that order.
281 
282       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
283         MadeChange = true;
284       } else {
285         AtomicRMWInst::BinOp Op = RMWI->getOperation();
286         if (Op == AtomicRMWInst::Xchg &&
287             RMWI->getValOperand()->getType()->isFloatingPointTy()) {
288           // TODO: add a TLI hook to control this so that each target can
289           // convert to lowering the original type one at a time.
290           RMWI = convertAtomicXchgToIntegerType(RMWI);
291           assert(RMWI->getValOperand()->getType()->isIntegerTy() &&
292                  "invariant broken");
293           MadeChange = true;
294         }
295         unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
296         unsigned ValueSize = getAtomicOpSize(RMWI);
297         if (ValueSize < MinCASSize &&
298             (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
299              Op == AtomicRMWInst::And)) {
300           RMWI = widenPartwordAtomicRMW(RMWI);
301           MadeChange = true;
302         }
303 
304         MadeChange |= tryExpandAtomicRMW(RMWI);
305       }
306     } else if (CASI) {
307       // TODO: when we're ready to make the change at the IR level, we can
308       // extend convertCmpXchgToInteger for floating point too.
309       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
310              "unimplemented - floating point not legal at IR level");
311       if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
312         // TODO: add a TLI hook to control this so that each target can
313         // convert to lowering the original type one at a time.
314         CASI = convertCmpXchgToIntegerType(CASI);
315         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
316                "invariant broken");
317         MadeChange = true;
318       }
319 
320       MadeChange |= tryExpandAtomicCmpXchg(CASI);
321     }
322   }
323   return MadeChange;
324 }
325 
326 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
327   IRBuilder<> Builder(I);
328 
329   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
330 
331   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
332   // We have a guard here because not every atomic operation generates a
333   // trailing fence.
334   if (TrailingFence)
335     TrailingFence->moveAfter(I);
336 
337   return (LeadingFence || TrailingFence);
338 }
339 
340 /// Get the iX type with the same bitwidth as T.
341 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
342                                                        const DataLayout &DL) {
343   EVT VT = TLI->getMemValueType(DL, T);
344   unsigned BitWidth = VT.getStoreSizeInBits();
345   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
346   return IntegerType::get(T->getContext(), BitWidth);
347 }
348 
349 /// Convert an atomic load of a non-integral type to an integer load of the
350 /// equivalent bitwidth.  See the function comment on
351 /// convertAtomicStoreToIntegerType for background.
352 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
353   auto *M = LI->getModule();
354   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
355                                             M->getDataLayout());
356 
357   IRBuilder<> Builder(LI);
358 
359   Value *Addr = LI->getPointerOperand();
360   Type *PT = PointerType::get(NewTy,
361                               Addr->getType()->getPointerAddressSpace());
362   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
363 
364   auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
365   NewLI->setAlignment(LI->getAlign());
366   NewLI->setVolatile(LI->isVolatile());
367   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
368   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
369 
370   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
371   LI->replaceAllUsesWith(NewVal);
372   LI->eraseFromParent();
373   return NewLI;
374 }
375 
376 AtomicRMWInst *
377 AtomicExpand::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
378   auto *M = RMWI->getModule();
379   Type *NewTy =
380       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
381 
382   IRBuilder<> Builder(RMWI);
383 
384   Value *Addr = RMWI->getPointerOperand();
385   Value *Val = RMWI->getValOperand();
386   Type *PT = PointerType::get(NewTy, RMWI->getPointerAddressSpace());
387   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
388   Value *NewVal = Builder.CreateBitCast(Val, NewTy);
389 
390   auto *NewRMWI =
391       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, NewAddr, NewVal,
392                               RMWI->getAlign(), RMWI->getOrdering());
393   NewRMWI->setVolatile(RMWI->isVolatile());
394   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
395 
396   Value *NewRVal = Builder.CreateBitCast(NewRMWI, RMWI->getType());
397   RMWI->replaceAllUsesWith(NewRVal);
398   RMWI->eraseFromParent();
399   return NewRMWI;
400 }
401 
402 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
403   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
404   case TargetLoweringBase::AtomicExpansionKind::None:
405     return false;
406   case TargetLoweringBase::AtomicExpansionKind::LLSC:
407     expandAtomicOpToLLSC(
408         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
409         LI->getOrdering(),
410         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
411     return true;
412   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
413     return expandAtomicLoadToLL(LI);
414   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
415     return expandAtomicLoadToCmpXchg(LI);
416   default:
417     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
418   }
419 }
420 
421 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
422   IRBuilder<> Builder(LI);
423 
424   // On some architectures, load-linked instructions are atomic for larger
425   // sizes than normal loads. For example, the only 64-bit load guaranteed
426   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
427   Value *Val =
428       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
429   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
430 
431   LI->replaceAllUsesWith(Val);
432   LI->eraseFromParent();
433 
434   return true;
435 }
436 
437 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
438   IRBuilder<> Builder(LI);
439   AtomicOrdering Order = LI->getOrdering();
440   if (Order == AtomicOrdering::Unordered)
441     Order = AtomicOrdering::Monotonic;
442 
443   Value *Addr = LI->getPointerOperand();
444   Type *Ty = LI->getType();
445   Constant *DummyVal = Constant::getNullValue(Ty);
446 
447   Value *Pair = Builder.CreateAtomicCmpXchg(
448       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
449       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
450   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
451 
452   LI->replaceAllUsesWith(Loaded);
453   LI->eraseFromParent();
454 
455   return true;
456 }
457 
458 /// Convert an atomic store of a non-integral type to an integer store of the
459 /// equivalent bitwidth.  We used to not support floating point or vector
460 /// atomics in the IR at all.  The backends learned to deal with the bitcast
461 /// idiom because that was the only way of expressing the notion of a atomic
462 /// float or vector store.  The long term plan is to teach each backend to
463 /// instruction select from the original atomic store, but as a migration
464 /// mechanism, we convert back to the old format which the backends understand.
465 /// Each backend will need individual work to recognize the new format.
466 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
467   IRBuilder<> Builder(SI);
468   auto *M = SI->getModule();
469   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
470                                             M->getDataLayout());
471   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
472 
473   Value *Addr = SI->getPointerOperand();
474   Type *PT = PointerType::get(NewTy,
475                               Addr->getType()->getPointerAddressSpace());
476   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
477 
478   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
479   NewSI->setAlignment(SI->getAlign());
480   NewSI->setVolatile(SI->isVolatile());
481   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
482   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
483   SI->eraseFromParent();
484   return NewSI;
485 }
486 
487 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
488   // This function is only called on atomic stores that are too large to be
489   // atomic if implemented as a native store. So we replace them by an
490   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
491   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
492   // It is the responsibility of the target to only signal expansion via
493   // shouldExpandAtomicRMW in cases where this is required and possible.
494   IRBuilder<> Builder(SI);
495   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
496       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
497       SI->getAlign(), SI->getOrdering());
498   SI->eraseFromParent();
499 
500   // Now we have an appropriate swap instruction, lower it as usual.
501   return tryExpandAtomicRMW(AI);
502 }
503 
504 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
505                                  Value *Loaded, Value *NewVal, Align AddrAlign,
506                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
507                                  Value *&Success, Value *&NewLoaded) {
508   Type *OrigTy = NewVal->getType();
509 
510   // This code can go away when cmpxchg supports FP types.
511   bool NeedBitcast = OrigTy->isFloatingPointTy();
512   if (NeedBitcast) {
513     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
514     unsigned AS = Addr->getType()->getPointerAddressSpace();
515     Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
516     NewVal = Builder.CreateBitCast(NewVal, IntTy);
517     Loaded = Builder.CreateBitCast(Loaded, IntTy);
518   }
519 
520   Value *Pair = Builder.CreateAtomicCmpXchg(
521       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
522       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
523   Success = Builder.CreateExtractValue(Pair, 1, "success");
524   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
525 
526   if (NeedBitcast)
527     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
528 }
529 
530 /// Emit IR to implement the given atomicrmw operation on values in registers,
531 /// returning the new value.
532 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
533                               Value *Loaded, Value *Inc) {
534   Value *NewVal;
535   switch (Op) {
536   case AtomicRMWInst::Xchg:
537     return Inc;
538   case AtomicRMWInst::Add:
539     return Builder.CreateAdd(Loaded, Inc, "new");
540   case AtomicRMWInst::Sub:
541     return Builder.CreateSub(Loaded, Inc, "new");
542   case AtomicRMWInst::And:
543     return Builder.CreateAnd(Loaded, Inc, "new");
544   case AtomicRMWInst::Nand:
545     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
546   case AtomicRMWInst::Or:
547     return Builder.CreateOr(Loaded, Inc, "new");
548   case AtomicRMWInst::Xor:
549     return Builder.CreateXor(Loaded, Inc, "new");
550   case AtomicRMWInst::Max:
551     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
552     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
553   case AtomicRMWInst::Min:
554     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
555     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
556   case AtomicRMWInst::UMax:
557     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
558     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
559   case AtomicRMWInst::UMin:
560     NewVal = Builder.CreateICmpULE(Loaded, Inc);
561     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
562   case AtomicRMWInst::FAdd:
563     return Builder.CreateFAdd(Loaded, Inc, "new");
564   case AtomicRMWInst::FSub:
565     return Builder.CreateFSub(Loaded, Inc, "new");
566   default:
567     llvm_unreachable("Unknown atomic op");
568   }
569 }
570 
571 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
572   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
573   case TargetLoweringBase::AtomicExpansionKind::None:
574     return false;
575   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
576     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
577     unsigned ValueSize = getAtomicOpSize(AI);
578     if (ValueSize < MinCASSize) {
579       expandPartwordAtomicRMW(AI,
580                               TargetLoweringBase::AtomicExpansionKind::LLSC);
581     } else {
582       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
583         return performAtomicOp(AI->getOperation(), Builder, Loaded,
584                                AI->getValOperand());
585       };
586       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
587                            AI->getAlign(), AI->getOrdering(), PerformOp);
588     }
589     return true;
590   }
591   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
592     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
593     unsigned ValueSize = getAtomicOpSize(AI);
594     if (ValueSize < MinCASSize) {
595       // TODO: Handle atomicrmw fadd/fsub
596       if (AI->getType()->isFloatingPointTy())
597         return false;
598 
599       expandPartwordAtomicRMW(AI,
600                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
601     } else {
602       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
603     }
604     return true;
605   }
606   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
607     expandAtomicRMWToMaskedIntrinsic(AI);
608     return true;
609   }
610   default:
611     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
612   }
613 }
614 
615 namespace {
616 
617 struct PartwordMaskValues {
618   // These three fields are guaranteed to be set by createMaskInstrs.
619   Type *WordType = nullptr;
620   Type *ValueType = nullptr;
621   Value *AlignedAddr = nullptr;
622   Align AlignedAddrAlignment;
623   // The remaining fields can be null.
624   Value *ShiftAmt = nullptr;
625   Value *Mask = nullptr;
626   Value *Inv_Mask = nullptr;
627 };
628 
629 LLVM_ATTRIBUTE_UNUSED
630 raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
631   auto PrintObj = [&O](auto *V) {
632     if (V)
633       O << *V;
634     else
635       O << "nullptr";
636     O << '\n';
637   };
638   O << "PartwordMaskValues {\n";
639   O << "  WordType: ";
640   PrintObj(PMV.WordType);
641   O << "  ValueType: ";
642   PrintObj(PMV.ValueType);
643   O << "  AlignedAddr: ";
644   PrintObj(PMV.AlignedAddr);
645   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
646   O << "  ShiftAmt: ";
647   PrintObj(PMV.ShiftAmt);
648   O << "  Mask: ";
649   PrintObj(PMV.Mask);
650   O << "  Inv_Mask: ";
651   PrintObj(PMV.Inv_Mask);
652   O << "}\n";
653   return O;
654 }
655 
656 } // end anonymous namespace
657 
658 /// This is a helper function which builds instructions to provide
659 /// values necessary for partword atomic operations. It takes an
660 /// incoming address, Addr, and ValueType, and constructs the address,
661 /// shift-amounts and masks needed to work with a larger value of size
662 /// WordSize.
663 ///
664 /// AlignedAddr: Addr rounded down to a multiple of WordSize
665 ///
666 /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
667 ///           from AlignAddr for it to have the same value as if
668 ///           ValueType was loaded from Addr.
669 ///
670 /// Mask: Value to mask with the value loaded from AlignAddr to
671 ///       include only the part that would've been loaded from Addr.
672 ///
673 /// Inv_Mask: The inverse of Mask.
674 static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
675                                            Type *ValueType, Value *Addr,
676                                            Align AddrAlign,
677                                            unsigned MinWordSize) {
678   PartwordMaskValues PMV;
679 
680   Module *M = I->getModule();
681   LLVMContext &Ctx = M->getContext();
682   const DataLayout &DL = M->getDataLayout();
683   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
684 
685   PMV.ValueType = ValueType;
686   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
687                                          : ValueType;
688   if (PMV.ValueType == PMV.WordType) {
689     PMV.AlignedAddr = Addr;
690     PMV.AlignedAddrAlignment = AddrAlign;
691     return PMV;
692   }
693 
694   assert(ValueSize < MinWordSize);
695 
696   Type *WordPtrType =
697       PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
698 
699   // TODO: we could skip some of this if AddrAlign >= MinWordSize.
700   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
701   PMV.AlignedAddr = Builder.CreateIntToPtr(
702       Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
703       "AlignedAddr");
704   PMV.AlignedAddrAlignment = Align(MinWordSize);
705 
706   Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
707   if (DL.isLittleEndian()) {
708     // turn bytes into bits
709     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
710   } else {
711     // turn bytes into bits, and count from the other side.
712     PMV.ShiftAmt = Builder.CreateShl(
713         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
714   }
715 
716   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
717   PMV.Mask = Builder.CreateShl(
718       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
719       "Mask");
720   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
721   return PMV;
722 }
723 
724 static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
725                                  const PartwordMaskValues &PMV) {
726   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
727   if (PMV.WordType == PMV.ValueType)
728     return WideWord;
729 
730   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
731   Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
732   return Trunc;
733 }
734 
735 static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
736                                 Value *Updated, const PartwordMaskValues &PMV) {
737   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
738   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
739   if (PMV.WordType == PMV.ValueType)
740     return Updated;
741 
742   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
743   Value *Shift =
744       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
745   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
746   Value *Or = Builder.CreateOr(And, Shift, "inserted");
747   return Or;
748 }
749 
750 /// Emit IR to implement a masked version of a given atomicrmw
751 /// operation. (That is, only the bits under the Mask should be
752 /// affected by the operation)
753 static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
754                                     IRBuilder<> &Builder, Value *Loaded,
755                                     Value *Shifted_Inc, Value *Inc,
756                                     const PartwordMaskValues &PMV) {
757   // TODO: update to use
758   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
759   // to merge bits from two values without requiring PMV.Inv_Mask.
760   switch (Op) {
761   case AtomicRMWInst::Xchg: {
762     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
763     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
764     return FinalVal;
765   }
766   case AtomicRMWInst::Or:
767   case AtomicRMWInst::Xor:
768   case AtomicRMWInst::And:
769     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
770   case AtomicRMWInst::Add:
771   case AtomicRMWInst::Sub:
772   case AtomicRMWInst::Nand: {
773     // The other arithmetic ops need to be masked into place.
774     Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
775     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
776     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
777     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
778     return FinalVal;
779   }
780   case AtomicRMWInst::Max:
781   case AtomicRMWInst::Min:
782   case AtomicRMWInst::UMax:
783   case AtomicRMWInst::UMin: {
784     // Finally, comparison ops will operate on the full value, so
785     // truncate down to the original size, and expand out again after
786     // doing the operation.
787     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
788     Value *NewVal = performAtomicOp(Op, Builder, Loaded_Extract, Inc);
789     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
790     return FinalVal;
791   }
792   default:
793     llvm_unreachable("Unknown atomic op");
794   }
795 }
796 
797 /// Expand a sub-word atomicrmw operation into an appropriate
798 /// word-sized operation.
799 ///
800 /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
801 /// way as a typical atomicrmw expansion. The only difference here is
802 /// that the operation inside of the loop may operate upon only a
803 /// part of the value.
804 void AtomicExpand::expandPartwordAtomicRMW(
805     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
806   AtomicOrdering MemOpOrder = AI->getOrdering();
807   SyncScope::ID SSID = AI->getSyncScopeID();
808 
809   IRBuilder<> Builder(AI);
810 
811   PartwordMaskValues PMV =
812       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
813                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
814 
815   Value *ValOperand_Shifted =
816       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
817                         PMV.ShiftAmt, "ValOperand_Shifted");
818 
819   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
820     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
821                                  ValOperand_Shifted, AI->getValOperand(), PMV);
822   };
823 
824   Value *OldResult;
825   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
826     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
827                                      PMV.AlignedAddrAlignment, MemOpOrder,
828                                      SSID, PerformPartwordOp,
829                                      createCmpXchgInstFun);
830   } else {
831     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
832     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
833                                   PMV.AlignedAddrAlignment, MemOpOrder,
834                                   PerformPartwordOp);
835   }
836 
837   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
838   AI->replaceAllUsesWith(FinalOldResult);
839   AI->eraseFromParent();
840 }
841 
842 // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
843 AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
844   IRBuilder<> Builder(AI);
845   AtomicRMWInst::BinOp Op = AI->getOperation();
846 
847   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
848           Op == AtomicRMWInst::And) &&
849          "Unable to widen operation");
850 
851   PartwordMaskValues PMV =
852       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
853                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
854 
855   Value *ValOperand_Shifted =
856       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
857                         PMV.ShiftAmt, "ValOperand_Shifted");
858 
859   Value *NewOperand;
860 
861   if (Op == AtomicRMWInst::And)
862     NewOperand =
863         Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
864   else
865     NewOperand = ValOperand_Shifted;
866 
867   AtomicRMWInst *NewAI =
868       Builder.CreateAtomicRMW(Op, PMV.AlignedAddr, NewOperand,
869                               PMV.AlignedAddrAlignment, AI->getOrdering());
870 
871   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
872   AI->replaceAllUsesWith(FinalOldResult);
873   AI->eraseFromParent();
874   return NewAI;
875 }
876 
877 bool AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
878   // The basic idea here is that we're expanding a cmpxchg of a
879   // smaller memory size up to a word-sized cmpxchg. To do this, we
880   // need to add a retry-loop for strong cmpxchg, so that
881   // modifications to other parts of the word don't cause a spurious
882   // failure.
883 
884   // This generates code like the following:
885   //     [[Setup mask values PMV.*]]
886   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
887   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
888   //     %InitLoaded = load i32* %addr
889   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
890   //     br partword.cmpxchg.loop
891   // partword.cmpxchg.loop:
892   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
893   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
894   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
895   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
896   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
897   //        i32 %FullWord_NewVal success_ordering failure_ordering
898   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
899   //     %Success = extractvalue { i32, i1 } %NewCI, 1
900   //     br i1 %Success, label %partword.cmpxchg.end,
901   //        label %partword.cmpxchg.failure
902   // partword.cmpxchg.failure:
903   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
904   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
905   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
906   //         label %partword.cmpxchg.end
907   // partword.cmpxchg.end:
908   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
909   //    %FinalOldVal = trunc i32 %tmp1 to i8
910   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
911   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
912 
913   Value *Addr = CI->getPointerOperand();
914   Value *Cmp = CI->getCompareOperand();
915   Value *NewVal = CI->getNewValOperand();
916 
917   BasicBlock *BB = CI->getParent();
918   Function *F = BB->getParent();
919   IRBuilder<> Builder(CI);
920   LLVMContext &Ctx = Builder.getContext();
921 
922   BasicBlock *EndBB =
923       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
924   auto FailureBB =
925       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
926   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
927 
928   // The split call above "helpfully" added a branch at the end of BB
929   // (to the wrong place).
930   std::prev(BB->end())->eraseFromParent();
931   Builder.SetInsertPoint(BB);
932 
933   PartwordMaskValues PMV =
934       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
935                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
936 
937   // Shift the incoming values over, into the right location in the word.
938   Value *NewVal_Shifted =
939       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
940   Value *Cmp_Shifted =
941       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
942 
943   // Load the entire current word, and mask into place the expected and new
944   // values
945   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
946   InitLoaded->setVolatile(CI->isVolatile());
947   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
948   Builder.CreateBr(LoopBB);
949 
950   // partword.cmpxchg.loop:
951   Builder.SetInsertPoint(LoopBB);
952   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
953   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
954 
955   // Mask/Or the expected and new values into place in the loaded word.
956   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
957   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
958   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
959       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
960       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
961   NewCI->setVolatile(CI->isVolatile());
962   // When we're building a strong cmpxchg, we need a loop, so you
963   // might think we could use a weak cmpxchg inside. But, using strong
964   // allows the below comparison for ShouldContinue, and we're
965   // expecting the underlying cmpxchg to be a machine instruction,
966   // which is strong anyways.
967   NewCI->setWeak(CI->isWeak());
968 
969   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
970   Value *Success = Builder.CreateExtractValue(NewCI, 1);
971 
972   if (CI->isWeak())
973     Builder.CreateBr(EndBB);
974   else
975     Builder.CreateCondBr(Success, EndBB, FailureBB);
976 
977   // partword.cmpxchg.failure:
978   Builder.SetInsertPoint(FailureBB);
979   // Upon failure, verify that the masked-out part of the loaded value
980   // has been modified.  If it didn't, abort the cmpxchg, since the
981   // masked-in part must've.
982   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
983   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
984   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
985 
986   // Add the second value to the phi from above
987   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
988 
989   // partword.cmpxchg.end:
990   Builder.SetInsertPoint(CI);
991 
992   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
993   Value *Res = UndefValue::get(CI->getType());
994   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
995   Res = Builder.CreateInsertValue(Res, Success, 1);
996 
997   CI->replaceAllUsesWith(Res);
998   CI->eraseFromParent();
999   return true;
1000 }
1001 
1002 void AtomicExpand::expandAtomicOpToLLSC(
1003     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
1004     AtomicOrdering MemOpOrder,
1005     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1006   IRBuilder<> Builder(I);
1007   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
1008                                     MemOpOrder, PerformOp);
1009 
1010   I->replaceAllUsesWith(Loaded);
1011   I->eraseFromParent();
1012 }
1013 
1014 void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
1015   IRBuilder<> Builder(AI);
1016 
1017   PartwordMaskValues PMV =
1018       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1019                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1020 
1021   // The value operand must be sign-extended for signed min/max so that the
1022   // target's signed comparison instructions can be used. Otherwise, just
1023   // zero-ext.
1024   Instruction::CastOps CastOp = Instruction::ZExt;
1025   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
1026   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
1027     CastOp = Instruction::SExt;
1028 
1029   Value *ValOperand_Shifted = Builder.CreateShl(
1030       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
1031       PMV.ShiftAmt, "ValOperand_Shifted");
1032   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
1033       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
1034       AI->getOrdering());
1035   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
1036   AI->replaceAllUsesWith(FinalOldResult);
1037   AI->eraseFromParent();
1038 }
1039 
1040 void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
1041   IRBuilder<> Builder(CI);
1042 
1043   PartwordMaskValues PMV = createMaskInstrs(
1044       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1045       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1046 
1047   Value *CmpVal_Shifted = Builder.CreateShl(
1048       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
1049       "CmpVal_Shifted");
1050   Value *NewVal_Shifted = Builder.CreateShl(
1051       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
1052       "NewVal_Shifted");
1053   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
1054       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
1055       CI->getSuccessOrdering());
1056   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1057   Value *Res = UndefValue::get(CI->getType());
1058   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1059   Value *Success = Builder.CreateICmpEQ(
1060       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
1061   Res = Builder.CreateInsertValue(Res, Success, 1);
1062 
1063   CI->replaceAllUsesWith(Res);
1064   CI->eraseFromParent();
1065 }
1066 
1067 Value *AtomicExpand::insertRMWLLSCLoop(
1068     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1069     AtomicOrdering MemOpOrder,
1070     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1071   LLVMContext &Ctx = Builder.getContext();
1072   BasicBlock *BB = Builder.GetInsertBlock();
1073   Function *F = BB->getParent();
1074 
1075   assert(AddrAlign >=
1076              F->getParent()->getDataLayout().getTypeStoreSize(ResultTy) &&
1077          "Expected at least natural alignment at this point.");
1078 
1079   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1080   //
1081   // The standard expansion we produce is:
1082   //     [...]
1083   // atomicrmw.start:
1084   //     %loaded = @load.linked(%addr)
1085   //     %new = some_op iN %loaded, %incr
1086   //     %stored = @store_conditional(%new, %addr)
1087   //     %try_again = icmp i32 ne %stored, 0
1088   //     br i1 %try_again, label %loop, label %atomicrmw.end
1089   // atomicrmw.end:
1090   //     [...]
1091   BasicBlock *ExitBB =
1092       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1093   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1094 
1095   // The split call above "helpfully" added a branch at the end of BB (to the
1096   // wrong place).
1097   std::prev(BB->end())->eraseFromParent();
1098   Builder.SetInsertPoint(BB);
1099   Builder.CreateBr(LoopBB);
1100 
1101   // Start the main loop block now that we've taken care of the preliminaries.
1102   Builder.SetInsertPoint(LoopBB);
1103   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1104 
1105   Value *NewVal = PerformOp(Builder, Loaded);
1106 
1107   Value *StoreSuccess =
1108       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
1109   Value *TryAgain = Builder.CreateICmpNE(
1110       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1111   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1112 
1113   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1114   return Loaded;
1115 }
1116 
1117 /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
1118 /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
1119 /// IR.  As a migration step, we convert back to what use to be the standard
1120 /// way to represent a pointer cmpxchg so that we can update backends one by
1121 /// one.
1122 AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
1123   auto *M = CI->getModule();
1124   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
1125                                             M->getDataLayout());
1126 
1127   IRBuilder<> Builder(CI);
1128 
1129   Value *Addr = CI->getPointerOperand();
1130   Type *PT = PointerType::get(NewTy,
1131                               Addr->getType()->getPointerAddressSpace());
1132   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1133 
1134   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
1135   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
1136 
1137   auto *NewCI = Builder.CreateAtomicCmpXchg(
1138       NewAddr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
1139       CI->getFailureOrdering(), CI->getSyncScopeID());
1140   NewCI->setVolatile(CI->isVolatile());
1141   NewCI->setWeak(CI->isWeak());
1142   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
1143 
1144   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1145   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
1146 
1147   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
1148 
1149   Value *Res = UndefValue::get(CI->getType());
1150   Res = Builder.CreateInsertValue(Res, OldVal, 0);
1151   Res = Builder.CreateInsertValue(Res, Succ, 1);
1152 
1153   CI->replaceAllUsesWith(Res);
1154   CI->eraseFromParent();
1155   return NewCI;
1156 }
1157 
1158 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1159   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1160   AtomicOrdering FailureOrder = CI->getFailureOrdering();
1161   Value *Addr = CI->getPointerOperand();
1162   BasicBlock *BB = CI->getParent();
1163   Function *F = BB->getParent();
1164   LLVMContext &Ctx = F->getContext();
1165   // If shouldInsertFencesForAtomic() returns true, then the target does not
1166   // want to deal with memory orders, and emitLeading/TrailingFence should take
1167   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1168   // should preserve the ordering.
1169   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
1170   AtomicOrdering MemOpOrder =
1171       ShouldInsertFencesForAtomic ? AtomicOrdering::Monotonic : SuccessOrder;
1172 
1173   // In implementations which use a barrier to achieve release semantics, we can
1174   // delay emitting this barrier until we know a store is actually going to be
1175   // attempted. The cost of this delay is that we need 2 copies of the block
1176   // emitting the load-linked, affecting code size.
1177   //
1178   // Ideally, this logic would be unconditional except for the minsize check
1179   // since in other cases the extra blocks naturally collapse down to the
1180   // minimal loop. Unfortunately, this puts too much stress on later
1181   // optimisations so we avoid emitting the extra logic in those cases too.
1182   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
1183                            SuccessOrder != AtomicOrdering::Monotonic &&
1184                            SuccessOrder != AtomicOrdering::Acquire &&
1185                            !F->hasMinSize();
1186 
1187   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1188   // do it even on minsize.
1189   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
1190 
1191   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1192   //
1193   // The full expansion we produce is:
1194   //     [...]
1195   // %aligned.addr = ...
1196   // cmpxchg.start:
1197   //     %unreleasedload = @load.linked(%aligned.addr)
1198   //     %unreleasedload.extract = extract value from %unreleasedload
1199   //     %should_store = icmp eq %unreleasedload.extract, %desired
1200   //     br i1 %should_store, label %cmpxchg.releasingstore,
1201   //                          label %cmpxchg.nostore
1202   // cmpxchg.releasingstore:
1203   //     fence?
1204   //     br label cmpxchg.trystore
1205   // cmpxchg.trystore:
1206   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
1207   //                            [%releasedload, %cmpxchg.releasedload]
1208   //     %updated.new = insert %new into %loaded.trystore
1209   //     %stored = @store_conditional(%updated.new, %aligned.addr)
1210   //     %success = icmp eq i32 %stored, 0
1211   //     br i1 %success, label %cmpxchg.success,
1212   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1213   // cmpxchg.releasedload:
1214   //     %releasedload = @load.linked(%aligned.addr)
1215   //     %releasedload.extract = extract value from %releasedload
1216   //     %should_store = icmp eq %releasedload.extract, %desired
1217   //     br i1 %should_store, label %cmpxchg.trystore,
1218   //                          label %cmpxchg.failure
1219   // cmpxchg.success:
1220   //     fence?
1221   //     br label %cmpxchg.end
1222   // cmpxchg.nostore:
1223   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1224   //                           [%releasedload,
1225   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
1226   //     @load_linked_fail_balance()?
1227   //     br label %cmpxchg.failure
1228   // cmpxchg.failure:
1229   //     fence?
1230   //     br label %cmpxchg.end
1231   // cmpxchg.end:
1232   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1233   //                        [%loaded.trystore, %cmpxchg.trystore]
1234   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1235   //     %loaded = extract value from %loaded.exit
1236   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1237   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1238   //     [...]
1239   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1240   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1241   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1242   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1243   auto ReleasedLoadBB =
1244       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1245   auto TryStoreBB =
1246       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1247   auto ReleasingStoreBB =
1248       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1249   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
1250 
1251   // This grabs the DebugLoc from CI
1252   IRBuilder<> Builder(CI);
1253 
1254   // The split call above "helpfully" added a branch at the end of BB (to the
1255   // wrong place), but we might want a fence too. It's easiest to just remove
1256   // the branch entirely.
1257   std::prev(BB->end())->eraseFromParent();
1258   Builder.SetInsertPoint(BB);
1259   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
1260     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1261 
1262   PartwordMaskValues PMV =
1263       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1264                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1265   Builder.CreateBr(StartBB);
1266 
1267   // Start the main loop block now that we've taken care of the preliminaries.
1268   Builder.SetInsertPoint(StartBB);
1269   Value *UnreleasedLoad =
1270       TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1271   Value *UnreleasedLoadExtract =
1272       extractMaskedValue(Builder, UnreleasedLoad, PMV);
1273   Value *ShouldStore = Builder.CreateICmpEQ(
1274       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
1275 
1276   // If the cmpxchg doesn't actually need any ordering when it fails, we can
1277   // jump straight past that fence instruction (if it exists).
1278   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1279 
1280   Builder.SetInsertPoint(ReleasingStoreBB);
1281   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
1282     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1283   Builder.CreateBr(TryStoreBB);
1284 
1285   Builder.SetInsertPoint(TryStoreBB);
1286   PHINode *LoadedTryStore =
1287       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1288   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1289   Value *NewValueInsert =
1290       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1291   Value *StoreSuccess =
1292       TLI->emitStoreConditional(Builder, NewValueInsert, PMV.AlignedAddr,
1293                                 MemOpOrder);
1294   StoreSuccess = Builder.CreateICmpEQ(
1295       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1296   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
1297   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1298                        CI->isWeak() ? FailureBB : RetryBB);
1299 
1300   Builder.SetInsertPoint(ReleasedLoadBB);
1301   Value *SecondLoad;
1302   if (HasReleasedLoadBB) {
1303     SecondLoad = TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1304     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1305     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1306                                        CI->getCompareOperand(), "should_store");
1307 
1308     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1309     // jump straight past that fence instruction (if it exists).
1310     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1311     // Update PHI node in TryStoreBB.
1312     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
1313   } else
1314     Builder.CreateUnreachable();
1315 
1316   // Make sure later instructions don't get reordered with a fence if
1317   // necessary.
1318   Builder.SetInsertPoint(SuccessBB);
1319   if (ShouldInsertFencesForAtomic)
1320     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
1321   Builder.CreateBr(ExitBB);
1322 
1323   Builder.SetInsertPoint(NoStoreBB);
1324   PHINode *LoadedNoStore =
1325       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1326   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1327   if (HasReleasedLoadBB)
1328     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1329 
1330   // In the failing case, where we don't execute the store-conditional, the
1331   // target might want to balance out the load-linked with a dedicated
1332   // instruction (e.g., on ARM, clearing the exclusive monitor).
1333   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1334   Builder.CreateBr(FailureBB);
1335 
1336   Builder.SetInsertPoint(FailureBB);
1337   PHINode *LoadedFailure =
1338       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1339   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1340   if (CI->isWeak())
1341     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
1342   if (ShouldInsertFencesForAtomic)
1343     TLI->emitTrailingFence(Builder, CI, FailureOrder);
1344   Builder.CreateBr(ExitBB);
1345 
1346   // Finally, we have control-flow based knowledge of whether the cmpxchg
1347   // succeeded or not. We expose this to later passes by converting any
1348   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1349   // PHI.
1350   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1351   PHINode *LoadedExit =
1352       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1353   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1354   LoadedExit->addIncoming(LoadedFailure, FailureBB);
1355   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
1356   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1357   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1358 
1359   // This is the "exit value" from the cmpxchg expansion. It may be of
1360   // a type wider than the one in the cmpxchg instruction.
1361   Value *LoadedFull = LoadedExit;
1362 
1363   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1364   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
1365 
1366   // Look for any users of the cmpxchg that are just comparing the loaded value
1367   // against the desired one, and replace them with the CFG-derived version.
1368   SmallVector<ExtractValueInst *, 2> PrunedInsts;
1369   for (auto User : CI->users()) {
1370     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1371     if (!EV)
1372       continue;
1373 
1374     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1375            "weird extraction from { iN, i1 }");
1376 
1377     if (EV->getIndices()[0] == 0)
1378       EV->replaceAllUsesWith(Loaded);
1379     else
1380       EV->replaceAllUsesWith(Success);
1381 
1382     PrunedInsts.push_back(EV);
1383   }
1384 
1385   // We can remove the instructions now we're no longer iterating through them.
1386   for (auto EV : PrunedInsts)
1387     EV->eraseFromParent();
1388 
1389   if (!CI->use_empty()) {
1390     // Some use of the full struct return that we don't understand has happened,
1391     // so we've got to reconstruct it properly.
1392     Value *Res;
1393     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1394     Res = Builder.CreateInsertValue(Res, Success, 1);
1395 
1396     CI->replaceAllUsesWith(Res);
1397   }
1398 
1399   CI->eraseFromParent();
1400   return true;
1401 }
1402 
1403 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
1404   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1405   if(!C)
1406     return false;
1407 
1408   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1409   switch(Op) {
1410     case AtomicRMWInst::Add:
1411     case AtomicRMWInst::Sub:
1412     case AtomicRMWInst::Or:
1413     case AtomicRMWInst::Xor:
1414       return C->isZero();
1415     case AtomicRMWInst::And:
1416       return C->isMinusOne();
1417     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1418     default:
1419       return false;
1420   }
1421 }
1422 
1423 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
1424   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1425     tryExpandAtomicLoad(ResultingLoad);
1426     return true;
1427   }
1428   return false;
1429 }
1430 
1431 Value *AtomicExpand::insertRMWCmpXchgLoop(
1432     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1433     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
1434     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1435     CreateCmpXchgInstFun CreateCmpXchg) {
1436   LLVMContext &Ctx = Builder.getContext();
1437   BasicBlock *BB = Builder.GetInsertBlock();
1438   Function *F = BB->getParent();
1439 
1440   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1441   //
1442   // The standard expansion we produce is:
1443   //     [...]
1444   //     %init_loaded = load atomic iN* %addr
1445   //     br label %loop
1446   // loop:
1447   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1448   //     %new = some_op iN %loaded, %incr
1449   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1450   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1451   //     %success = extractvalue { iN, i1 } %pair, 1
1452   //     br i1 %success, label %atomicrmw.end, label %loop
1453   // atomicrmw.end:
1454   //     [...]
1455   BasicBlock *ExitBB =
1456       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1457   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1458 
1459   // The split call above "helpfully" added a branch at the end of BB (to the
1460   // wrong place), but we want a load. It's easiest to just remove
1461   // the branch entirely.
1462   std::prev(BB->end())->eraseFromParent();
1463   Builder.SetInsertPoint(BB);
1464   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
1465   Builder.CreateBr(LoopBB);
1466 
1467   // Start the main loop block now that we've taken care of the preliminaries.
1468   Builder.SetInsertPoint(LoopBB);
1469   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1470   Loaded->addIncoming(InitLoaded, BB);
1471 
1472   Value *NewVal = PerformOp(Builder, Loaded);
1473 
1474   Value *NewLoaded = nullptr;
1475   Value *Success = nullptr;
1476 
1477   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
1478                 MemOpOrder == AtomicOrdering::Unordered
1479                     ? AtomicOrdering::Monotonic
1480                     : MemOpOrder,
1481                 SSID, Success, NewLoaded);
1482   assert(Success && NewLoaded);
1483 
1484   Loaded->addIncoming(NewLoaded, LoopBB);
1485 
1486   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1487 
1488   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1489   return NewLoaded;
1490 }
1491 
1492 bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1493   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1494   unsigned ValueSize = getAtomicOpSize(CI);
1495 
1496   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1497   default:
1498     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1499   case TargetLoweringBase::AtomicExpansionKind::None:
1500     if (ValueSize < MinCASSize)
1501       return expandPartwordCmpXchg(CI);
1502     return false;
1503   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
1504     return expandAtomicCmpXchg(CI);
1505   }
1506   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
1507     expandAtomicCmpXchgToMaskedIntrinsic(CI);
1508     return true;
1509   }
1510 }
1511 
1512 // Note: This function is exposed externally by AtomicExpandUtils.h
1513 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1514                                     CreateCmpXchgInstFun CreateCmpXchg) {
1515   IRBuilder<> Builder(AI);
1516   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1517       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1518       AI->getOrdering(), AI->getSyncScopeID(),
1519       [&](IRBuilder<> &Builder, Value *Loaded) {
1520         return performAtomicOp(AI->getOperation(), Builder, Loaded,
1521                                AI->getValOperand());
1522       },
1523       CreateCmpXchg);
1524 
1525   AI->replaceAllUsesWith(Loaded);
1526   AI->eraseFromParent();
1527   return true;
1528 }
1529 
1530 // In order to use one of the sized library calls such as
1531 // __atomic_fetch_add_4, the alignment must be sufficient, the size
1532 // must be one of the potentially-specialized sizes, and the value
1533 // type must actually exist in C on the target (otherwise, the
1534 // function wouldn't actually be defined.)
1535 static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
1536                                   const DataLayout &DL) {
1537   // TODO: "LargestSize" is an approximation for "largest type that
1538   // you can express in C". It seems to be the case that int128 is
1539   // supported on all 64-bit platforms, otherwise only up to 64-bit
1540   // integers are supported. If we get this wrong, then we'll try to
1541   // call a sized libcall that doesn't actually exist. There should
1542   // really be some more reliable way in LLVM of determining integer
1543   // sizes which are valid in the target's C ABI...
1544   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1545   return Alignment >= Size &&
1546          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1547          Size <= LargestSize;
1548 }
1549 
1550 void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
1551   static const RTLIB::Libcall Libcalls[6] = {
1552       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1553       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1554   unsigned Size = getAtomicOpSize(I);
1555 
1556   bool expanded = expandAtomicOpToLibcall(
1557       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
1558       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1559   if (!expanded)
1560     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
1561 }
1562 
1563 void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
1564   static const RTLIB::Libcall Libcalls[6] = {
1565       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1566       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1567   unsigned Size = getAtomicOpSize(I);
1568 
1569   bool expanded = expandAtomicOpToLibcall(
1570       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1571       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1572   if (!expanded)
1573     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
1574 }
1575 
1576 void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1577   static const RTLIB::Libcall Libcalls[6] = {
1578       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1579       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1580       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1581   unsigned Size = getAtomicOpSize(I);
1582 
1583   bool expanded = expandAtomicOpToLibcall(
1584       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
1585       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1586       Libcalls);
1587   if (!expanded)
1588     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
1589 }
1590 
1591 static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1592   static const RTLIB::Libcall LibcallsXchg[6] = {
1593       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1594       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1595       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1596   static const RTLIB::Libcall LibcallsAdd[6] = {
1597       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1598       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1599       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1600   static const RTLIB::Libcall LibcallsSub[6] = {
1601       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1602       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1603       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1604   static const RTLIB::Libcall LibcallsAnd[6] = {
1605       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1606       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1607       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1608   static const RTLIB::Libcall LibcallsOr[6] = {
1609       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1610       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1611       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1612   static const RTLIB::Libcall LibcallsXor[6] = {
1613       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1614       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1615       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1616   static const RTLIB::Libcall LibcallsNand[6] = {
1617       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1618       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1619       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1620 
1621   switch (Op) {
1622   case AtomicRMWInst::BAD_BINOP:
1623     llvm_unreachable("Should not have BAD_BINOP.");
1624   case AtomicRMWInst::Xchg:
1625     return makeArrayRef(LibcallsXchg);
1626   case AtomicRMWInst::Add:
1627     return makeArrayRef(LibcallsAdd);
1628   case AtomicRMWInst::Sub:
1629     return makeArrayRef(LibcallsSub);
1630   case AtomicRMWInst::And:
1631     return makeArrayRef(LibcallsAnd);
1632   case AtomicRMWInst::Or:
1633     return makeArrayRef(LibcallsOr);
1634   case AtomicRMWInst::Xor:
1635     return makeArrayRef(LibcallsXor);
1636   case AtomicRMWInst::Nand:
1637     return makeArrayRef(LibcallsNand);
1638   case AtomicRMWInst::Max:
1639   case AtomicRMWInst::Min:
1640   case AtomicRMWInst::UMax:
1641   case AtomicRMWInst::UMin:
1642   case AtomicRMWInst::FAdd:
1643   case AtomicRMWInst::FSub:
1644     // No atomic libcalls are available for max/min/umax/umin.
1645     return {};
1646   }
1647   llvm_unreachable("Unexpected AtomicRMW operation.");
1648 }
1649 
1650 void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1651   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1652 
1653   unsigned Size = getAtomicOpSize(I);
1654 
1655   bool Success = false;
1656   if (!Libcalls.empty())
1657     Success = expandAtomicOpToLibcall(
1658         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1659         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1660 
1661   // The expansion failed: either there were no libcalls at all for
1662   // the operation (min/max), or there were only size-specialized
1663   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1664   // CAS libcall, via a CAS loop, instead.
1665   if (!Success) {
1666     expandAtomicRMWToCmpXchg(
1667         I, [this](IRBuilder<> &Builder, Value *Addr, Value *Loaded,
1668                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1669                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
1670           // Create the CAS instruction normally...
1671           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1672               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1673               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
1674           Success = Builder.CreateExtractValue(Pair, 1, "success");
1675           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1676 
1677           // ...and then expand the CAS into a libcall.
1678           expandAtomicCASToLibcall(Pair);
1679         });
1680   }
1681 }
1682 
1683 // A helper routine for the above expandAtomic*ToLibcall functions.
1684 //
1685 // 'Libcalls' contains an array of enum values for the particular
1686 // ATOMIC libcalls to be emitted. All of the other arguments besides
1687 // 'I' are extracted from the Instruction subclass by the
1688 // caller. Depending on the particular call, some will be null.
1689 bool AtomicExpand::expandAtomicOpToLibcall(
1690     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
1691     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1692     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1693   assert(Libcalls.size() == 6);
1694 
1695   LLVMContext &Ctx = I->getContext();
1696   Module *M = I->getModule();
1697   const DataLayout &DL = M->getDataLayout();
1698   IRBuilder<> Builder(I);
1699   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1700 
1701   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
1702   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1703 
1704   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
1705 
1706   // TODO: the "order" argument type is "int", not int32. So
1707   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1708   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1709   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1710   Constant *OrderingVal =
1711       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1712   Constant *Ordering2Val = nullptr;
1713   if (CASExpected) {
1714     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1715     Ordering2Val =
1716         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1717   }
1718   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1719 
1720   RTLIB::Libcall RTLibType;
1721   if (UseSizedLibcall) {
1722     switch (Size) {
1723     case 1: RTLibType = Libcalls[1]; break;
1724     case 2: RTLibType = Libcalls[2]; break;
1725     case 4: RTLibType = Libcalls[3]; break;
1726     case 8: RTLibType = Libcalls[4]; break;
1727     case 16: RTLibType = Libcalls[5]; break;
1728     }
1729   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1730     RTLibType = Libcalls[0];
1731   } else {
1732     // Can't use sized function, and there's no generic for this
1733     // operation, so give up.
1734     return false;
1735   }
1736 
1737   if (!TLI->getLibcallName(RTLibType)) {
1738     // This target does not implement the requested atomic libcall so give up.
1739     return false;
1740   }
1741 
1742   // Build up the function call. There's two kinds. First, the sized
1743   // variants.  These calls are going to be one of the following (with
1744   // N=1,2,4,8,16):
1745   //  iN    __atomic_load_N(iN *ptr, int ordering)
1746   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1747   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1748   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1749   //                                    int success_order, int failure_order)
1750   //
1751   // Note that these functions can be used for non-integer atomic
1752   // operations, the values just need to be bitcast to integers on the
1753   // way in and out.
1754   //
1755   // And, then, the generic variants. They look like the following:
1756   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1757   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1758   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1759   //                          int ordering)
1760   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1761   //                                  void *desired, int success_order,
1762   //                                  int failure_order)
1763   //
1764   // The different signatures are built up depending on the
1765   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1766   // variables.
1767 
1768   AllocaInst *AllocaCASExpected = nullptr;
1769   Value *AllocaCASExpected_i8 = nullptr;
1770   AllocaInst *AllocaValue = nullptr;
1771   Value *AllocaValue_i8 = nullptr;
1772   AllocaInst *AllocaResult = nullptr;
1773   Value *AllocaResult_i8 = nullptr;
1774 
1775   Type *ResultTy;
1776   SmallVector<Value *, 6> Args;
1777   AttributeList Attr;
1778 
1779   // 'size' argument.
1780   if (!UseSizedLibcall) {
1781     // Note, getIntPtrType is assumed equivalent to size_t.
1782     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1783   }
1784 
1785   // 'ptr' argument.
1786   // note: This assumes all address spaces share a common libfunc
1787   // implementation and that addresses are convertable.  For systems without
1788   // that property, we'd need to extend this mechanism to support AS-specific
1789   // families of atomic intrinsics.
1790   auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
1791   Value *PtrVal = Builder.CreateBitCast(PointerOperand,
1792                                         Type::getInt8PtrTy(Ctx, PtrTypeAS));
1793   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
1794   Args.push_back(PtrVal);
1795 
1796   // 'expected' argument, if present.
1797   if (CASExpected) {
1798     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1799     AllocaCASExpected->setAlignment(AllocaAlignment);
1800     unsigned AllocaAS =  AllocaCASExpected->getType()->getPointerAddressSpace();
1801 
1802     AllocaCASExpected_i8 =
1803       Builder.CreateBitCast(AllocaCASExpected,
1804                             Type::getInt8PtrTy(Ctx, AllocaAS));
1805     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
1806     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1807     Args.push_back(AllocaCASExpected_i8);
1808   }
1809 
1810   // 'val' argument ('desired' for cas), if present.
1811   if (ValueOperand) {
1812     if (UseSizedLibcall) {
1813       Value *IntValue =
1814           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1815       Args.push_back(IntValue);
1816     } else {
1817       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1818       AllocaValue->setAlignment(AllocaAlignment);
1819       AllocaValue_i8 =
1820           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
1821       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
1822       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1823       Args.push_back(AllocaValue_i8);
1824     }
1825   }
1826 
1827   // 'ret' argument.
1828   if (!CASExpected && HasResult && !UseSizedLibcall) {
1829     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1830     AllocaResult->setAlignment(AllocaAlignment);
1831     unsigned AllocaAS =  AllocaResult->getType()->getPointerAddressSpace();
1832     AllocaResult_i8 =
1833       Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
1834     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
1835     Args.push_back(AllocaResult_i8);
1836   }
1837 
1838   // 'ordering' ('success_order' for cas) argument.
1839   Args.push_back(OrderingVal);
1840 
1841   // 'failure_order' argument, if present.
1842   if (Ordering2Val)
1843     Args.push_back(Ordering2Val);
1844 
1845   // Now, the return type.
1846   if (CASExpected) {
1847     ResultTy = Type::getInt1Ty(Ctx);
1848     Attr = Attr.addAttribute(Ctx, AttributeList::ReturnIndex, Attribute::ZExt);
1849   } else if (HasResult && UseSizedLibcall)
1850     ResultTy = SizedIntTy;
1851   else
1852     ResultTy = Type::getVoidTy(Ctx);
1853 
1854   // Done with setting up arguments and return types, create the call:
1855   SmallVector<Type *, 6> ArgTys;
1856   for (Value *Arg : Args)
1857     ArgTys.push_back(Arg->getType());
1858   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
1859   FunctionCallee LibcallFn =
1860       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
1861   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
1862   Call->setAttributes(Attr);
1863   Value *Result = Call;
1864 
1865   // And then, extract the results...
1866   if (ValueOperand && !UseSizedLibcall)
1867     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
1868 
1869   if (CASExpected) {
1870     // The final result from the CAS is {load of 'expected' alloca, bool result
1871     // from call}
1872     Type *FinalResultTy = I->getType();
1873     Value *V = UndefValue::get(FinalResultTy);
1874     Value *ExpectedOut = Builder.CreateAlignedLoad(
1875         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
1876     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
1877     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
1878     V = Builder.CreateInsertValue(V, Result, 1);
1879     I->replaceAllUsesWith(V);
1880   } else if (HasResult) {
1881     Value *V;
1882     if (UseSizedLibcall)
1883       V = Builder.CreateBitOrPointerCast(Result, I->getType());
1884     else {
1885       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
1886                                     AllocaAlignment);
1887       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
1888     }
1889     I->replaceAllUsesWith(V);
1890   }
1891   I->eraseFromParent();
1892   return true;
1893 }
1894