ExpandMemCmp.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. //===--- ExpandMemCmp.cpp - Expand memcmp() to load/stores ----------------===//
  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 pass tries to expand memcmp() calls into optimally-sized loads and
  10. // compares for the target.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/ConstantFolding.h"
  15. #include "llvm/Analysis/DomTreeUpdater.h"
  16. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  17. #include "llvm/Analysis/ProfileSummaryInfo.h"
  18. #include "llvm/Analysis/TargetLibraryInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/CodeGen/TargetLowering.h"
  22. #include "llvm/CodeGen/TargetPassConfig.h"
  23. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  24. #include "llvm/IR/Dominators.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/InitializePasses.h"
  27. #include "llvm/Target/TargetMachine.h"
  28. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  29. #include "llvm/Transforms/Utils/Local.h"
  30. #include "llvm/Transforms/Utils/SizeOpts.h"
  31. using namespace llvm;
  32. #define DEBUG_TYPE "expandmemcmp"
  33. STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
  34. STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
  35. STATISTIC(NumMemCmpGreaterThanMax,
  36. "Number of memcmp calls with size greater than max size");
  37. STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
  38. static cl::opt<unsigned> MemCmpEqZeroNumLoadsPerBlock(
  39. "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
  40. cl::desc("The number of loads per basic block for inline expansion of "
  41. "memcmp that is only being compared against zero."));
  42. static cl::opt<unsigned> MaxLoadsPerMemcmp(
  43. "max-loads-per-memcmp", cl::Hidden,
  44. cl::desc("Set maximum number of loads used in expanded memcmp"));
  45. static cl::opt<unsigned> MaxLoadsPerMemcmpOptSize(
  46. "max-loads-per-memcmp-opt-size", cl::Hidden,
  47. cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
  48. namespace {
  49. // This class provides helper functions to expand a memcmp library call into an
  50. // inline expansion.
  51. class MemCmpExpansion {
  52. struct ResultBlock {
  53. BasicBlock *BB = nullptr;
  54. PHINode *PhiSrc1 = nullptr;
  55. PHINode *PhiSrc2 = nullptr;
  56. ResultBlock() = default;
  57. };
  58. CallInst *const CI;
  59. ResultBlock ResBlock;
  60. const uint64_t Size;
  61. unsigned MaxLoadSize = 0;
  62. uint64_t NumLoadsNonOneByte = 0;
  63. const uint64_t NumLoadsPerBlockForZeroCmp;
  64. std::vector<BasicBlock *> LoadCmpBlocks;
  65. BasicBlock *EndBlock;
  66. PHINode *PhiRes;
  67. const bool IsUsedForZeroCmp;
  68. const DataLayout &DL;
  69. DomTreeUpdater *DTU;
  70. IRBuilder<> Builder;
  71. // Represents the decomposition in blocks of the expansion. For example,
  72. // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
  73. // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {1, 32}.
  74. struct LoadEntry {
  75. LoadEntry(unsigned LoadSize, uint64_t Offset)
  76. : LoadSize(LoadSize), Offset(Offset) {
  77. }
  78. // The size of the load for this block, in bytes.
  79. unsigned LoadSize;
  80. // The offset of this load from the base pointer, in bytes.
  81. uint64_t Offset;
  82. };
  83. using LoadEntryVector = SmallVector<LoadEntry, 8>;
  84. LoadEntryVector LoadSequence;
  85. void createLoadCmpBlocks();
  86. void createResultBlock();
  87. void setupResultBlockPHINodes();
  88. void setupEndBlockPHINodes();
  89. Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
  90. void emitLoadCompareBlock(unsigned BlockIndex);
  91. void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
  92. unsigned &LoadIndex);
  93. void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
  94. void emitMemCmpResultBlock();
  95. Value *getMemCmpExpansionZeroCase();
  96. Value *getMemCmpEqZeroOneBlock();
  97. Value *getMemCmpOneBlock();
  98. struct LoadPair {
  99. Value *Lhs = nullptr;
  100. Value *Rhs = nullptr;
  101. };
  102. LoadPair getLoadPair(Type *LoadSizeType, bool NeedsBSwap, Type *CmpSizeType,
  103. unsigned OffsetBytes);
  104. static LoadEntryVector
  105. computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
  106. unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
  107. static LoadEntryVector
  108. computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
  109. unsigned MaxNumLoads,
  110. unsigned &NumLoadsNonOneByte);
  111. public:
  112. MemCmpExpansion(CallInst *CI, uint64_t Size,
  113. const TargetTransformInfo::MemCmpExpansionOptions &Options,
  114. const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
  115. DomTreeUpdater *DTU);
  116. unsigned getNumBlocks();
  117. uint64_t getNumLoads() const { return LoadSequence.size(); }
  118. Value *getMemCmpExpansion();
  119. };
  120. MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
  121. uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
  122. const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
  123. NumLoadsNonOneByte = 0;
  124. LoadEntryVector LoadSequence;
  125. uint64_t Offset = 0;
  126. while (Size && !LoadSizes.empty()) {
  127. const unsigned LoadSize = LoadSizes.front();
  128. const uint64_t NumLoadsForThisSize = Size / LoadSize;
  129. if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
  130. // Do not expand if the total number of loads is larger than what the
  131. // target allows. Note that it's important that we exit before completing
  132. // the expansion to avoid using a ton of memory to store the expansion for
  133. // large sizes.
  134. return {};
  135. }
  136. if (NumLoadsForThisSize > 0) {
  137. for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
  138. LoadSequence.push_back({LoadSize, Offset});
  139. Offset += LoadSize;
  140. }
  141. if (LoadSize > 1)
  142. ++NumLoadsNonOneByte;
  143. Size = Size % LoadSize;
  144. }
  145. LoadSizes = LoadSizes.drop_front();
  146. }
  147. return LoadSequence;
  148. }
  149. MemCmpExpansion::LoadEntryVector
  150. MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size,
  151. const unsigned MaxLoadSize,
  152. const unsigned MaxNumLoads,
  153. unsigned &NumLoadsNonOneByte) {
  154. // These are already handled by the greedy approach.
  155. if (Size < 2 || MaxLoadSize < 2)
  156. return {};
  157. // We try to do as many non-overlapping loads as possible starting from the
  158. // beginning.
  159. const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
  160. assert(NumNonOverlappingLoads && "there must be at least one load");
  161. // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
  162. // an overlapping load.
  163. Size = Size - NumNonOverlappingLoads * MaxLoadSize;
  164. // Bail if we do not need an overloapping store, this is already handled by
  165. // the greedy approach.
  166. if (Size == 0)
  167. return {};
  168. // Bail if the number of loads (non-overlapping + potential overlapping one)
  169. // is larger than the max allowed.
  170. if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
  171. return {};
  172. // Add non-overlapping loads.
  173. LoadEntryVector LoadSequence;
  174. uint64_t Offset = 0;
  175. for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
  176. LoadSequence.push_back({MaxLoadSize, Offset});
  177. Offset += MaxLoadSize;
  178. }
  179. // Add the last overlapping load.
  180. assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
  181. LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)});
  182. NumLoadsNonOneByte = 1;
  183. return LoadSequence;
  184. }
  185. // Initialize the basic block structure required for expansion of memcmp call
  186. // with given maximum load size and memcmp size parameter.
  187. // This structure includes:
  188. // 1. A list of load compare blocks - LoadCmpBlocks.
  189. // 2. An EndBlock, split from original instruction point, which is the block to
  190. // return from.
  191. // 3. ResultBlock, block to branch to for early exit when a
  192. // LoadCmpBlock finds a difference.
  193. MemCmpExpansion::MemCmpExpansion(
  194. CallInst *const CI, uint64_t Size,
  195. const TargetTransformInfo::MemCmpExpansionOptions &Options,
  196. const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
  197. DomTreeUpdater *DTU)
  198. : CI(CI), Size(Size), NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
  199. IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), DTU(DTU),
  200. Builder(CI) {
  201. assert(Size > 0 && "zero blocks");
  202. // Scale the max size down if the target can load more bytes than we need.
  203. llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
  204. while (!LoadSizes.empty() && LoadSizes.front() > Size) {
  205. LoadSizes = LoadSizes.drop_front();
  206. }
  207. assert(!LoadSizes.empty() && "cannot load Size bytes");
  208. MaxLoadSize = LoadSizes.front();
  209. // Compute the decomposition.
  210. unsigned GreedyNumLoadsNonOneByte = 0;
  211. LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
  212. GreedyNumLoadsNonOneByte);
  213. NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
  214. assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
  215. // If we allow overlapping loads and the load sequence is not already optimal,
  216. // use overlapping loads.
  217. if (Options.AllowOverlappingLoads &&
  218. (LoadSequence.empty() || LoadSequence.size() > 2)) {
  219. unsigned OverlappingNumLoadsNonOneByte = 0;
  220. auto OverlappingLoads = computeOverlappingLoadSequence(
  221. Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
  222. if (!OverlappingLoads.empty() &&
  223. (LoadSequence.empty() ||
  224. OverlappingLoads.size() < LoadSequence.size())) {
  225. LoadSequence = OverlappingLoads;
  226. NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
  227. }
  228. }
  229. assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
  230. }
  231. unsigned MemCmpExpansion::getNumBlocks() {
  232. if (IsUsedForZeroCmp)
  233. return getNumLoads() / NumLoadsPerBlockForZeroCmp +
  234. (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
  235. return getNumLoads();
  236. }
  237. void MemCmpExpansion::createLoadCmpBlocks() {
  238. for (unsigned i = 0; i < getNumBlocks(); i++) {
  239. BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
  240. EndBlock->getParent(), EndBlock);
  241. LoadCmpBlocks.push_back(BB);
  242. }
  243. }
  244. void MemCmpExpansion::createResultBlock() {
  245. ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
  246. EndBlock->getParent(), EndBlock);
  247. }
  248. MemCmpExpansion::LoadPair MemCmpExpansion::getLoadPair(Type *LoadSizeType,
  249. bool NeedsBSwap,
  250. Type *CmpSizeType,
  251. unsigned OffsetBytes) {
  252. // Get the memory source at offset `OffsetBytes`.
  253. Value *LhsSource = CI->getArgOperand(0);
  254. Value *RhsSource = CI->getArgOperand(1);
  255. Align LhsAlign = LhsSource->getPointerAlignment(DL);
  256. Align RhsAlign = RhsSource->getPointerAlignment(DL);
  257. if (OffsetBytes > 0) {
  258. auto *ByteType = Type::getInt8Ty(CI->getContext());
  259. LhsSource = Builder.CreateConstGEP1_64(
  260. ByteType, Builder.CreateBitCast(LhsSource, ByteType->getPointerTo()),
  261. OffsetBytes);
  262. RhsSource = Builder.CreateConstGEP1_64(
  263. ByteType, Builder.CreateBitCast(RhsSource, ByteType->getPointerTo()),
  264. OffsetBytes);
  265. LhsAlign = commonAlignment(LhsAlign, OffsetBytes);
  266. RhsAlign = commonAlignment(RhsAlign, OffsetBytes);
  267. }
  268. LhsSource = Builder.CreateBitCast(LhsSource, LoadSizeType->getPointerTo());
  269. RhsSource = Builder.CreateBitCast(RhsSource, LoadSizeType->getPointerTo());
  270. // Create a constant or a load from the source.
  271. Value *Lhs = nullptr;
  272. if (auto *C = dyn_cast<Constant>(LhsSource))
  273. Lhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
  274. if (!Lhs)
  275. Lhs = Builder.CreateAlignedLoad(LoadSizeType, LhsSource, LhsAlign);
  276. Value *Rhs = nullptr;
  277. if (auto *C = dyn_cast<Constant>(RhsSource))
  278. Rhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
  279. if (!Rhs)
  280. Rhs = Builder.CreateAlignedLoad(LoadSizeType, RhsSource, RhsAlign);
  281. // Swap bytes if required.
  282. if (NeedsBSwap) {
  283. Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
  284. Intrinsic::bswap, LoadSizeType);
  285. Lhs = Builder.CreateCall(Bswap, Lhs);
  286. Rhs = Builder.CreateCall(Bswap, Rhs);
  287. }
  288. // Zero extend if required.
  289. if (CmpSizeType != nullptr && CmpSizeType != LoadSizeType) {
  290. Lhs = Builder.CreateZExt(Lhs, CmpSizeType);
  291. Rhs = Builder.CreateZExt(Rhs, CmpSizeType);
  292. }
  293. return {Lhs, Rhs};
  294. }
  295. // This function creates the IR instructions for loading and comparing 1 byte.
  296. // It loads 1 byte from each source of the memcmp parameters with the given
  297. // GEPIndex. It then subtracts the two loaded values and adds this result to the
  298. // final phi node for selecting the memcmp result.
  299. void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
  300. unsigned OffsetBytes) {
  301. BasicBlock *BB = LoadCmpBlocks[BlockIndex];
  302. Builder.SetInsertPoint(BB);
  303. const LoadPair Loads =
  304. getLoadPair(Type::getInt8Ty(CI->getContext()), /*NeedsBSwap=*/false,
  305. Type::getInt32Ty(CI->getContext()), OffsetBytes);
  306. Value *Diff = Builder.CreateSub(Loads.Lhs, Loads.Rhs);
  307. PhiRes->addIncoming(Diff, BB);
  308. if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
  309. // Early exit branch if difference found to EndBlock. Otherwise, continue to
  310. // next LoadCmpBlock,
  311. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
  312. ConstantInt::get(Diff->getType(), 0));
  313. BranchInst *CmpBr =
  314. BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp);
  315. Builder.Insert(CmpBr);
  316. if (DTU)
  317. DTU->applyUpdates(
  318. {{DominatorTree::Insert, BB, EndBlock},
  319. {DominatorTree::Insert, BB, LoadCmpBlocks[BlockIndex + 1]}});
  320. } else {
  321. // The last block has an unconditional branch to EndBlock.
  322. BranchInst *CmpBr = BranchInst::Create(EndBlock);
  323. Builder.Insert(CmpBr);
  324. if (DTU)
  325. DTU->applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
  326. }
  327. }
  328. /// Generate an equality comparison for one or more pairs of loaded values.
  329. /// This is used in the case where the memcmp() call is compared equal or not
  330. /// equal to zero.
  331. Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
  332. unsigned &LoadIndex) {
  333. assert(LoadIndex < getNumLoads() &&
  334. "getCompareLoadPairs() called with no remaining loads");
  335. std::vector<Value *> XorList, OrList;
  336. Value *Diff = nullptr;
  337. const unsigned NumLoads =
  338. std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
  339. // For a single-block expansion, start inserting before the memcmp call.
  340. if (LoadCmpBlocks.empty())
  341. Builder.SetInsertPoint(CI);
  342. else
  343. Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
  344. Value *Cmp = nullptr;
  345. // If we have multiple loads per block, we need to generate a composite
  346. // comparison using xor+or. The type for the combinations is the largest load
  347. // type.
  348. IntegerType *const MaxLoadType =
  349. NumLoads == 1 ? nullptr
  350. : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  351. for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
  352. const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
  353. const LoadPair Loads = getLoadPair(
  354. IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8),
  355. /*NeedsBSwap=*/false, MaxLoadType, CurLoadEntry.Offset);
  356. if (NumLoads != 1) {
  357. // If we have multiple loads per block, we need to generate a composite
  358. // comparison using xor+or.
  359. Diff = Builder.CreateXor(Loads.Lhs, Loads.Rhs);
  360. Diff = Builder.CreateZExt(Diff, MaxLoadType);
  361. XorList.push_back(Diff);
  362. } else {
  363. // If there's only one load per block, we just compare the loaded values.
  364. Cmp = Builder.CreateICmpNE(Loads.Lhs, Loads.Rhs);
  365. }
  366. }
  367. auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
  368. std::vector<Value *> OutList;
  369. for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
  370. Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
  371. OutList.push_back(Or);
  372. }
  373. if (InList.size() % 2 != 0)
  374. OutList.push_back(InList.back());
  375. return OutList;
  376. };
  377. if (!Cmp) {
  378. // Pairwise OR the XOR results.
  379. OrList = pairWiseOr(XorList);
  380. // Pairwise OR the OR results until one result left.
  381. while (OrList.size() != 1) {
  382. OrList = pairWiseOr(OrList);
  383. }
  384. assert(Diff && "Failed to find comparison diff");
  385. Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
  386. }
  387. return Cmp;
  388. }
  389. void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
  390. unsigned &LoadIndex) {
  391. Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
  392. BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
  393. ? EndBlock
  394. : LoadCmpBlocks[BlockIndex + 1];
  395. // Early exit branch if difference found to ResultBlock. Otherwise,
  396. // continue to next LoadCmpBlock or EndBlock.
  397. BasicBlock *BB = Builder.GetInsertBlock();
  398. BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
  399. Builder.Insert(CmpBr);
  400. if (DTU)
  401. DTU->applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
  402. {DominatorTree::Insert, BB, NextBB}});
  403. // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
  404. // since early exit to ResultBlock was not taken (no difference was found in
  405. // any of the bytes).
  406. if (BlockIndex == LoadCmpBlocks.size() - 1) {
  407. Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
  408. PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
  409. }
  410. }
  411. // This function creates the IR intructions for loading and comparing using the
  412. // given LoadSize. It loads the number of bytes specified by LoadSize from each
  413. // source of the memcmp parameters. It then does a subtract to see if there was
  414. // a difference in the loaded values. If a difference is found, it branches
  415. // with an early exit to the ResultBlock for calculating which source was
  416. // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
  417. // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
  418. // a special case through emitLoadCompareByteBlock. The special handling can
  419. // simply subtract the loaded values and add it to the result phi node.
  420. void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
  421. // There is one load per block in this case, BlockIndex == LoadIndex.
  422. const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
  423. if (CurLoadEntry.LoadSize == 1) {
  424. MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
  425. return;
  426. }
  427. Type *LoadSizeType =
  428. IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
  429. Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  430. assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
  431. Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
  432. const LoadPair Loads =
  433. getLoadPair(LoadSizeType, /*NeedsBSwap=*/DL.isLittleEndian(), MaxLoadType,
  434. CurLoadEntry.Offset);
  435. // Add the loaded values to the phi nodes for calculating memcmp result only
  436. // if result is not used in a zero equality.
  437. if (!IsUsedForZeroCmp) {
  438. ResBlock.PhiSrc1->addIncoming(Loads.Lhs, LoadCmpBlocks[BlockIndex]);
  439. ResBlock.PhiSrc2->addIncoming(Loads.Rhs, LoadCmpBlocks[BlockIndex]);
  440. }
  441. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Loads.Lhs, Loads.Rhs);
  442. BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
  443. ? EndBlock
  444. : LoadCmpBlocks[BlockIndex + 1];
  445. // Early exit branch if difference found to ResultBlock. Otherwise, continue
  446. // to next LoadCmpBlock or EndBlock.
  447. BasicBlock *BB = Builder.GetInsertBlock();
  448. BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
  449. Builder.Insert(CmpBr);
  450. if (DTU)
  451. DTU->applyUpdates({{DominatorTree::Insert, BB, NextBB},
  452. {DominatorTree::Insert, BB, ResBlock.BB}});
  453. // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
  454. // since early exit to ResultBlock was not taken (no difference was found in
  455. // any of the bytes).
  456. if (BlockIndex == LoadCmpBlocks.size() - 1) {
  457. Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
  458. PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
  459. }
  460. }
  461. // This function populates the ResultBlock with a sequence to calculate the
  462. // memcmp result. It compares the two loaded source values and returns -1 if
  463. // src1 < src2 and 1 if src1 > src2.
  464. void MemCmpExpansion::emitMemCmpResultBlock() {
  465. // Special case: if memcmp result is used in a zero equality, result does not
  466. // need to be calculated and can simply return 1.
  467. if (IsUsedForZeroCmp) {
  468. BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
  469. Builder.SetInsertPoint(ResBlock.BB, InsertPt);
  470. Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
  471. PhiRes->addIncoming(Res, ResBlock.BB);
  472. BranchInst *NewBr = BranchInst::Create(EndBlock);
  473. Builder.Insert(NewBr);
  474. if (DTU)
  475. DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
  476. return;
  477. }
  478. BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
  479. Builder.SetInsertPoint(ResBlock.BB, InsertPt);
  480. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
  481. ResBlock.PhiSrc2);
  482. Value *Res =
  483. Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
  484. ConstantInt::get(Builder.getInt32Ty(), 1));
  485. PhiRes->addIncoming(Res, ResBlock.BB);
  486. BranchInst *NewBr = BranchInst::Create(EndBlock);
  487. Builder.Insert(NewBr);
  488. if (DTU)
  489. DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
  490. }
  491. void MemCmpExpansion::setupResultBlockPHINodes() {
  492. Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
  493. Builder.SetInsertPoint(ResBlock.BB);
  494. // Note: this assumes one load per block.
  495. ResBlock.PhiSrc1 =
  496. Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
  497. ResBlock.PhiSrc2 =
  498. Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
  499. }
  500. void MemCmpExpansion::setupEndBlockPHINodes() {
  501. Builder.SetInsertPoint(&EndBlock->front());
  502. PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
  503. }
  504. Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
  505. unsigned LoadIndex = 0;
  506. // This loop populates each of the LoadCmpBlocks with the IR sequence to
  507. // handle multiple loads per block.
  508. for (unsigned I = 0; I < getNumBlocks(); ++I) {
  509. emitLoadCompareBlockMultipleLoads(I, LoadIndex);
  510. }
  511. emitMemCmpResultBlock();
  512. return PhiRes;
  513. }
  514. /// A memcmp expansion that compares equality with 0 and only has one block of
  515. /// load and compare can bypass the compare, branch, and phi IR that is required
  516. /// in the general case.
  517. Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
  518. unsigned LoadIndex = 0;
  519. Value *Cmp = getCompareLoadPairs(0, LoadIndex);
  520. assert(LoadIndex == getNumLoads() && "some entries were not consumed");
  521. return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
  522. }
  523. /// A memcmp expansion that only has one block of load and compare can bypass
  524. /// the compare, branch, and phi IR that is required in the general case.
  525. Value *MemCmpExpansion::getMemCmpOneBlock() {
  526. Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
  527. bool NeedsBSwap = DL.isLittleEndian() && Size != 1;
  528. // The i8 and i16 cases don't need compares. We zext the loaded values and
  529. // subtract them to get the suitable negative, zero, or positive i32 result.
  530. if (Size < 4) {
  531. const LoadPair Loads =
  532. getLoadPair(LoadSizeType, NeedsBSwap, Builder.getInt32Ty(),
  533. /*Offset*/ 0);
  534. return Builder.CreateSub(Loads.Lhs, Loads.Rhs);
  535. }
  536. const LoadPair Loads = getLoadPair(LoadSizeType, NeedsBSwap, LoadSizeType,
  537. /*Offset*/ 0);
  538. // The result of memcmp is negative, zero, or positive, so produce that by
  539. // subtracting 2 extended compare bits: sub (ugt, ult).
  540. // If a target prefers to use selects to get -1/0/1, they should be able
  541. // to transform this later. The inverse transform (going from selects to math)
  542. // may not be possible in the DAG because the selects got converted into
  543. // branches before we got there.
  544. Value *CmpUGT = Builder.CreateICmpUGT(Loads.Lhs, Loads.Rhs);
  545. Value *CmpULT = Builder.CreateICmpULT(Loads.Lhs, Loads.Rhs);
  546. Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty());
  547. Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty());
  548. return Builder.CreateSub(ZextUGT, ZextULT);
  549. }
  550. // This function expands the memcmp call into an inline expansion and returns
  551. // the memcmp result.
  552. Value *MemCmpExpansion::getMemCmpExpansion() {
  553. // Create the basic block framework for a multi-block expansion.
  554. if (getNumBlocks() != 1) {
  555. BasicBlock *StartBlock = CI->getParent();
  556. EndBlock = SplitBlock(StartBlock, CI, DTU, /*LI=*/nullptr,
  557. /*MSSAU=*/nullptr, "endblock");
  558. setupEndBlockPHINodes();
  559. createResultBlock();
  560. // If return value of memcmp is not used in a zero equality, we need to
  561. // calculate which source was larger. The calculation requires the
  562. // two loaded source values of each load compare block.
  563. // These will be saved in the phi nodes created by setupResultBlockPHINodes.
  564. if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
  565. // Create the number of required load compare basic blocks.
  566. createLoadCmpBlocks();
  567. // Update the terminator added by SplitBlock to branch to the first
  568. // LoadCmpBlock.
  569. StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
  570. if (DTU)
  571. DTU->applyUpdates({{DominatorTree::Insert, StartBlock, LoadCmpBlocks[0]},
  572. {DominatorTree::Delete, StartBlock, EndBlock}});
  573. }
  574. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  575. if (IsUsedForZeroCmp)
  576. return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
  577. : getMemCmpExpansionZeroCase();
  578. if (getNumBlocks() == 1)
  579. return getMemCmpOneBlock();
  580. for (unsigned I = 0; I < getNumBlocks(); ++I) {
  581. emitLoadCompareBlock(I);
  582. }
  583. emitMemCmpResultBlock();
  584. return PhiRes;
  585. }
  586. // This function checks to see if an expansion of memcmp can be generated.
  587. // It checks for constant compare size that is less than the max inline size.
  588. // If an expansion cannot occur, returns false to leave as a library call.
  589. // Otherwise, the library call is replaced with a new IR instruction sequence.
  590. /// We want to transform:
  591. /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
  592. /// To:
  593. /// loadbb:
  594. /// %0 = bitcast i32* %buffer2 to i8*
  595. /// %1 = bitcast i32* %buffer1 to i8*
  596. /// %2 = bitcast i8* %1 to i64*
  597. /// %3 = bitcast i8* %0 to i64*
  598. /// %4 = load i64, i64* %2
  599. /// %5 = load i64, i64* %3
  600. /// %6 = call i64 @llvm.bswap.i64(i64 %4)
  601. /// %7 = call i64 @llvm.bswap.i64(i64 %5)
  602. /// %8 = sub i64 %6, %7
  603. /// %9 = icmp ne i64 %8, 0
  604. /// br i1 %9, label %res_block, label %loadbb1
  605. /// res_block: ; preds = %loadbb2,
  606. /// %loadbb1, %loadbb
  607. /// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
  608. /// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
  609. /// %10 = icmp ult i64 %phi.src1, %phi.src2
  610. /// %11 = select i1 %10, i32 -1, i32 1
  611. /// br label %endblock
  612. /// loadbb1: ; preds = %loadbb
  613. /// %12 = bitcast i32* %buffer2 to i8*
  614. /// %13 = bitcast i32* %buffer1 to i8*
  615. /// %14 = bitcast i8* %13 to i32*
  616. /// %15 = bitcast i8* %12 to i32*
  617. /// %16 = getelementptr i32, i32* %14, i32 2
  618. /// %17 = getelementptr i32, i32* %15, i32 2
  619. /// %18 = load i32, i32* %16
  620. /// %19 = load i32, i32* %17
  621. /// %20 = call i32 @llvm.bswap.i32(i32 %18)
  622. /// %21 = call i32 @llvm.bswap.i32(i32 %19)
  623. /// %22 = zext i32 %20 to i64
  624. /// %23 = zext i32 %21 to i64
  625. /// %24 = sub i64 %22, %23
  626. /// %25 = icmp ne i64 %24, 0
  627. /// br i1 %25, label %res_block, label %loadbb2
  628. /// loadbb2: ; preds = %loadbb1
  629. /// %26 = bitcast i32* %buffer2 to i8*
  630. /// %27 = bitcast i32* %buffer1 to i8*
  631. /// %28 = bitcast i8* %27 to i16*
  632. /// %29 = bitcast i8* %26 to i16*
  633. /// %30 = getelementptr i16, i16* %28, i16 6
  634. /// %31 = getelementptr i16, i16* %29, i16 6
  635. /// %32 = load i16, i16* %30
  636. /// %33 = load i16, i16* %31
  637. /// %34 = call i16 @llvm.bswap.i16(i16 %32)
  638. /// %35 = call i16 @llvm.bswap.i16(i16 %33)
  639. /// %36 = zext i16 %34 to i64
  640. /// %37 = zext i16 %35 to i64
  641. /// %38 = sub i64 %36, %37
  642. /// %39 = icmp ne i64 %38, 0
  643. /// br i1 %39, label %res_block, label %loadbb3
  644. /// loadbb3: ; preds = %loadbb2
  645. /// %40 = bitcast i32* %buffer2 to i8*
  646. /// %41 = bitcast i32* %buffer1 to i8*
  647. /// %42 = getelementptr i8, i8* %41, i8 14
  648. /// %43 = getelementptr i8, i8* %40, i8 14
  649. /// %44 = load i8, i8* %42
  650. /// %45 = load i8, i8* %43
  651. /// %46 = zext i8 %44 to i32
  652. /// %47 = zext i8 %45 to i32
  653. /// %48 = sub i32 %46, %47
  654. /// br label %endblock
  655. /// endblock: ; preds = %res_block,
  656. /// %loadbb3
  657. /// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
  658. /// ret i32 %phi.res
  659. static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
  660. const TargetLowering *TLI, const DataLayout *DL,
  661. ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
  662. DomTreeUpdater *DTU) {
  663. NumMemCmpCalls++;
  664. // Early exit from expansion if -Oz.
  665. if (CI->getFunction()->hasMinSize())
  666. return false;
  667. // Early exit from expansion if size is not a constant.
  668. ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  669. if (!SizeCast) {
  670. NumMemCmpNotConstant++;
  671. return false;
  672. }
  673. const uint64_t SizeVal = SizeCast->getZExtValue();
  674. if (SizeVal == 0) {
  675. return false;
  676. }
  677. // TTI call to check if target would like to expand memcmp. Also, get the
  678. // available load sizes.
  679. const bool IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI);
  680. bool OptForSize = CI->getFunction()->hasOptSize() ||
  681. llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
  682. auto Options = TTI->enableMemCmpExpansion(OptForSize,
  683. IsUsedForZeroCmp);
  684. if (!Options) return false;
  685. if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
  686. Options.NumLoadsPerBlock = MemCmpEqZeroNumLoadsPerBlock;
  687. if (OptForSize &&
  688. MaxLoadsPerMemcmpOptSize.getNumOccurrences())
  689. Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
  690. if (!OptForSize && MaxLoadsPerMemcmp.getNumOccurrences())
  691. Options.MaxNumLoads = MaxLoadsPerMemcmp;
  692. MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DTU);
  693. // Don't expand if this will require more loads than desired by the target.
  694. if (Expansion.getNumLoads() == 0) {
  695. NumMemCmpGreaterThanMax++;
  696. return false;
  697. }
  698. NumMemCmpInlined++;
  699. Value *Res = Expansion.getMemCmpExpansion();
  700. // Replace call with result of expansion and erase call.
  701. CI->replaceAllUsesWith(Res);
  702. CI->eraseFromParent();
  703. return true;
  704. }
  705. class ExpandMemCmpPass : public FunctionPass {
  706. public:
  707. static char ID;
  708. ExpandMemCmpPass() : FunctionPass(ID) {
  709. initializeExpandMemCmpPassPass(*PassRegistry::getPassRegistry());
  710. }
  711. bool runOnFunction(Function &F) override {
  712. if (skipFunction(F)) return false;
  713. auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
  714. if (!TPC) {
  715. return false;
  716. }
  717. const TargetLowering* TL =
  718. TPC->getTM<TargetMachine>().getSubtargetImpl(F)->getTargetLowering();
  719. const TargetLibraryInfo *TLI =
  720. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  721. const TargetTransformInfo *TTI =
  722. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  723. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  724. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  725. &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
  726. nullptr;
  727. DominatorTree *DT = nullptr;
  728. if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  729. DT = &DTWP->getDomTree();
  730. auto PA = runImpl(F, TLI, TTI, TL, PSI, BFI, DT);
  731. return !PA.areAllPreserved();
  732. }
  733. private:
  734. void getAnalysisUsage(AnalysisUsage &AU) const override {
  735. AU.addRequired<TargetLibraryInfoWrapperPass>();
  736. AU.addRequired<TargetTransformInfoWrapperPass>();
  737. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  738. AU.addPreserved<DominatorTreeWrapperPass>();
  739. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  740. FunctionPass::getAnalysisUsage(AU);
  741. }
  742. PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
  743. const TargetTransformInfo *TTI,
  744. const TargetLowering *TL, ProfileSummaryInfo *PSI,
  745. BlockFrequencyInfo *BFI, DominatorTree *DT);
  746. // Returns true if a change was made.
  747. bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
  748. const TargetTransformInfo *TTI, const TargetLowering *TL,
  749. const DataLayout &DL, ProfileSummaryInfo *PSI,
  750. BlockFrequencyInfo *BFI, DomTreeUpdater *DTU);
  751. };
  752. bool ExpandMemCmpPass::runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
  753. const TargetTransformInfo *TTI,
  754. const TargetLowering *TL,
  755. const DataLayout &DL, ProfileSummaryInfo *PSI,
  756. BlockFrequencyInfo *BFI,
  757. DomTreeUpdater *DTU) {
  758. for (Instruction& I : BB) {
  759. CallInst *CI = dyn_cast<CallInst>(&I);
  760. if (!CI) {
  761. continue;
  762. }
  763. LibFunc Func;
  764. if (TLI->getLibFunc(*CI, Func) &&
  765. (Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
  766. expandMemCmp(CI, TTI, TL, &DL, PSI, BFI, DTU)) {
  767. return true;
  768. }
  769. }
  770. return false;
  771. }
  772. PreservedAnalyses
  773. ExpandMemCmpPass::runImpl(Function &F, const TargetLibraryInfo *TLI,
  774. const TargetTransformInfo *TTI,
  775. const TargetLowering *TL, ProfileSummaryInfo *PSI,
  776. BlockFrequencyInfo *BFI, DominatorTree *DT) {
  777. Optional<DomTreeUpdater> DTU;
  778. if (DT)
  779. DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  780. const DataLayout& DL = F.getParent()->getDataLayout();
  781. bool MadeChanges = false;
  782. for (auto BBIt = F.begin(); BBIt != F.end();) {
  783. if (runOnBlock(*BBIt, TLI, TTI, TL, DL, PSI, BFI,
  784. DTU.hasValue() ? DTU.getPointer() : nullptr)) {
  785. MadeChanges = true;
  786. // If changes were made, restart the function from the beginning, since
  787. // the structure of the function was changed.
  788. BBIt = F.begin();
  789. } else {
  790. ++BBIt;
  791. }
  792. }
  793. if (MadeChanges)
  794. for (BasicBlock &BB : F)
  795. SimplifyInstructionsInBlock(&BB);
  796. if (!MadeChanges)
  797. return PreservedAnalyses::all();
  798. PreservedAnalyses PA;
  799. PA.preserve<DominatorTreeAnalysis>();
  800. return PA;
  801. }
  802. } // namespace
  803. char ExpandMemCmpPass::ID = 0;
  804. INITIALIZE_PASS_BEGIN(ExpandMemCmpPass, "expandmemcmp",
  805. "Expand memcmp() to load/stores", false, false)
  806. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  807. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  808. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  809. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  810. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  811. INITIALIZE_PASS_END(ExpandMemCmpPass, "expandmemcmp",
  812. "Expand memcmp() to load/stores", false, false)
  813. FunctionPass *llvm::createExpandMemCmpPass() {
  814. return new ExpandMemCmpPass();
  815. }