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