LLVM 23.0.0git
ExpandMemCmp.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/IRBuilder.h"
31#include <optional>
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "expand-memcmp"
37
38STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
39STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
40STATISTIC(NumMemCmpGreaterThanMax,
41 "Number of memcmp calls with size greater than max size");
42STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
43
45 "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
46 cl::desc("The number of loads per basic block for inline expansion of "
47 "memcmp that is only being compared against zero."));
48
50 "max-loads-per-memcmp", cl::Hidden,
51 cl::desc("Set maximum number of loads used in expanded memcmp"));
52
54 "max-loads-per-memcmp-opt-size", cl::Hidden,
55 cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
56
57namespace {
58
59
60// This class provides helper functions to expand a memcmp library call into an
61// inline expansion.
62class MemCmpExpansion {
63 struct ResultBlock {
64 BasicBlock *BB = nullptr;
65 PHINode *PhiSrc1 = nullptr;
66 PHINode *PhiSrc2 = nullptr;
67
68 ResultBlock() = default;
69 };
70
71 CallInst *const CI = nullptr;
72 ResultBlock ResBlock;
73 const uint64_t Size;
74 unsigned MaxLoadSize = 0;
75 uint64_t NumLoadsNonOneByte = 0;
76 const uint64_t NumLoadsPerBlockForZeroCmp;
77 std::vector<BasicBlock *> LoadCmpBlocks;
78 BasicBlock *EndBlock = nullptr;
79 PHINode *PhiRes = nullptr;
80 const bool IsUsedForZeroCmp;
81 const DataLayout &DL;
82 DomTreeUpdater *DTU = nullptr;
83 IRBuilder<> Builder;
84 // Represents the decomposition in blocks of the expansion. For example,
85 // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
86 // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {1, 32}.
87 struct LoadEntry {
88 LoadEntry(unsigned LoadSize, uint64_t Offset)
89 : LoadSize(LoadSize), Offset(Offset) {
90 }
91
92 // The size of the load for this block, in bytes.
93 unsigned LoadSize;
94 // The offset of this load from the base pointer, in bytes.
95 uint64_t Offset;
96 };
97 using LoadEntryVector = SmallVector<LoadEntry, 8>;
98 LoadEntryVector LoadSequence;
99
100 void createLoadCmpBlocks();
101 void createResultBlock();
102 void setupResultBlockPHINodes();
103 void setupEndBlockPHINodes();
104 Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
105 void emitLoadCompareBlock(unsigned BlockIndex);
106 void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
107 unsigned &LoadIndex);
108 void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
109 void emitMemCmpResultBlock();
110 Value *getMemCmpExpansionZeroCase();
111 Value *getMemCmpEqZeroOneBlock();
112 Value *getMemCmpOneBlock();
113 struct LoadPair {
114 Value *Lhs = nullptr;
115 Value *Rhs = nullptr;
116 };
117 LoadPair getLoadPair(Type *LoadSizeType, Type *BSwapSizeType,
118 Type *CmpSizeType, unsigned OffsetBytes);
119
120 static LoadEntryVector
121 computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
122 unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
123 static LoadEntryVector
124 computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
125 unsigned MaxNumLoads,
126 unsigned &NumLoadsNonOneByte);
127
128 static void optimiseLoadSequence(
129 LoadEntryVector &LoadSequence,
130 const TargetTransformInfo::MemCmpExpansionOptions &Options,
131 bool IsUsedForZeroCmp);
132
133public:
134 MemCmpExpansion(CallInst *CI, uint64_t Size,
135 const TargetTransformInfo::MemCmpExpansionOptions &Options,
136 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
137 DomTreeUpdater *DTU);
138
139 unsigned getNumBlocks();
140 uint64_t getNumLoads() const { return LoadSequence.size(); }
141
142 Value *getMemCmpExpansion();
143};
144
145MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
147 const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
148 NumLoadsNonOneByte = 0;
149 LoadEntryVector LoadSequence;
150 uint64_t Offset = 0;
151 while (Size && !LoadSizes.empty()) {
152 const unsigned LoadSize = LoadSizes.front();
153 const uint64_t NumLoadsForThisSize = Size / LoadSize;
154 if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
155 // Do not expand if the total number of loads is larger than what the
156 // target allows. Note that it's important that we exit before completing
157 // the expansion to avoid using a ton of memory to store the expansion for
158 // large sizes.
159 return {};
160 }
161 if (NumLoadsForThisSize > 0) {
162 for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
163 LoadSequence.push_back({LoadSize, Offset});
164 Offset += LoadSize;
165 }
166 if (LoadSize > 1)
167 ++NumLoadsNonOneByte;
168 Size = Size % LoadSize;
169 }
170 LoadSizes = LoadSizes.drop_front();
171 }
172 return LoadSequence;
173}
174
175MemCmpExpansion::LoadEntryVector
176MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size,
177 const unsigned MaxLoadSize,
178 const unsigned MaxNumLoads,
179 unsigned &NumLoadsNonOneByte) {
180 // These are already handled by the greedy approach.
181 if (Size < 2 || MaxLoadSize < 2)
182 return {};
183
184 // We try to do as many non-overlapping loads as possible starting from the
185 // beginning.
186 const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
187 assert(NumNonOverlappingLoads && "there must be at least one load");
188 // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
189 // an overlapping load.
190 Size = Size - NumNonOverlappingLoads * MaxLoadSize;
191 // Bail if we do not need an overloapping store, this is already handled by
192 // the greedy approach.
193 if (Size == 0)
194 return {};
195 // Bail if the number of loads (non-overlapping + potential overlapping one)
196 // is larger than the max allowed.
197 if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
198 return {};
199
200 // Add non-overlapping loads.
201 LoadEntryVector LoadSequence;
202 uint64_t Offset = 0;
203 for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
204 LoadSequence.push_back({MaxLoadSize, Offset});
205 Offset += MaxLoadSize;
206 }
207
208 // Add the last overlapping load.
209 assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
210 LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)});
211 NumLoadsNonOneByte = 1;
212 return LoadSequence;
213}
214
215void MemCmpExpansion::optimiseLoadSequence(
216 LoadEntryVector &LoadSequence,
217 const TargetTransformInfo::MemCmpExpansionOptions &Options,
218 bool IsUsedForZeroCmp) {
219 // This part of code attempts to optimize the LoadSequence by merging allowed
220 // subsequences into single loads of allowed sizes from
221 // `MemCmpExpansionOptions::AllowedTailExpansions`. If it is for zero
222 // comparison or if no allowed tail expansions are specified, we exit early.
223 if (IsUsedForZeroCmp || Options.AllowedTailExpansions.empty())
224 return;
225
226 while (LoadSequence.size() >= 2) {
227 auto Last = LoadSequence[LoadSequence.size() - 1];
228 auto PreLast = LoadSequence[LoadSequence.size() - 2];
229
230 // Exit the loop if the two sequences are not contiguous
231 if (PreLast.Offset + PreLast.LoadSize != Last.Offset)
232 break;
233
234 auto LoadSize = Last.LoadSize + PreLast.LoadSize;
235 if (find(Options.AllowedTailExpansions, LoadSize) ==
236 Options.AllowedTailExpansions.end())
237 break;
238
239 // Remove the last two sequences and replace with the combined sequence
240 LoadSequence.pop_back();
241 LoadSequence.pop_back();
242 LoadSequence.emplace_back(PreLast.Offset, LoadSize);
243 }
244}
245
246// Initialize the basic block structure required for expansion of memcmp call
247// with given maximum load size and memcmp size parameter.
248// This structure includes:
249// 1. A list of load compare blocks - LoadCmpBlocks.
250// 2. An EndBlock, split from original instruction point, which is the block to
251// return from.
252// 3. ResultBlock, block to branch to for early exit when a
253// LoadCmpBlock finds a difference.
254MemCmpExpansion::MemCmpExpansion(
255 CallInst *const CI, uint64_t Size,
256 const TargetTransformInfo::MemCmpExpansionOptions &Options,
257 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
258 DomTreeUpdater *DTU)
259 : CI(CI), Size(Size), NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
260 IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), DTU(DTU),
261 Builder(CI) {
262 assert(Size > 0 && "zero blocks");
263 // Scale the max size down if the target can load more bytes than we need.
264 llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
265 while (!LoadSizes.empty() && LoadSizes.front() > Size) {
266 LoadSizes = LoadSizes.drop_front();
267 }
268 assert(!LoadSizes.empty() && "cannot load Size bytes");
269 MaxLoadSize = LoadSizes.front();
270 // Compute the decomposition.
271 unsigned GreedyNumLoadsNonOneByte = 0;
272 LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
273 GreedyNumLoadsNonOneByte);
274 NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
275 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
276 // If we allow overlapping loads and the load sequence is not already optimal,
277 // use overlapping loads.
278 if (Options.AllowOverlappingLoads &&
279 (LoadSequence.empty() || LoadSequence.size() > 2)) {
280 unsigned OverlappingNumLoadsNonOneByte = 0;
281 auto OverlappingLoads = computeOverlappingLoadSequence(
282 Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
283 if (!OverlappingLoads.empty() &&
284 (LoadSequence.empty() ||
285 OverlappingLoads.size() < LoadSequence.size())) {
286 LoadSequence = OverlappingLoads;
287 NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
288 }
289 }
290 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
291 optimiseLoadSequence(LoadSequence, Options, IsUsedForZeroCmp);
292}
293
294unsigned MemCmpExpansion::getNumBlocks() {
295 if (IsUsedForZeroCmp)
296 return getNumLoads() / NumLoadsPerBlockForZeroCmp +
297 (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
298 return getNumLoads();
299}
300
301void MemCmpExpansion::createLoadCmpBlocks() {
302 for (unsigned i = 0; i < getNumBlocks(); i++) {
303 BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
304 EndBlock->getParent(), EndBlock);
305 LoadCmpBlocks.push_back(BB);
306 }
307}
308
309void MemCmpExpansion::createResultBlock() {
310 ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
311 EndBlock->getParent(), EndBlock);
312}
313
314MemCmpExpansion::LoadPair MemCmpExpansion::getLoadPair(Type *LoadSizeType,
315 Type *BSwapSizeType,
316 Type *CmpSizeType,
317 unsigned OffsetBytes) {
318 // Get the memory source at offset `OffsetBytes`.
319 Value *LhsSource = CI->getArgOperand(0);
320 Value *RhsSource = CI->getArgOperand(1);
321 Align LhsAlign = LhsSource->getPointerAlignment(DL);
322 Align RhsAlign = RhsSource->getPointerAlignment(DL);
323 if (OffsetBytes > 0) {
324 auto *ByteType = Type::getInt8Ty(CI->getContext());
325 LhsSource = Builder.CreateConstGEP1_64(ByteType, LhsSource, OffsetBytes);
326 RhsSource = Builder.CreateConstGEP1_64(ByteType, RhsSource, OffsetBytes);
327 LhsAlign = commonAlignment(LhsAlign, OffsetBytes);
328 RhsAlign = commonAlignment(RhsAlign, OffsetBytes);
329 }
330
331 // Create a constant or a load from the source.
332 Value *Lhs = nullptr;
333 if (auto *C = dyn_cast<Constant>(LhsSource))
334 Lhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
335 if (!Lhs)
336 Lhs = Builder.CreateAlignedLoad(LoadSizeType, LhsSource, LhsAlign);
337
338 Value *Rhs = nullptr;
339 if (auto *C = dyn_cast<Constant>(RhsSource))
340 Rhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
341 if (!Rhs)
342 Rhs = Builder.CreateAlignedLoad(LoadSizeType, RhsSource, RhsAlign);
343
344 // Zero extend if Byte Swap intrinsic has different type
345 if (BSwapSizeType && LoadSizeType != BSwapSizeType) {
346 Lhs = Builder.CreateZExt(Lhs, BSwapSizeType);
347 Rhs = Builder.CreateZExt(Rhs, BSwapSizeType);
348 }
349
350 // Swap bytes if required.
351 if (BSwapSizeType) {
353 CI->getModule(), Intrinsic::bswap, BSwapSizeType);
354 Lhs = Builder.CreateCall(Bswap, Lhs);
355 Rhs = Builder.CreateCall(Bswap, Rhs);
356 }
357
358 // Zero extend if required.
359 if (CmpSizeType != nullptr && CmpSizeType != Lhs->getType()) {
360 Lhs = Builder.CreateZExt(Lhs, CmpSizeType);
361 Rhs = Builder.CreateZExt(Rhs, CmpSizeType);
362 }
363 return {Lhs, Rhs};
364}
365
366// This function creates the IR instructions for loading and comparing 1 byte.
367// It loads 1 byte from each source of the memcmp parameters with the given
368// GEPIndex. It then subtracts the two loaded values and adds this result to the
369// final phi node for selecting the memcmp result.
370void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
371 unsigned OffsetBytes) {
372 BasicBlock *BB = LoadCmpBlocks[BlockIndex];
373 Builder.SetInsertPoint(BB);
374 const LoadPair Loads =
375 getLoadPair(Type::getInt8Ty(CI->getContext()), nullptr,
376 Type::getInt32Ty(CI->getContext()), OffsetBytes);
377 Value *Diff = Builder.CreateSub(Loads.Lhs, Loads.Rhs);
378
379 PhiRes->addIncoming(Diff, BB);
380
381 if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
382 // Early exit branch if difference found to EndBlock. Otherwise, continue to
383 // next LoadCmpBlock,
384 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
385 ConstantInt::get(Diff->getType(), 0));
386 Builder.CreateCondBr(Cmp, EndBlock, LoadCmpBlocks[BlockIndex + 1]);
387 if (DTU)
388 DTU->applyUpdates(
389 {{DominatorTree::Insert, BB, EndBlock},
390 {DominatorTree::Insert, BB, LoadCmpBlocks[BlockIndex + 1]}});
391 } else {
392 // The last block has an unconditional branch to EndBlock.
393 Builder.CreateBr(EndBlock);
394 if (DTU)
395 DTU->applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
396 }
397}
398
399/// Generate an equality comparison for one or more pairs of loaded values.
400/// This is used in the case where the memcmp() call is compared equal or not
401/// equal to zero.
402Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
403 unsigned &LoadIndex) {
404 assert(LoadIndex < getNumLoads() &&
405 "getCompareLoadPairs() called with no remaining loads");
406 std::vector<Value *> XorList, OrList;
407 Value *Diff = nullptr;
408
409 const unsigned NumLoads =
410 std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
411
412 // For a single-block expansion, start inserting before the memcmp call.
413 if (LoadCmpBlocks.empty())
414 Builder.SetInsertPoint(CI);
415 else
416 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
417
418 Value *Cmp = nullptr;
419 // If we have multiple loads per block, we need to generate a composite
420 // comparison using xor+or. The type for the combinations is the largest load
421 // type.
422 IntegerType *const MaxLoadType =
423 NumLoads == 1 ? nullptr
424 : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
425
426 for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
427 const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
428 const LoadPair Loads = getLoadPair(
429 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8), nullptr,
430 MaxLoadType, CurLoadEntry.Offset);
431
432 if (NumLoads != 1) {
433 // If we have multiple loads per block, we need to generate a composite
434 // comparison using xor+or.
435 Diff = Builder.CreateXor(Loads.Lhs, Loads.Rhs);
436 Diff = Builder.CreateZExt(Diff, MaxLoadType);
437 XorList.push_back(Diff);
438 } else {
439 // If there's only one load per block, we just compare the loaded values.
440 Cmp = Builder.CreateICmpNE(Loads.Lhs, Loads.Rhs);
441 }
442 }
443
444 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
445 std::vector<Value *> OutList;
446 for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
447 Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
448 OutList.push_back(Or);
449 }
450 if (InList.size() % 2 != 0)
451 OutList.push_back(InList.back());
452 return OutList;
453 };
454
455 if (!Cmp) {
456 // Pairwise OR the XOR results.
457 OrList = pairWiseOr(XorList);
458
459 // Pairwise OR the OR results until one result left.
460 while (OrList.size() != 1) {
461 OrList = pairWiseOr(OrList);
462 }
463
464 assert(Diff && "Failed to find comparison diff");
465 Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
466 }
467
468 return Cmp;
469}
470
471void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
472 unsigned &LoadIndex) {
473 Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
474
475 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
476 ? EndBlock
477 : LoadCmpBlocks[BlockIndex + 1];
478 // Early exit branch if difference found to ResultBlock. Otherwise,
479 // continue to next LoadCmpBlock or EndBlock.
480 BasicBlock *BB = Builder.GetInsertBlock();
481 CondBrInst *CmpBr = Builder.CreateCondBr(Cmp, ResBlock.BB, NextBB);
483 CI->getFunction());
484 if (DTU)
485 DTU->applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
486 {DominatorTree::Insert, BB, NextBB}});
487
488 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
489 // since early exit to ResultBlock was not taken (no difference was found in
490 // any of the bytes).
491 if (BlockIndex == LoadCmpBlocks.size() - 1) {
492 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
493 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
494 }
495}
496
497// This function creates the IR intructions for loading and comparing using the
498// given LoadSize. It loads the number of bytes specified by LoadSize from each
499// source of the memcmp parameters. It then does a subtract to see if there was
500// a difference in the loaded values. If a difference is found, it branches
501// with an early exit to the ResultBlock for calculating which source was
502// larger. Otherwise, it falls through to the either the next LoadCmpBlock or
503// the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
504// a special case through emitLoadCompareByteBlock. The special handling can
505// simply subtract the loaded values and add it to the result phi node.
506void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
507 // There is one load per block in this case, BlockIndex == LoadIndex.
508 const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
509
510 if (CurLoadEntry.LoadSize == 1) {
511 MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
512 return;
513 }
514
515 Type *LoadSizeType =
516 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
517 Type *BSwapSizeType =
518 DL.isLittleEndian()
520 PowerOf2Ceil(CurLoadEntry.LoadSize * 8))
521 : nullptr;
522 Type *MaxLoadType = IntegerType::get(
523 CI->getContext(),
524 std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(CurLoadEntry.LoadSize)) * 8);
525 assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
526
527 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
528
529 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
530 CurLoadEntry.Offset);
531
532 // Add the loaded values to the phi nodes for calculating memcmp result only
533 // if result is not used in a zero equality.
534 if (!IsUsedForZeroCmp) {
535 ResBlock.PhiSrc1->addIncoming(Loads.Lhs, LoadCmpBlocks[BlockIndex]);
536 ResBlock.PhiSrc2->addIncoming(Loads.Rhs, LoadCmpBlocks[BlockIndex]);
537 }
538
539 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Loads.Lhs, Loads.Rhs);
540 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
541 ? EndBlock
542 : LoadCmpBlocks[BlockIndex + 1];
543 // Early exit branch if difference found to ResultBlock. Otherwise, continue
544 // to next LoadCmpBlock or EndBlock.
545 BasicBlock *BB = Builder.GetInsertBlock();
546 CondBrInst *CmpBr = Builder.CreateCondBr(Cmp, NextBB, ResBlock.BB);
548 CI->getFunction());
549 if (DTU)
550 DTU->applyUpdates({{DominatorTree::Insert, BB, NextBB},
551 {DominatorTree::Insert, BB, ResBlock.BB}});
552
553 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
554 // since early exit to ResultBlock was not taken (no difference was found in
555 // any of the bytes).
556 if (BlockIndex == LoadCmpBlocks.size() - 1) {
557 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
558 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
559 }
560}
561
562// This function populates the ResultBlock with a sequence to calculate the
563// memcmp result. It compares the two loaded source values and returns -1 if
564// src1 < src2 and 1 if src1 > src2.
565void MemCmpExpansion::emitMemCmpResultBlock() {
566 // Special case: if memcmp result is used in a zero equality, result does not
567 // need to be calculated and can simply return 1.
568 if (IsUsedForZeroCmp) {
569 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
570 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
571 Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
572 PhiRes->addIncoming(Res, ResBlock.BB);
573 Builder.CreateBr(EndBlock);
574 if (DTU)
575 DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
576 return;
577 }
578 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
579 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
580
581 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
582 ResBlock.PhiSrc2);
583
584 Value *Res =
585 Builder.CreateSelect(Cmp, Constant::getAllOnesValue(Builder.getInt32Ty()),
586 ConstantInt::get(Builder.getInt32Ty(), 1));
588 DEBUG_TYPE, CI->getFunction());
589
590 PhiRes->addIncoming(Res, ResBlock.BB);
591 Builder.CreateBr(EndBlock);
592 if (DTU)
593 DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
594}
595
596void MemCmpExpansion::setupResultBlockPHINodes() {
597 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
598 Builder.SetInsertPoint(ResBlock.BB);
599 // Note: this assumes one load per block.
600 ResBlock.PhiSrc1 =
601 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
602 ResBlock.PhiSrc2 =
603 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
604}
605
606void MemCmpExpansion::setupEndBlockPHINodes() {
607 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
608 PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
609}
610
611Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
612 unsigned LoadIndex = 0;
613 // This loop populates each of the LoadCmpBlocks with the IR sequence to
614 // handle multiple loads per block.
615 for (unsigned I = 0; I < getNumBlocks(); ++I) {
616 emitLoadCompareBlockMultipleLoads(I, LoadIndex);
617 }
618
619 emitMemCmpResultBlock();
620 return PhiRes;
621}
622
623/// A memcmp expansion that compares equality with 0 and only has one block of
624/// load and compare can bypass the compare, branch, and phi IR that is required
625/// in the general case.
626Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
627 unsigned LoadIndex = 0;
628 Value *Cmp = getCompareLoadPairs(0, LoadIndex);
629 assert(LoadIndex == getNumLoads() && "some entries were not consumed");
630 return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
631}
632
633/// A memcmp expansion that only has one block of load and compare can bypass
634/// the compare, branch, and phi IR that is required in the general case.
635/// This function also analyses users of memcmp, and if there is only one user
636/// from which we can conclude that only 2 out of 3 memcmp outcomes really
637/// matter, then it generates more efficient code with only one comparison.
638Value *MemCmpExpansion::getMemCmpOneBlock() {
639 bool NeedsBSwap = DL.isLittleEndian() && Size != 1;
640 Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
641 Type *BSwapSizeType =
642 NeedsBSwap ? IntegerType::get(CI->getContext(), PowerOf2Ceil(Size * 8))
643 : nullptr;
644 Type *MaxLoadType =
646 std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(Size)) * 8);
647
648 // The i8 and i16 cases don't need compares. We zext the loaded values and
649 // subtract them to get the suitable negative, zero, or positive i32 result.
650 if (Size == 1 || Size == 2) {
651 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType,
652 Builder.getInt32Ty(), /*Offset*/ 0);
653 return Builder.CreateSub(Loads.Lhs, Loads.Rhs);
654 }
655
656 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
657 /*Offset*/ 0);
658
659 // If a user of memcmp cares only about two outcomes, for example:
660 // bool result = memcmp(a, b, NBYTES) > 0;
661 // We can generate more optimal code with a smaller number of operations
662 if (CI->hasOneUser()) {
663 auto *UI = cast<Instruction>(*CI->user_begin());
664 CmpPredicate Pred = ICmpInst::Predicate::BAD_ICMP_PREDICATE;
665 bool NeedsZExt = false;
666 // This is a special case because instead of checking if the result is less
667 // than zero:
668 // bool result = memcmp(a, b, NBYTES) < 0;
669 // Compiler is clever enough to generate the following code:
670 // bool result = memcmp(a, b, NBYTES) >> 31;
671 if (match(UI,
672 m_LShr(m_Value(),
673 m_SpecificInt(CI->getType()->getIntegerBitWidth() - 1)))) {
674 Pred = ICmpInst::ICMP_SLT;
675 NeedsZExt = true;
676 } else if (match(UI, m_SpecificICmp(ICmpInst::ICMP_SGT, m_Specific(CI),
677 m_AllOnes()))) {
678 // Adjust predicate as if it compared with 0.
679 Pred = ICmpInst::ICMP_SGE;
680 } else if (match(UI, m_SpecificICmp(ICmpInst::ICMP_SLT, m_Specific(CI),
681 m_One()))) {
682 // Adjust predicate as if it compared with 0.
683 Pred = ICmpInst::ICMP_SLE;
684 } else {
685 // In case of a successful match this call will set `Pred` variable
686 match(UI, m_ICmp(Pred, m_Specific(CI), m_Zero()));
687 }
688 // Generate new code and remove the original memcmp call and the user
689 if (ICmpInst::isSigned(Pred)) {
691 Loads.Lhs, Loads.Rhs);
692 auto *Result = NeedsZExt ? Builder.CreateZExt(Cmp, UI->getType()) : Cmp;
693 UI->replaceAllUsesWith(Result);
694 UI->eraseFromParent();
695 CI->eraseFromParent();
696 return nullptr;
697 }
698 }
699
700 // The result of memcmp is negative, zero, or positive.
701 return Builder.CreateIntrinsic(Builder.getInt32Ty(), Intrinsic::ucmp,
702 {Loads.Lhs, Loads.Rhs});
703}
704
705// This function expands the memcmp call into an inline expansion and returns
706// the memcmp result. Returns nullptr if the memcmp is already replaced.
707Value *MemCmpExpansion::getMemCmpExpansion() {
708 // Create the basic block framework for a multi-block expansion.
709 if (getNumBlocks() != 1) {
710 BasicBlock *StartBlock = CI->getParent();
711 EndBlock = SplitBlock(StartBlock, CI, DTU, /*LI=*/nullptr,
712 /*MSSAU=*/nullptr, "endblock");
713 setupEndBlockPHINodes();
714 createResultBlock();
715
716 // If return value of memcmp is not used in a zero equality, we need to
717 // calculate which source was larger. The calculation requires the
718 // two loaded source values of each load compare block.
719 // These will be saved in the phi nodes created by setupResultBlockPHINodes.
720 if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
721
722 // Create the number of required load compare basic blocks.
723 createLoadCmpBlocks();
724
725 // Update the terminator added by SplitBlock to branch to the first
726 // LoadCmpBlock.
727 StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
728 if (DTU)
729 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, LoadCmpBlocks[0]},
730 {DominatorTree::Delete, StartBlock, EndBlock}});
731 }
732
734
735 if (IsUsedForZeroCmp)
736 return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
737 : getMemCmpExpansionZeroCase();
738
739 if (getNumBlocks() == 1)
740 return getMemCmpOneBlock();
741
742 for (unsigned I = 0; I < getNumBlocks(); ++I) {
743 emitLoadCompareBlock(I);
744 }
745
746 emitMemCmpResultBlock();
747 return PhiRes;
748}
749
750// This function checks to see if an expansion of memcmp can be generated.
751// It checks for constant compare size that is less than the max inline size.
752// If an expansion cannot occur, returns false to leave as a library call.
753// Otherwise, the library call is replaced with a new IR instruction sequence.
754/// We want to transform:
755/// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
756/// To:
757/// loadbb:
758/// %0 = bitcast i32* %buffer2 to i8*
759/// %1 = bitcast i32* %buffer1 to i8*
760/// %2 = bitcast i8* %1 to i64*
761/// %3 = bitcast i8* %0 to i64*
762/// %4 = load i64, i64* %2
763/// %5 = load i64, i64* %3
764/// %6 = call i64 @llvm.bswap.i64(i64 %4)
765/// %7 = call i64 @llvm.bswap.i64(i64 %5)
766/// %8 = sub i64 %6, %7
767/// %9 = icmp ne i64 %8, 0
768/// br i1 %9, label %res_block, label %loadbb1
769/// res_block: ; preds = %loadbb2,
770/// %loadbb1, %loadbb
771/// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
772/// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
773/// %10 = icmp ult i64 %phi.src1, %phi.src2
774/// %11 = select i1 %10, i32 -1, i32 1
775/// br label %endblock
776/// loadbb1: ; preds = %loadbb
777/// %12 = bitcast i32* %buffer2 to i8*
778/// %13 = bitcast i32* %buffer1 to i8*
779/// %14 = bitcast i8* %13 to i32*
780/// %15 = bitcast i8* %12 to i32*
781/// %16 = getelementptr i32, i32* %14, i32 2
782/// %17 = getelementptr i32, i32* %15, i32 2
783/// %18 = load i32, i32* %16
784/// %19 = load i32, i32* %17
785/// %20 = call i32 @llvm.bswap.i32(i32 %18)
786/// %21 = call i32 @llvm.bswap.i32(i32 %19)
787/// %22 = zext i32 %20 to i64
788/// %23 = zext i32 %21 to i64
789/// %24 = sub i64 %22, %23
790/// %25 = icmp ne i64 %24, 0
791/// br i1 %25, label %res_block, label %loadbb2
792/// loadbb2: ; preds = %loadbb1
793/// %26 = bitcast i32* %buffer2 to i8*
794/// %27 = bitcast i32* %buffer1 to i8*
795/// %28 = bitcast i8* %27 to i16*
796/// %29 = bitcast i8* %26 to i16*
797/// %30 = getelementptr i16, i16* %28, i16 6
798/// %31 = getelementptr i16, i16* %29, i16 6
799/// %32 = load i16, i16* %30
800/// %33 = load i16, i16* %31
801/// %34 = call i16 @llvm.bswap.i16(i16 %32)
802/// %35 = call i16 @llvm.bswap.i16(i16 %33)
803/// %36 = zext i16 %34 to i64
804/// %37 = zext i16 %35 to i64
805/// %38 = sub i64 %36, %37
806/// %39 = icmp ne i64 %38, 0
807/// br i1 %39, label %res_block, label %loadbb3
808/// loadbb3: ; preds = %loadbb2
809/// %40 = bitcast i32* %buffer2 to i8*
810/// %41 = bitcast i32* %buffer1 to i8*
811/// %42 = getelementptr i8, i8* %41, i8 14
812/// %43 = getelementptr i8, i8* %40, i8 14
813/// %44 = load i8, i8* %42
814/// %45 = load i8, i8* %43
815/// %46 = zext i8 %44 to i32
816/// %47 = zext i8 %45 to i32
817/// %48 = sub i32 %46, %47
818/// br label %endblock
819/// endblock: ; preds = %res_block,
820/// %loadbb3
821/// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
822/// ret i32 %phi.res
823static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
824 const DataLayout *DL, ProfileSummaryInfo *PSI,
825 BlockFrequencyInfo *BFI, DomTreeUpdater *DTU,
826 const bool IsBCmp) {
827 NumMemCmpCalls++;
828
829 // Early exit from expansion if -Oz.
830 if (CI->getFunction()->hasMinSize())
831 return false;
832
833 // Early exit from expansion if size is not a constant.
834 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
835 if (!SizeCast) {
836 NumMemCmpNotConstant++;
837 return false;
838 }
839 const uint64_t SizeVal = SizeCast->getZExtValue();
840
841 if (SizeVal == 0) {
842 return false;
843 }
844 // TTI call to check if target would like to expand memcmp. Also, get the
845 // available load sizes.
846 const bool IsUsedForZeroCmp =
848 bool OptForSize = llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
849 auto Options = TTI->enableMemCmpExpansion(OptForSize,
850 IsUsedForZeroCmp);
851 if (!Options) return false;
852
853 if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
855
856 if (OptForSize &&
857 MaxLoadsPerMemcmpOptSize.getNumOccurrences())
858 Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
859
860 if (!OptForSize && MaxLoadsPerMemcmp.getNumOccurrences())
861 Options.MaxNumLoads = MaxLoadsPerMemcmp;
862
863 MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DTU);
864
865 // Don't expand if this will require more loads than desired by the target.
866 if (Expansion.getNumLoads() == 0) {
867 NumMemCmpGreaterThanMax++;
868 return false;
869 }
870
871 NumMemCmpInlined++;
872
873 if (Value *Res = Expansion.getMemCmpExpansion()) {
874 // Replace call with result of expansion and erase call.
875 CI->replaceAllUsesWith(Res);
876 CI->eraseFromParent();
877 }
878
879 return true;
880}
881
882static PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
883 const TargetTransformInfo *TTI,
884 ProfileSummaryInfo *PSI,
885 BlockFrequencyInfo *BFI, DominatorTree *DT) {
886 std::optional<DomTreeUpdater> DTU;
887 if (DT)
888 DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
889
890 const DataLayout& DL = F.getDataLayout();
892 for (Instruction &I : instructions(F)) {
893 if (auto *CI = dyn_cast<CallInst>(&I)) {
894 LibFunc Func;
895 if (TLI->getLibFunc(*CI, Func) &&
896 (Func == LibFunc_memcmp || Func == LibFunc_bcmp))
897 MemCmpCalls.push_back({CI, Func});
898 }
899 }
900
901 bool MadeChanges = false;
902 for (const auto [CI, Func] : MemCmpCalls) {
903 if (expandMemCmp(CI, TTI, &DL, PSI, BFI, DTU ? &*DTU : nullptr,
904 Func == LibFunc_bcmp))
905 MadeChanges = true;
906 }
907
908 if (MadeChanges)
909 for (BasicBlock &BB : F)
911 if (!MadeChanges)
912 return PreservedAnalyses::all();
913 PreservedAnalyses PA;
914 PA.preserve<DominatorTreeAnalysis>();
915 return PA;
916}
917
918} // namespace
919
922 // Don't expand memcmp in sanitized functions — sanitizers intercept memcmp
923 // calls to check for memory errors, and expanding would bypass that.
924 if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
925 F.hasFnAttribute(Attribute::SanitizeMemory) ||
926 F.hasFnAttribute(Attribute::SanitizeThread) ||
927 F.hasFnAttribute(Attribute::SanitizeHWAddress))
928 return PreservedAnalyses::all();
929
930 const auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
931 const auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
932 auto *PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F)
933 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
934 BlockFrequencyInfo *BFI = (PSI && PSI->hasProfileSummary())
935 ? &FAM.getResult<BlockFrequencyAnalysis>(F)
936 : nullptr;
937 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
938
939 return runImpl(F, &TLI, &TTI, PSI, BFI, DT);
940}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
DXIL Intrinsic Expansion
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
static cl::opt< unsigned > MaxLoadsPerMemcmpOptSize("max-loads-per-memcmp-opt-size", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"))
static cl::opt< unsigned > MaxLoadsPerMemcmp("max-loads-per-memcmp", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp"))
static cl::opt< unsigned > MemCmpEqZeroNumLoadsPerBlock("memcmp-num-loads-per-block", cl::Hidden, cl::init(1), cl::desc("The number of loads per basic block for inline expansion of " "memcmp that is only being compared against zero."))
#define DEBUG_TYPE
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This pass exposes codegen information to IR-level passes.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:195
const T & front() const
front - Get the first element.
Definition ArrayRef.h:145
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Value * getArgOperand(unsigned i) const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:711
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:2035
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1918
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1237
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:247
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:586
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:201
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2359
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1231
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2520
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1460
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2101
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2534
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1639
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2465
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1613
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
void push_back(const T &Elt)
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
LLVM_ABI MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
LLVM_ABI unsigned getIntegerBitWidth() const
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:162
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:964
const ParentTy * getParent() const
Definition ilist_node.h:34
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_Value()
Match an arbitrary value and ignore it.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:723
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:385
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
@ Or
Bitwise or logical OR of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.