LLVM 22.0.0git
MergeICmps.cpp
Go to the documentation of this file.
1//===- MergeICmps.cpp - Optimize chains of integer comparisons ------------===//
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 turns chains of integer comparisons into memcmp (the memcmp is
10// later typically inlined as a chain of efficient hardware comparisons). This
11// typically benefits c++ member or nonmember operator==().
12//
13// The basic idea is to replace a longer chain of integer comparisons loaded
14// from contiguous memory locations into a shorter chain of larger integer
15// comparisons. Benefits are double:
16// - There are less jumps, and therefore less opportunities for mispredictions
17// and I-cache misses.
18// - Code size is smaller, both because jumps are removed and because the
19// encoding of a 2*n byte compare is smaller than that of two n-byte
20// compares.
21//
22// Example:
23//
24// struct S {
25// int a;
26// char b;
27// char c;
28// uint16_t d;
29// bool operator==(const S& o) const {
30// return a == o.a && b == o.b && c == o.c && d == o.d;
31// }
32// };
33//
34// Is optimized as :
35//
36// bool S::operator==(const S& o) const {
37// return memcmp(this, &o, 8) == 0;
38// }
39//
40// Which will later be expanded (ExpandMemCmp) as a single 8-bytes icmp.
41//
42//===----------------------------------------------------------------------===//
43
48#include "llvm/Analysis/Loads.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/IRBuilder.h"
56#include "llvm/Pass.h"
60#include <algorithm>
61#include <numeric>
62#include <utility>
63#include <vector>
64
65using namespace llvm;
66
67#define DEBUG_TYPE "mergeicmps"
68
69namespace {
70
71// A BCE atom "Binary Compare Expression Atom" represents an integer load
72// that is a constant offset from a base value, e.g. `a` or `o.c` in the example
73// at the top.
74struct BCEAtom {
75 BCEAtom() = default;
76 BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
77 : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(std::move(Offset)) {}
78
79 BCEAtom(const BCEAtom &) = delete;
80 BCEAtom &operator=(const BCEAtom &) = delete;
81
82 BCEAtom(BCEAtom &&that) = default;
83 BCEAtom &operator=(BCEAtom &&that) {
84 if (this == &that)
85 return *this;
86 GEP = that.GEP;
87 LoadI = that.LoadI;
88 BaseId = that.BaseId;
89 Offset = std::move(that.Offset);
90 return *this;
91 }
92
93 // We want to order BCEAtoms by (Base, Offset). However we cannot use
94 // the pointer values for Base because these are non-deterministic.
95 // To make sure that the sort order is stable, we first assign to each atom
96 // base value an index based on its order of appearance in the chain of
97 // comparisons. We call this index `BaseOrdering`. For example, for:
98 // b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
99 // | block 1 | | block 2 | | block 3 |
100 // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
101 // which is before block 2.
102 // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
103 bool operator<(const BCEAtom &O) const {
104 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
105 }
106
107 GetElementPtrInst *GEP = nullptr;
108 LoadInst *LoadI = nullptr;
109 unsigned BaseId = 0;
111};
112
113// A class that assigns increasing ids to values in the order in which they are
114// seen. See comment in `BCEAtom::operator<()``.
115class BaseIdentifier {
116public:
117 // Returns the id for value `Base`, after assigning one if `Base` has not been
118 // seen before.
119 int getBaseId(const Value *Base) {
120 assert(Base && "invalid base");
121 const auto Insertion = BaseToIndex.try_emplace(Base, Order);
122 if (Insertion.second)
123 ++Order;
124 return Insertion.first->second;
125 }
126
127private:
128 unsigned Order = 1;
129 DenseMap<const Value*, int> BaseToIndex;
130};
131} // namespace
132
133// If this value is a load from a constant offset w.r.t. a base address, and
134// there are no other users of the load or address, returns the base address and
135// the offset.
136static BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
137 auto *const LoadI = dyn_cast<LoadInst>(Val);
138 if (!LoadI)
139 return {};
140 LLVM_DEBUG(dbgs() << "load\n");
141 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
142 LLVM_DEBUG(dbgs() << "used outside of block\n");
143 return {};
144 }
145 // Do not optimize atomic loads to non-atomic memcmp
146 if (!LoadI->isSimple()) {
147 LLVM_DEBUG(dbgs() << "volatile or atomic\n");
148 return {};
149 }
150 Value *Addr = LoadI->getOperand(0);
151 if (Addr->getType()->getPointerAddressSpace() != 0) {
152 LLVM_DEBUG(dbgs() << "from non-zero AddressSpace\n");
153 return {};
154 }
155 const auto &DL = LoadI->getDataLayout();
156 if (!isDereferenceablePointer(Addr, LoadI->getType(), DL)) {
157 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
158 // We need to make sure that we can do comparison in any order, so we
159 // require memory to be unconditionally dereferenceable.
160 return {};
161 }
162
163 APInt Offset = APInt(DL.getIndexTypeSizeInBits(Addr->getType()), 0);
164 Value *Base = Addr;
165 auto *GEP = dyn_cast<GetElementPtrInst>(Addr);
166 if (GEP) {
167 LLVM_DEBUG(dbgs() << "GEP\n");
168 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
169 LLVM_DEBUG(dbgs() << "used outside of block\n");
170 return {};
171 }
172 if (!GEP->accumulateConstantOffset(DL, Offset))
173 return {};
174 Base = GEP->getPointerOperand();
175 }
176 return BCEAtom(GEP, LoadI, BaseId.getBaseId(Base), Offset);
177}
178
179namespace {
180// A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
181// top.
182// Note: the terminology is misleading: the comparison is symmetric, so there
183// is no real {l/r}hs. What we want though is to have the same base on the
184// left (resp. right), so that we can detect consecutive loads. To ensure this
185// we put the smallest atom on the left.
186struct BCECmp {
187 BCEAtom Lhs;
188 BCEAtom Rhs;
189 int SizeBits;
190 const ICmpInst *CmpI;
191
192 BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
193 : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
194 if (Rhs < Lhs) std::swap(Rhs, Lhs);
195 }
196};
197
198// A basic block with a comparison between two BCE atoms.
199// The block might do extra work besides the atom comparison, in which case
200// doesOtherWork() returns true. Under some conditions, the block can be
201// split into the atom comparison part and the "other work" part
202// (see canSplit()).
203class BCECmpBlock {
204 public:
205 typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
206
207 BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
208 : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
209
210 const BCEAtom &Lhs() const { return Cmp.Lhs; }
211 const BCEAtom &Rhs() const { return Cmp.Rhs; }
212 int SizeBits() const { return Cmp.SizeBits; }
213
214 // Returns true if the block does other works besides comparison.
215 bool doesOtherWork() const;
216
217 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
218 // instructions in the block.
219 bool canSplit(AliasAnalysis &AA) const;
220
221 // Return true if this all the relevant instructions in the BCE-cmp-block can
222 // be sunk below this instruction. By doing this, we know we can separate the
223 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
224 // block.
225 bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const;
226
227 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
228 // instructions. Split the old block and move all non-BCE-cmp-insts into the
229 // new parent block.
230 void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
231
232 // The basic block where this comparison happens.
233 BasicBlock *BB;
234 // Instructions relating to the BCECmp and branch.
235 InstructionSet BlockInsts;
236 // The block requires splitting.
237 bool RequireSplit = false;
238 // Original order of this block in the chain.
239 unsigned OrigOrder = 0;
240
241private:
242 BCECmp Cmp;
243};
244} // namespace
245
246bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
247 AliasAnalysis &AA) const {
248 // If this instruction may clobber the loads and is in middle of the BCE cmp
249 // block instructions, then bail for now.
250 if (Inst->mayWriteToMemory()) {
251 auto MayClobber = [&](LoadInst *LI) {
252 // If a potentially clobbering instruction comes before the load,
253 // we can still safely sink the load.
254 return (Inst->getParent() != LI->getParent() || !Inst->comesBefore(LI)) &&
256 };
257 if (MayClobber(Cmp.Lhs.LoadI) || MayClobber(Cmp.Rhs.LoadI))
258 return false;
259 }
260 // Make sure this instruction does not use any of the BCE cmp block
261 // instructions as operand.
262 return llvm::none_of(Inst->operands(), [&](const Value *Op) {
263 const Instruction *OpI = dyn_cast<Instruction>(Op);
264 return OpI && BlockInsts.contains(OpI);
265 });
266}
267
268void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
269 llvm::SmallVector<Instruction *, 4> OtherInsts;
270 for (Instruction &Inst : *BB) {
271 if (BlockInsts.count(&Inst))
272 continue;
273 assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block");
274 // This is a non-BCE-cmp-block instruction. And it can be separated
275 // from the BCE-cmp-block instruction.
276 OtherInsts.push_back(&Inst);
277 }
278
279 // Do the actual spliting.
280 for (Instruction *Inst : reverse(OtherInsts))
281 Inst->moveBeforePreserving(*NewParent, NewParent->begin());
282}
283
284bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
285 for (Instruction &Inst : *BB) {
286 if (!BlockInsts.count(&Inst)) {
287 if (!canSinkBCECmpInst(&Inst, AA))
288 return false;
289 }
290 }
291 return true;
292}
293
294bool BCECmpBlock::doesOtherWork() const {
295 // TODO(courbet): Can we allow some other things ? This is very conservative.
296 // We might be able to get away with anything does not have any side
297 // effects outside of the basic block.
298 // Note: The GEPs and/or loads are not necessarily in the same block.
299 for (const Instruction &Inst : *BB) {
300 if (!BlockInsts.count(&Inst))
301 return true;
302 }
303 return false;
304}
305
306// Visit the given comparison. If this is a comparison between two valid
307// BCE atoms, returns the comparison.
308static std::optional<BCECmp>
309visitICmp(const ICmpInst *const CmpI,
310 const ICmpInst::Predicate ExpectedPredicate, BaseIdentifier &BaseId) {
311 // The comparison can only be used once:
312 // - For intermediate blocks, as a branch condition.
313 // - For the final block, as an incoming value for the Phi.
314 // If there are any other uses of the comparison, we cannot merge it with
315 // other comparisons as we would create an orphan use of the value.
316 if (!CmpI->hasOneUse()) {
317 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
318 return std::nullopt;
319 }
320 if (CmpI->getPredicate() != ExpectedPredicate)
321 return std::nullopt;
322 LLVM_DEBUG(dbgs() << "cmp "
323 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
324 << "\n");
325 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
326 if (!Lhs.BaseId)
327 return std::nullopt;
328 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
329 if (!Rhs.BaseId)
330 return std::nullopt;
331 const auto &DL = CmpI->getDataLayout();
332 return BCECmp(std::move(Lhs), std::move(Rhs),
333 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
334}
335
336// Visit the given comparison block. If this is a comparison between two valid
337// BCE atoms, returns the comparison.
338static std::optional<BCECmpBlock>
340 const BasicBlock *const PhiBlock, BaseIdentifier &BaseId) {
341 if (Block->empty())
342 return std::nullopt;
343 auto *const BranchI = dyn_cast<BranchInst>(Block->getTerminator());
344 if (!BranchI)
345 return std::nullopt;
346 LLVM_DEBUG(dbgs() << "branch\n");
347 Value *Cond;
348 ICmpInst::Predicate ExpectedPredicate;
349 if (BranchI->isUnconditional()) {
350 // In this case, we expect an incoming value which is the result of the
351 // comparison. This is the last link in the chain of comparisons (note
352 // that this does not mean that this is the last incoming value, blocks
353 // can be reordered).
354 Cond = Val;
355 ExpectedPredicate = ICmpInst::ICMP_EQ;
356 } else {
357 // In this case, we expect a constant incoming value (the comparison is
358 // chained).
359 const auto *const Const = cast<ConstantInt>(Val);
360 LLVM_DEBUG(dbgs() << "const\n");
361 if (!Const->isZero())
362 return std::nullopt;
363 LLVM_DEBUG(dbgs() << "false\n");
364 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
365 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
366 Cond = BranchI->getCondition();
367 ExpectedPredicate =
368 FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
369 }
370
371 auto *CmpI = dyn_cast<ICmpInst>(Cond);
372 if (!CmpI)
373 return std::nullopt;
374 LLVM_DEBUG(dbgs() << "icmp\n");
375
376 std::optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
377 if (!Result)
378 return std::nullopt;
379
380 BCECmpBlock::InstructionSet BlockInsts(
381 {Result->Lhs.LoadI, Result->Rhs.LoadI, Result->CmpI, BranchI});
382 if (Result->Lhs.GEP)
383 BlockInsts.insert(Result->Lhs.GEP);
384 if (Result->Rhs.GEP)
385 BlockInsts.insert(Result->Rhs.GEP);
386 return BCECmpBlock(std::move(*Result), Block, BlockInsts);
387}
388
389static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
390 BCECmpBlock &&Comparison) {
391 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
392 << "': Found cmp of " << Comparison.SizeBits()
393 << " bits between " << Comparison.Lhs().BaseId << " + "
394 << Comparison.Lhs().Offset << " and "
395 << Comparison.Rhs().BaseId << " + "
396 << Comparison.Rhs().Offset << "\n");
397 LLVM_DEBUG(dbgs() << "\n");
398 Comparison.OrigOrder = Comparisons.size();
399 Comparisons.push_back(std::move(Comparison));
400}
401
402namespace {
403// A chain of comparisons.
404class BCECmpChain {
405public:
406 using ContiguousBlocks = std::vector<BCECmpBlock>;
407
408 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
409 AliasAnalysis &AA);
410
411 bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
412 DomTreeUpdater &DTU);
413
414 bool atLeastOneMerged() const {
415 return any_of(MergedBlocks_,
416 [](const auto &Blocks) { return Blocks.size() > 1; });
417 }
418
419private:
420 PHINode &Phi_;
421 // The list of all blocks in the chain, grouped by contiguity.
422 std::vector<ContiguousBlocks> MergedBlocks_;
423 // The original entry block (before sorting);
424 BasicBlock *EntryBlock_;
425};
426} // namespace
427
428static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second) {
429 return First.Lhs().BaseId == Second.Lhs().BaseId &&
430 First.Rhs().BaseId == Second.Rhs().BaseId &&
431 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
432 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
433}
434
435static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks) {
436 unsigned MinOrigOrder = std::numeric_limits<unsigned>::max();
437 for (const BCECmpBlock &Block : Blocks)
438 MinOrigOrder = std::min(MinOrigOrder, Block.OrigOrder);
439 return MinOrigOrder;
440}
441
442/// Given a chain of comparison blocks, groups the blocks into contiguous
443/// ranges that can be merged together into a single comparison.
444static std::vector<BCECmpChain::ContiguousBlocks>
445mergeBlocks(std::vector<BCECmpBlock> &&Blocks) {
446 std::vector<BCECmpChain::ContiguousBlocks> MergedBlocks;
447
448 // Sort to detect continuous offsets.
449 llvm::sort(Blocks,
450 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
451 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
452 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
453 });
454
455 BCECmpChain::ContiguousBlocks *LastMergedBlock = nullptr;
456 for (BCECmpBlock &Block : Blocks) {
457 if (!LastMergedBlock || !areContiguous(LastMergedBlock->back(), Block)) {
458 MergedBlocks.emplace_back();
459 LastMergedBlock = &MergedBlocks.back();
460 } else {
461 LLVM_DEBUG(dbgs() << "Merging block " << Block.BB->getName() << " into "
462 << LastMergedBlock->back().BB->getName() << "\n");
463 }
464 LastMergedBlock->push_back(std::move(Block));
465 }
466
467 // While we allow reordering for merging, do not reorder unmerged comparisons.
468 // Doing so may introduce branch on poison.
469 llvm::sort(MergedBlocks, [](const BCECmpChain::ContiguousBlocks &LhsBlocks,
470 const BCECmpChain::ContiguousBlocks &RhsBlocks) {
471 return getMinOrigOrder(LhsBlocks) < getMinOrigOrder(RhsBlocks);
472 });
473
474 return MergedBlocks;
475}
476
477BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
478 AliasAnalysis &AA)
479 : Phi_(Phi) {
480 assert(!Blocks.empty() && "a chain should have at least one block");
481 // Now look inside blocks to check for BCE comparisons.
482 std::vector<BCECmpBlock> Comparisons;
483 BaseIdentifier BaseId;
484 for (BasicBlock *const Block : Blocks) {
485 assert(Block && "invalid block");
486 if (Block->hasAddressTaken()) {
487 LLVM_DEBUG(dbgs() << "cannot merge blocks with blockaddress\n");
488 return;
489 }
490 std::optional<BCECmpBlock> Comparison = visitCmpBlock(
491 Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
492 if (!Comparison) {
493 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
494 return;
495 }
496 if (Comparison->doesOtherWork()) {
497 LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
498 << "' does extra work besides compare\n");
499 if (Comparisons.empty()) {
500 // This is the initial block in the chain, in case this block does other
501 // work, we can try to split the block and move the irrelevant
502 // instructions to the predecessor.
503 //
504 // If this is not the initial block in the chain, splitting it wont
505 // work.
506 //
507 // As once split, there will still be instructions before the BCE cmp
508 // instructions that do other work in program order, i.e. within the
509 // chain before sorting. Unless we can abort the chain at this point
510 // and start anew.
511 //
512 // NOTE: we only handle blocks a with single predecessor for now.
513 if (Comparison->canSplit(AA)) {
515 << "Split initial block '" << Comparison->BB->getName()
516 << "' that does extra work besides compare\n");
517 Comparison->RequireSplit = true;
518 enqueueBlock(Comparisons, std::move(*Comparison));
519 } else {
521 << "ignoring initial block '" << Comparison->BB->getName()
522 << "' that does extra work besides compare\n");
523 }
524 continue;
525 }
526 // TODO(courbet): Right now we abort the whole chain. We could be
527 // merging only the blocks that don't do other work and resume the
528 // chain from there. For example:
529 // if (a[0] == b[0]) { // bb1
530 // if (a[1] == b[1]) { // bb2
531 // some_value = 3; //bb3
532 // if (a[2] == b[2]) { //bb3
533 // do a ton of stuff //bb4
534 // }
535 // }
536 // }
537 //
538 // This is:
539 //
540 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
541 // \ \ \ \
542 // ne ne ne \
543 // \ \ \ v
544 // +------------+-----------+----------> bb_phi
545 //
546 // We can only merge the first two comparisons, because bb3* does
547 // "other work" (setting some_value to 3).
548 // We could still merge bb1 and bb2 though.
549 return;
550 }
551 enqueueBlock(Comparisons, std::move(*Comparison));
552 }
553
554 // It is possible we have no suitable comparison to merge.
555 if (Comparisons.empty()) {
556 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
557 return;
558 }
559 EntryBlock_ = Comparisons[0].BB;
560 MergedBlocks_ = mergeBlocks(std::move(Comparisons));
561}
562
563namespace {
564
565// A class to compute the name of a set of merged basic blocks.
566// This is optimized for the common case of no block names.
567class MergedBlockName {
568 // Storage for the uncommon case of several named blocks.
569 SmallString<16> Scratch;
570
571public:
572 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
573 : Name(makeName(Comparisons)) {}
574 const StringRef Name;
575
576private:
577 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
578 assert(!Comparisons.empty() && "no basic block");
579 // Fast path: only one block, or no names at all.
580 if (Comparisons.size() == 1)
581 return Comparisons[0].BB->getName();
582 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
583 [](int i, const BCECmpBlock &Cmp) {
584 return i + Cmp.BB->getName().size();
585 });
586 if (size == 0)
587 return StringRef("", 0);
588
589 // Slow path: at least two blocks, at least one block with a name.
590 Scratch.clear();
591 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
592 // separators.
593 Scratch.reserve(size + Comparisons.size() - 1);
594 const auto append = [this](StringRef str) {
595 Scratch.append(str.begin(), str.end());
596 };
597 append(Comparisons[0].BB->getName());
598 for (int I = 1, E = Comparisons.size(); I < E; ++I) {
599 const BasicBlock *const BB = Comparisons[I].BB;
600 if (!BB->getName().empty()) {
601 append("+");
602 append(BB->getName());
603 }
604 }
605 return Scratch.str();
606 }
607};
608} // namespace
609
610// Merges the given contiguous comparison blocks into one memcmp block.
612 BasicBlock *const InsertBefore,
613 BasicBlock *const NextCmpBlock,
614 PHINode &Phi, const TargetLibraryInfo &TLI,
616 assert(!Comparisons.empty() && "merging zero comparisons");
617 LLVMContext &Context = NextCmpBlock->getContext();
618 const BCECmpBlock &FirstCmp = Comparisons[0];
619
620 // Create a new cmp block before next cmp block.
621 BasicBlock *const BB =
622 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
623 NextCmpBlock->getParent(), InsertBefore);
624 IRBuilder<> Builder(BB);
625 // Add the GEPs from the first BCECmpBlock.
626 Value *Lhs, *Rhs;
627 if (FirstCmp.Lhs().GEP)
628 Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
629 else
630 Lhs = FirstCmp.Lhs().LoadI->getPointerOperand();
631 if (FirstCmp.Rhs().GEP)
632 Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
633 else
634 Rhs = FirstCmp.Rhs().LoadI->getPointerOperand();
635
636 Value *IsEqual = nullptr;
637 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
638 << BB->getName() << "\n");
639
640 // If there is one block that requires splitting, we do it now, i.e.
641 // just before we know we will collapse the chain. The instructions
642 // can be executed before any of the instructions in the chain.
643 const auto ToSplit = llvm::find_if(
644 Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
645 if (ToSplit != Comparisons.end()) {
646 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
647 ToSplit->split(BB, AA);
648 }
649
650 if (Comparisons.size() == 1) {
651 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
652 // Use clone to keep the metadata
653 Instruction *const LhsLoad = Builder.Insert(FirstCmp.Lhs().LoadI->clone());
654 Instruction *const RhsLoad = Builder.Insert(FirstCmp.Rhs().LoadI->clone());
655 LhsLoad->replaceUsesOfWith(LhsLoad->getOperand(0), Lhs);
656 RhsLoad->replaceUsesOfWith(RhsLoad->getOperand(0), Rhs);
657 // There are no blocks to merge, just do the comparison.
658 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
659 } else {
660 const unsigned TotalSizeBits = std::accumulate(
661 Comparisons.begin(), Comparisons.end(), 0u,
662 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
663
664 // memcmp expects a 'size_t' argument and returns 'int'.
665 unsigned SizeTBits = TLI.getSizeTSize(*Phi.getModule());
666 unsigned IntBits = TLI.getIntSize();
667
668 // Create memcmp() == 0.
669 const auto &DL = Phi.getDataLayout();
670 Value *const MemCmpCall = emitMemCmp(
671 Lhs, Rhs,
672 ConstantInt::get(Builder.getIntNTy(SizeTBits), TotalSizeBits / 8),
673 Builder, DL, &TLI);
674 IsEqual = Builder.CreateICmpEQ(
675 MemCmpCall, ConstantInt::get(Builder.getIntNTy(IntBits), 0));
676 }
677
678 BasicBlock *const PhiBB = Phi.getParent();
679 // Add a branch to the next basic block in the chain.
680 if (NextCmpBlock == PhiBB) {
681 // Continue to phi, passing it the comparison result.
682 Builder.CreateBr(PhiBB);
683 Phi.addIncoming(IsEqual, BB);
684 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
685 } else {
686 // Continue to next block if equal, exit to phi else.
687 Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
688 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
689 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
690 {DominatorTree::Insert, BB, PhiBB}});
691 }
692 return BB;
693}
694
695bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
696 DomTreeUpdater &DTU) {
697 assert(atLeastOneMerged() && "simplifying trivial BCECmpChain");
698 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
699 << EntryBlock_->getName() << "\n");
700
701 // Effectively merge blocks. We go in the reverse direction from the phi block
702 // so that the next block is always available to branch to.
703 BasicBlock *InsertBefore = EntryBlock_;
704 BasicBlock *NextCmpBlock = Phi_.getParent();
705 for (const auto &Blocks : reverse(MergedBlocks_)) {
706 InsertBefore = NextCmpBlock = mergeComparisons(
707 Blocks, InsertBefore, NextCmpBlock, Phi_, TLI, AA, DTU);
708 }
709
710 // Replace the original cmp chain with the new cmp chain by pointing all
711 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
712 // blocks in the old chain unreachable.
713 while (!pred_empty(EntryBlock_)) {
714 BasicBlock* const Pred = *pred_begin(EntryBlock_);
715 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
716 << "\n");
717 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
718 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
719 {DominatorTree::Insert, Pred, NextCmpBlock}});
720 }
721
722 // If the old cmp chain was the function entry, we need to update the function
723 // entry.
724 const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
725 if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
726 LLVM_DEBUG(dbgs() << "Changing function entry from "
727 << EntryBlock_->getName() << " to "
728 << NextCmpBlock->getName() << "\n");
729 DTU.getDomTree().setNewRoot(NextCmpBlock);
730 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
731 }
732 EntryBlock_ = nullptr;
733
734 // Delete merged blocks. This also removes incoming values in phi.
735 SmallVector<BasicBlock *, 16> DeadBlocks;
736 for (const auto &Blocks : MergedBlocks_) {
737 for (const BCECmpBlock &Block : Blocks) {
738 LLVM_DEBUG(dbgs() << "Deleting merged block " << Block.BB->getName()
739 << "\n");
740 DeadBlocks.push_back(Block.BB);
741 }
742 }
743 DeleteDeadBlocks(DeadBlocks, &DTU);
744
745 MergedBlocks_.clear();
746 return true;
747}
748
749static std::vector<BasicBlock *>
750getOrderedBlocks(PHINode &Phi, BasicBlock *const LastBlock, int NumBlocks) {
751 // Walk up from the last block to find other blocks.
752 std::vector<BasicBlock *> Blocks(NumBlocks);
753 assert(LastBlock && "invalid last block");
754 BasicBlock *CurBlock = LastBlock;
755 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
756 if (CurBlock->hasAddressTaken()) {
757 // Somebody is jumping to the block through an address, all bets are
758 // off.
759 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
760 << " has its address taken\n");
761 return {};
762 }
763 Blocks[BlockIndex] = CurBlock;
764 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
765 if (!SinglePredecessor) {
766 // The block has two or more predecessors.
767 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
768 << " has two or more predecessors\n");
769 return {};
770 }
771 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
772 // The block does not link back to the phi.
773 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
774 << " does not link back to the phi\n");
775 return {};
776 }
777 CurBlock = SinglePredecessor;
778 }
779 Blocks[0] = CurBlock;
780 return Blocks;
781}
782
783static bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI,
785 LLVM_DEBUG(dbgs() << "processPhi()\n");
786 if (Phi.getNumIncomingValues() <= 1) {
787 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
788 return false;
789 }
790 // We are looking for something that has the following structure:
791 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
792 // \ \ \ \
793 // ne ne ne \
794 // \ \ \ v
795 // +------------+-----------+----------> bb_phi
796 //
797 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
798 // It's the only block that contributes a non-constant value to the Phi.
799 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
800 // them being the phi block.
801 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
802 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
803
804 // The blocks are not necessarily ordered in the phi, so we start from the
805 // last block and reconstruct the order.
806 BasicBlock *LastBlock = nullptr;
807 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
808 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
809 if (LastBlock) {
810 // There are several non-constant values.
811 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
812 return false;
813 }
814 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
815 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
816 Phi.getIncomingBlock(I)) {
817 // Non-constant incoming value is not from a cmp instruction or not
818 // produced by the last block. We could end up processing the value
819 // producing block more than once.
820 //
821 // This is an uncommon case, so we bail.
823 dbgs()
824 << "skip: non-constant value not from cmp or not from last block.\n");
825 return false;
826 }
827 LastBlock = Phi.getIncomingBlock(I);
828 }
829 if (!LastBlock) {
830 // There is no non-constant block.
831 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
832 return false;
833 }
834 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
835 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
836 return false;
837 }
838
839 const auto Blocks =
840 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
841 if (Blocks.empty()) return false;
842 BCECmpChain CmpChain(Blocks, Phi, AA);
843
844 if (!CmpChain.atLeastOneMerged()) {
845 LLVM_DEBUG(dbgs() << "skip: nothing merged\n");
846 return false;
847 }
848
849 return CmpChain.simplify(TLI, AA, DTU);
850}
851
852static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
854 DominatorTree *DT) {
855 LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
856
857 // We only try merging comparisons if the target wants to expand memcmp later.
858 // The rationale is to avoid turning small chains into memcmp calls.
859 if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
860 return false;
861
862 // If we don't have memcmp avaiable we can't emit calls to it.
863 if (!TLI.has(LibFunc_memcmp))
864 return false;
865
866 DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
867 DomTreeUpdater::UpdateStrategy::Eager);
868
869 bool MadeChange = false;
870
871 for (BasicBlock &BB : llvm::drop_begin(F)) {
872 // A Phi operation is always first in a basic block.
873 if (auto *const Phi = dyn_cast<PHINode>(&*BB.begin()))
874 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
875 }
876
877 return MadeChange;
878}
879
880namespace {
881class MergeICmpsLegacyPass : public FunctionPass {
882public:
883 static char ID;
884
885 MergeICmpsLegacyPass() : FunctionPass(ID) {
887 }
888
889 bool runOnFunction(Function &F) override {
890 if (skipFunction(F)) return false;
891 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
892 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
893 // MergeICmps does not need the DominatorTree, but we update it if it's
894 // already available.
895 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
896 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
897 return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
898 }
899
900 private:
901 void getAnalysisUsage(AnalysisUsage &AU) const override {
902 AU.addRequired<TargetLibraryInfoWrapperPass>();
903 AU.addRequired<TargetTransformInfoWrapperPass>();
904 AU.addRequired<AAResultsWrapperPass>();
905 AU.addPreserved<GlobalsAAWrapperPass>();
906 AU.addPreserved<DominatorTreeWrapperPass>();
907 }
908};
909
910} // namespace
911
912char MergeICmpsLegacyPass::ID = 0;
913INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
914 "Merge contiguous icmps into a memcmp", false, false)
918INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
919 "Merge contiguous icmps into a memcmp", false, false)
920
921Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
922
925 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
926 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
927 auto &AA = AM.getResult<AAManager>(F);
929 const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
930 if (!MadeChanges)
931 return PreservedAnalyses::all();
934 return PA;
935}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
static bool runImpl(Function &F, const TargetLowering &TLI, AssumptionCache *AC)
Definition ExpandFp.cpp:993
This is the interface for a simple mod/ref and alias analysis over globals.
hexagon bit simplify
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static void enqueueBlock(std::vector< BCECmpBlock > &Comparisons, BCECmpBlock &&Comparison)
static std::vector< BCECmpChain::ContiguousBlocks > mergeBlocks(std::vector< BCECmpBlock > &&Blocks)
Given a chain of comparison blocks, groups the blocks into contiguous ranges that can be merged toget...
static std::optional< BCECmpBlock > visitCmpBlock(Value *const Val, BasicBlock *const Block, const BasicBlock *const PhiBlock, BaseIdentifier &BaseId)
static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second)
static std::vector< BasicBlock * > getOrderedBlocks(PHINode &Phi, BasicBlock *const LastBlock, int NumBlocks)
static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks)
static BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId)
static std::optional< BCECmp > visitICmp(const ICmpInst *const CmpI, const ICmpInst::Predicate ExpectedPredicate, BaseIdentifier &BaseId)
static BasicBlock * mergeComparisons(ArrayRef< BCECmpBlock > Comparisons, BasicBlock *const InsertBefore, BasicBlock *const NextCmpBlock, PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA, DomTreeUpdater &DTU)
static bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI, AliasAnalysis &AA, DomTreeUpdater &DTU)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallString class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition APInt.h:78
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
iterator end() const
Definition ArrayRef.h:136
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:142
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:690
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_NE
not equal
Definition InstrTypes.h:698
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:765
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
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)
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
unsigned getSizeTSize(const Module &M) const
Returns the size of the size_t type in bits.
unsigned getIntSize() const
Get size of a C-level int or unsigned int, in bits.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
op_range operands()
Definition User.h:292
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
const ParentTy * getParent() const
Definition ilist_node.h:34
Abstract Attribute helper functions.
Definition Attributor.h:165
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:456
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:477
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:362
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1655
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
LLVM_ABI Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilderBase &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
LLVM_ABI Pass * createMergeICmpsLegacyPass()
TargetTransformInfo TTI
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
Definition Loads.cpp:249
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1758
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:119
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI void initializeMergeICmpsLegacyPassPass(PassRegistry &)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:869
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)