AtomicExpandPass.cpp 71 KB

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