LLVM 23.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/IRBuilder.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/Pass.h"
61#include <algorithm>
62#include <numeric>
63#include <utility>
64#include <vector>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "mergeicmps"
69
70namespace llvm {
72} // namespace llvm
73namespace {
74
75// A BCE atom "Binary Compare Expression Atom" represents an integer load
76// that is a constant offset from a base value, e.g. `a` or `o.c` in the example
77// at the top.
78struct BCEAtom {
79 BCEAtom() = default;
80 BCEAtom(GetElementPtrInst *GEP, LoadInst *LoadI, int BaseId, APInt Offset)
81 : GEP(GEP), LoadI(LoadI), BaseId(BaseId), Offset(std::move(Offset)) {}
82
83 BCEAtom(const BCEAtom &) = delete;
84 BCEAtom &operator=(const BCEAtom &) = delete;
85
86 BCEAtom(BCEAtom &&that) = default;
87 BCEAtom &operator=(BCEAtom &&that) {
88 if (this == &that)
89 return *this;
90 GEP = that.GEP;
91 LoadI = that.LoadI;
92 BaseId = that.BaseId;
93 Offset = std::move(that.Offset);
94 return *this;
95 }
96
97 // We want to order BCEAtoms by (Base, Offset). However we cannot use
98 // the pointer values for Base because these are non-deterministic.
99 // To make sure that the sort order is stable, we first assign to each atom
100 // base value an index based on its order of appearance in the chain of
101 // comparisons. We call this index `BaseOrdering`. For example, for:
102 // b[3] == c[2] && a[1] == d[1] && b[4] == c[3]
103 // | block 1 | | block 2 | | block 3 |
104 // b gets assigned index 0 and a index 1, because b appears as LHS in block 1,
105 // which is before block 2.
106 // We then sort by (BaseOrdering[LHS.Base()], LHS.Offset), which is stable.
107 bool operator<(const BCEAtom &O) const {
108 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.slt(O.Offset);
109 }
110
111 GetElementPtrInst *GEP = nullptr;
112 LoadInst *LoadI = nullptr;
113 unsigned BaseId = 0;
114 APInt Offset;
115};
116
117// A class that assigns increasing ids to values in the order in which they are
118// seen. See comment in `BCEAtom::operator<()``.
119class BaseIdentifier {
120public:
121 // Returns the id for value `Base`, after assigning one if `Base` has not been
122 // seen before.
123 int getBaseId(const Value *Base) {
124 assert(Base && "invalid base");
125 const auto Insertion = BaseToIndex.try_emplace(Base, Order);
126 if (Insertion.second)
127 ++Order;
128 return Insertion.first->second;
129 }
130
131private:
132 unsigned Order = 1;
133 DenseMap<const Value*, int> BaseToIndex;
134};
135} // namespace
136
137// If this value is a load from a constant offset w.r.t. a base address, and
138// there are no other users of the load or address, returns the base address and
139// the offset.
140static BCEAtom visitICmpLoadOperand(Value *const Val, BaseIdentifier &BaseId) {
141 auto *const LoadI = dyn_cast<LoadInst>(Val);
142 if (!LoadI)
143 return {};
144 LLVM_DEBUG(dbgs() << "load\n");
145 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
146 LLVM_DEBUG(dbgs() << "used outside of block\n");
147 return {};
148 }
149 // Do not optimize atomic loads to non-atomic memcmp
150 if (!LoadI->isSimple()) {
151 LLVM_DEBUG(dbgs() << "volatile or atomic\n");
152 return {};
153 }
154 Value *Addr = LoadI->getOperand(0);
155 if (Addr->getType()->getPointerAddressSpace() != 0) {
156 LLVM_DEBUG(dbgs() << "from non-zero AddressSpace\n");
157 return {};
158 }
159 const auto &DL = LoadI->getDataLayout();
160 if (!isDereferenceablePointer(Addr, LoadI->getType(), DL)) {
161 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
162 // We need to make sure that we can do comparison in any order, so we
163 // require memory to be unconditionally dereferenceable.
164 return {};
165 }
166
167 APInt Offset = APInt(DL.getIndexTypeSizeInBits(Addr->getType()), 0);
168 Value *Base = Addr;
169 auto *GEP = dyn_cast<GetElementPtrInst>(Addr);
170 if (GEP) {
171 LLVM_DEBUG(dbgs() << "GEP\n");
172 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
173 LLVM_DEBUG(dbgs() << "used outside of block\n");
174 return {};
175 }
176 if (!GEP->accumulateConstantOffset(DL, Offset))
177 return {};
178 Base = GEP->getPointerOperand();
179 }
180 return BCEAtom(GEP, LoadI, BaseId.getBaseId(Base), Offset);
181}
182
183namespace {
184// A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
185// top.
186// Note: the terminology is misleading: the comparison is symmetric, so there
187// is no real {l/r}hs. What we want though is to have the same base on the
188// left (resp. right), so that we can detect consecutive loads. To ensure this
189// we put the smallest atom on the left.
190struct BCECmp {
191 BCEAtom Lhs;
192 BCEAtom Rhs;
193 int SizeBits;
194 const ICmpInst *CmpI;
195
196 BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
197 : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
198 if (Rhs < Lhs) std::swap(Rhs, Lhs);
199 }
200};
201
202// A basic block with a comparison between two BCE atoms.
203// The block might do extra work besides the atom comparison, in which case
204// doesOtherWork() returns true. Under some conditions, the block can be
205// split into the atom comparison part and the "other work" part
206// (see canSplit()).
207class BCECmpBlock {
208 public:
209 typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
210
211 BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
212 : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
213
214 const BCEAtom &Lhs() const { return Cmp.Lhs; }
215 const BCEAtom &Rhs() const { return Cmp.Rhs; }
216 int SizeBits() const { return Cmp.SizeBits; }
217
218 // Returns true if the block does other works besides comparison.
219 bool doesOtherWork() const;
220
221 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
222 // instructions in the block.
223 bool canSplit(AliasAnalysis &AA) const;
224
225 // Return true if this all the relevant instructions in the BCE-cmp-block can
226 // be sunk below this instruction. By doing this, we know we can separate the
227 // BCE-cmp-block instructions from the non-BCE-cmp-block instructions in the
228 // block.
229 bool canSinkBCECmpInst(const Instruction *, AliasAnalysis &AA) const;
230
231 // We can separate the BCE-cmp-block instructions and the non-BCE-cmp-block
232 // instructions. Split the old block and move all non-BCE-cmp-insts into the
233 // new parent block.
234 void split(BasicBlock *NewParent, AliasAnalysis &AA) const;
235
236 // The basic block where this comparison happens.
237 BasicBlock *BB;
238 // Instructions relating to the BCECmp and branch.
239 InstructionSet BlockInsts;
240 // The block requires splitting.
241 bool RequireSplit = false;
242 // Original order of this block in the chain.
243 unsigned OrigOrder = 0;
244
245private:
246 BCECmp Cmp;
247};
248} // namespace
249
250bool BCECmpBlock::canSinkBCECmpInst(const Instruction *Inst,
251 AliasAnalysis &AA) const {
252 // If this instruction may clobber the loads and is in middle of the BCE cmp
253 // block instructions, then bail for now.
254 if (Inst->mayWriteToMemory()) {
255 auto MayClobber = [&](LoadInst *LI) {
256 // If a potentially clobbering instruction comes before the load,
257 // we can still safely sink the load.
258 return (Inst->getParent() != LI->getParent() || !Inst->comesBefore(LI)) &&
260 };
261 if (MayClobber(Cmp.Lhs.LoadI) || MayClobber(Cmp.Rhs.LoadI))
262 return false;
263 }
264 // Make sure this instruction does not use any of the BCE cmp block
265 // instructions as operand.
266 return llvm::none_of(Inst->operands(), [&](const Value *Op) {
267 const Instruction *OpI = dyn_cast<Instruction>(Op);
268 return OpI && BlockInsts.contains(OpI);
269 });
270}
271
272void BCECmpBlock::split(BasicBlock *NewParent, AliasAnalysis &AA) const {
273 llvm::SmallVector<Instruction *, 4> OtherInsts;
274 for (Instruction &Inst : *BB) {
275 if (BlockInsts.count(&Inst))
276 continue;
277 assert(canSinkBCECmpInst(&Inst, AA) && "Split unsplittable block");
278 // This is a non-BCE-cmp-block instruction. And it can be separated
279 // from the BCE-cmp-block instruction.
280 OtherInsts.push_back(&Inst);
281 }
282
283 // Do the actual spliting.
284 for (Instruction *Inst : reverse(OtherInsts))
285 Inst->moveBeforePreserving(*NewParent, NewParent->begin());
286}
287
288bool BCECmpBlock::canSplit(AliasAnalysis &AA) const {
289 for (Instruction &Inst : *BB) {
290 if (!BlockInsts.count(&Inst)) {
291 if (!canSinkBCECmpInst(&Inst, AA))
292 return false;
293 }
294 }
295 return true;
296}
297
298bool BCECmpBlock::doesOtherWork() const {
299 // TODO(courbet): Can we allow some other things ? This is very conservative.
300 // We might be able to get away with anything does not have any side
301 // effects outside of the basic block.
302 // Note: The GEPs and/or loads are not necessarily in the same block.
303 for (const Instruction &Inst : *BB) {
304 if (!BlockInsts.count(&Inst))
305 return true;
306 }
307 return false;
308}
309
310// Visit the given comparison. If this is a comparison between two valid
311// BCE atoms, returns the comparison.
312static std::optional<BCECmp>
313visitICmp(const ICmpInst *const CmpI,
314 const ICmpInst::Predicate ExpectedPredicate, BaseIdentifier &BaseId) {
315 // The comparison can only be used once:
316 // - For intermediate blocks, as a branch condition.
317 // - For the final block, as an incoming value for the Phi.
318 // If there are any other uses of the comparison, we cannot merge it with
319 // other comparisons as we would create an orphan use of the value.
320 if (!CmpI->hasOneUse()) {
321 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
322 return std::nullopt;
323 }
324 if (CmpI->getPredicate() != ExpectedPredicate)
325 return std::nullopt;
326 LLVM_DEBUG(dbgs() << "cmp "
327 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
328 << "\n");
329 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
330 if (!Lhs.BaseId)
331 return std::nullopt;
332 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
333 if (!Rhs.BaseId)
334 return std::nullopt;
335 const auto &DL = CmpI->getDataLayout();
336 return BCECmp(std::move(Lhs), std::move(Rhs),
337 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
338}
339
340// Visit the given comparison block. If this is a comparison between two valid
341// BCE atoms, returns the comparison.
342static std::optional<BCECmpBlock>
344 const BasicBlock *const PhiBlock, BaseIdentifier &BaseId) {
345 if (Block->empty())
346 return std::nullopt;
347 auto *Term = Block->getTerminator();
348 Value *Cond;
349 ICmpInst::Predicate ExpectedPredicate;
350 if (isa<UncondBrInst>(Term)) {
351 // In this case, we expect an incoming value which is the result of the
352 // comparison. This is the last link in the chain of comparisons (note
353 // that this does not mean that this is the last incoming value, blocks
354 // can be reordered).
355 Cond = Val;
356 ExpectedPredicate = ICmpInst::ICMP_EQ;
357 } else if (auto *BranchI = dyn_cast<CondBrInst>(Term)) {
358 // In this case, we expect a constant incoming value (the comparison is
359 // chained).
360 const auto *const Const = cast<ConstantInt>(Val);
361 LLVM_DEBUG(dbgs() << "const\n");
362 if (!Const->isZero())
363 return std::nullopt;
364 LLVM_DEBUG(dbgs() << "false\n");
365 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
366 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
367 Cond = BranchI->getCondition();
368 ExpectedPredicate =
369 FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
370 } else
371 return std::nullopt;
372
373 auto *CmpI = dyn_cast<ICmpInst>(Cond);
374 if (!CmpI)
375 return std::nullopt;
376 LLVM_DEBUG(dbgs() << "icmp\n");
377
378 std::optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
379 if (!Result)
380 return std::nullopt;
381
382 BCECmpBlock::InstructionSet BlockInsts(
383 {Result->Lhs.LoadI, Result->Rhs.LoadI, Result->CmpI, Term});
384 if (Result->Lhs.GEP)
385 BlockInsts.insert(Result->Lhs.GEP);
386 if (Result->Rhs.GEP)
387 BlockInsts.insert(Result->Rhs.GEP);
388 return BCECmpBlock(std::move(*Result), Block, BlockInsts);
389}
390
391static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
392 BCECmpBlock &&Comparison) {
393 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
394 << "': Found cmp of " << Comparison.SizeBits()
395 << " bits between " << Comparison.Lhs().BaseId << " + "
396 << Comparison.Lhs().Offset << " and "
397 << Comparison.Rhs().BaseId << " + "
398 << Comparison.Rhs().Offset << "\n");
399 LLVM_DEBUG(dbgs() << "\n");
400 Comparison.OrigOrder = Comparisons.size();
401 Comparisons.push_back(std::move(Comparison));
402}
403
404namespace {
405// A chain of comparisons.
406class BCECmpChain {
407public:
408 using ContiguousBlocks = std::vector<BCECmpBlock>;
409
410 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
411 AliasAnalysis &AA);
412
413 bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
414 DomTreeUpdater &DTU);
415
416 bool atLeastOneMerged() const {
417 return any_of(MergedBlocks_,
418 [](const auto &Blocks) { return Blocks.size() > 1; });
419 }
420
421private:
422 PHINode &Phi_;
423 // The list of all blocks in the chain, grouped by contiguity.
424 std::vector<ContiguousBlocks> MergedBlocks_;
425 // The original entry block (before sorting);
426 BasicBlock *EntryBlock_;
427};
428} // namespace
429
430static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second) {
431 return First.Lhs().BaseId == Second.Lhs().BaseId &&
432 First.Rhs().BaseId == Second.Rhs().BaseId &&
433 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
434 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
435}
436
437static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks) {
438 unsigned MinOrigOrder = std::numeric_limits<unsigned>::max();
439 for (const BCECmpBlock &Block : Blocks)
440 MinOrigOrder = std::min(MinOrigOrder, Block.OrigOrder);
441 return MinOrigOrder;
442}
443
444/// Given a chain of comparison blocks, groups the blocks into contiguous
445/// ranges that can be merged together into a single comparison.
446static std::vector<BCECmpChain::ContiguousBlocks>
447mergeBlocks(std::vector<BCECmpBlock> &&Blocks) {
448 std::vector<BCECmpChain::ContiguousBlocks> MergedBlocks;
449
450 // Sort to detect continuous offsets.
451 llvm::sort(Blocks,
452 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
453 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
454 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
455 });
456
457 BCECmpChain::ContiguousBlocks *LastMergedBlock = nullptr;
458 for (BCECmpBlock &Block : Blocks) {
459 if (!LastMergedBlock || !areContiguous(LastMergedBlock->back(), Block)) {
460 MergedBlocks.emplace_back();
461 LastMergedBlock = &MergedBlocks.back();
462 } else {
463 LLVM_DEBUG(dbgs() << "Merging block " << Block.BB->getName() << " into "
464 << LastMergedBlock->back().BB->getName() << "\n");
465 }
466 LastMergedBlock->push_back(std::move(Block));
467 }
468
469 // While we allow reordering for merging, do not reorder unmerged comparisons.
470 // Doing so may introduce branch on poison.
471 llvm::sort(MergedBlocks, [](const BCECmpChain::ContiguousBlocks &LhsBlocks,
472 const BCECmpChain::ContiguousBlocks &RhsBlocks) {
473 return getMinOrigOrder(LhsBlocks) < getMinOrigOrder(RhsBlocks);
474 });
475
476 return MergedBlocks;
477}
478
479BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
480 AliasAnalysis &AA)
481 : Phi_(Phi) {
482 assert(!Blocks.empty() && "a chain should have at least one block");
483 // Now look inside blocks to check for BCE comparisons.
484 std::vector<BCECmpBlock> Comparisons;
485 BaseIdentifier BaseId;
486 for (BasicBlock *const Block : Blocks) {
487 assert(Block && "invalid block");
488 if (Block->hasAddressTaken()) {
489 LLVM_DEBUG(dbgs() << "cannot merge blocks with blockaddress\n");
490 return;
491 }
492 std::optional<BCECmpBlock> Comparison = visitCmpBlock(
493 Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
494 if (!Comparison) {
495 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
496 return;
497 }
498 if (Comparison->doesOtherWork()) {
499 LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
500 << "' does extra work besides compare\n");
501 if (Comparisons.empty()) {
502 // This is the initial block in the chain, in case this block does other
503 // work, we can try to split the block and move the irrelevant
504 // instructions to the predecessor.
505 //
506 // If this is not the initial block in the chain, splitting it wont
507 // work.
508 //
509 // As once split, there will still be instructions before the BCE cmp
510 // instructions that do other work in program order, i.e. within the
511 // chain before sorting. Unless we can abort the chain at this point
512 // and start anew.
513 //
514 // NOTE: we only handle blocks a with single predecessor for now.
515 if (Comparison->canSplit(AA)) {
517 << "Split initial block '" << Comparison->BB->getName()
518 << "' that does extra work besides compare\n");
519 Comparison->RequireSplit = true;
520 enqueueBlock(Comparisons, std::move(*Comparison));
521 } else {
523 << "ignoring initial block '" << Comparison->BB->getName()
524 << "' that does extra work besides compare\n");
525 }
526 continue;
527 }
528 // TODO(courbet): Right now we abort the whole chain. We could be
529 // merging only the blocks that don't do other work and resume the
530 // chain from there. For example:
531 // if (a[0] == b[0]) { // bb1
532 // if (a[1] == b[1]) { // bb2
533 // some_value = 3; //bb3
534 // if (a[2] == b[2]) { //bb3
535 // do a ton of stuff //bb4
536 // }
537 // }
538 // }
539 //
540 // This is:
541 //
542 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
543 // \ \ \ \
544 // ne ne ne \
545 // \ \ \ v
546 // +------------+-----------+----------> bb_phi
547 //
548 // We can only merge the first two comparisons, because bb3* does
549 // "other work" (setting some_value to 3).
550 // We could still merge bb1 and bb2 though.
551 return;
552 }
553 enqueueBlock(Comparisons, std::move(*Comparison));
554 }
555
556 // It is possible we have no suitable comparison to merge.
557 if (Comparisons.empty()) {
558 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
559 return;
560 }
561 EntryBlock_ = Comparisons[0].BB;
562 MergedBlocks_ = mergeBlocks(std::move(Comparisons));
563}
564
565namespace {
566
567// A class to compute the name of a set of merged basic blocks.
568// This is optimized for the common case of no block names.
569class MergedBlockName {
570 // Storage for the uncommon case of several named blocks.
571 SmallString<16> Scratch;
572
573public:
574 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
575 : Name(makeName(Comparisons)) {}
576 const StringRef Name;
577
578private:
579 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
580 assert(!Comparisons.empty() && "no basic block");
581 // Fast path: only one block, or no names at all.
582 if (Comparisons.size() == 1)
583 return Comparisons[0].BB->getName();
584 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
585 [](int i, const BCECmpBlock &Cmp) {
586 return i + Cmp.BB->getName().size();
587 });
588 if (size == 0)
589 return StringRef("", 0);
590
591 // Slow path: at least two blocks, at least one block with a name.
592 Scratch.clear();
593 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
594 // separators.
595 Scratch.reserve(size + Comparisons.size() - 1);
596 const auto append = [this](StringRef str) {
597 Scratch.append(str.begin(), str.end());
598 };
599 append(Comparisons[0].BB->getName());
600 for (int I = 1, E = Comparisons.size(); I < E; ++I) {
601 const BasicBlock *const BB = Comparisons[I].BB;
602 if (!BB->getName().empty()) {
603 append("+");
604 append(BB->getName());
605 }
606 }
607 return Scratch.str();
608 }
609};
610} // namespace
611
612/// Determine the branch weights for the resulting conditional branch, resulting
613/// after merging \p Comparisons.
614static std::optional<SmallVector<uint32_t, 2>>
616 assert(!Comparisons.empty());
618 return std::nullopt;
619 if (Comparisons.size() == 1) {
621 if (!extractBranchWeights(*Comparisons[0].BB->getTerminator(), Weights))
622 return std::nullopt;
623 return Weights;
624 }
625 // The probability to go to the phi block is the disjunction of the
626 // probability to go to the phi block from the individual Comparisons. We'll
627 // swap the weights because `getDisjunctionWeights` computes the disjunction
628 // for the "true" branch, then swap back.
629 SmallVector<uint64_t, 2> Weights{0, 1};
630 // At this point, Weights encodes "0-probability" for the "true" side.
631 for (const auto &C : Comparisons) {
633 if (!extractBranchWeights(*C.BB->getTerminator(), W))
634 return std::nullopt;
635
636 std::swap(W[0], W[1]);
637 Weights = getDisjunctionWeights(Weights, W);
638 }
639 std::swap(Weights[0], Weights[1]);
640 return fitWeights(Weights);
641}
642
643// Merges the given contiguous comparison blocks into one memcmp block.
645 BasicBlock *const InsertBefore,
646 BasicBlock *const NextCmpBlock,
647 PHINode &Phi, const TargetLibraryInfo &TLI,
649 assert(!Comparisons.empty() && "merging zero comparisons");
650 LLVMContext &Context = NextCmpBlock->getContext();
651 const BCECmpBlock &FirstCmp = Comparisons[0];
652
653 // Create a new cmp block before next cmp block.
654 BasicBlock *const BB =
655 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
656 NextCmpBlock->getParent(), InsertBefore);
657 IRBuilder<> Builder(BB);
658 // Add the GEPs from the first BCECmpBlock.
659 Value *Lhs, *Rhs;
660 if (FirstCmp.Lhs().GEP)
661 Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
662 else
663 Lhs = FirstCmp.Lhs().LoadI->getPointerOperand();
664 if (FirstCmp.Rhs().GEP)
665 Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
666 else
667 Rhs = FirstCmp.Rhs().LoadI->getPointerOperand();
668
669 Value *IsEqual = nullptr;
670 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
671 << BB->getName() << "\n");
672
673 // If there is one block that requires splitting, we do it now, i.e.
674 // just before we know we will collapse the chain. The instructions
675 // can be executed before any of the instructions in the chain.
676 const auto *ToSplit = llvm::find_if(
677 Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
678 if (ToSplit != Comparisons.end()) {
679 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
680 ToSplit->split(BB, AA);
681 }
682
683 if (Comparisons.size() == 1) {
684 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
685 // Use clone to keep the metadata
686 Instruction *const LhsLoad = Builder.Insert(FirstCmp.Lhs().LoadI->clone());
687 Instruction *const RhsLoad = Builder.Insert(FirstCmp.Rhs().LoadI->clone());
688 LhsLoad->replaceUsesOfWith(LhsLoad->getOperand(0), Lhs);
689 RhsLoad->replaceUsesOfWith(RhsLoad->getOperand(0), Rhs);
690 // There are no blocks to merge, just do the comparison.
691 // If we condition on this IsEqual, we already have its probabilities.
692 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
693 } else {
694 const unsigned TotalSizeBits = std::accumulate(
695 Comparisons.begin(), Comparisons.end(), 0u,
696 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
697
698 // memcmp expects a 'size_t' argument and returns 'int'.
699 unsigned SizeTBits = TLI.getSizeTSize(*Phi.getModule());
700 unsigned IntBits = TLI.getIntSize();
701
702 // Create memcmp() == 0.
703 const auto &DL = Phi.getDataLayout();
704 Value *const MemCmpCall = emitMemCmp(
705 Lhs, Rhs,
706 ConstantInt::get(Builder.getIntNTy(SizeTBits), TotalSizeBits / 8),
707 Builder, DL, &TLI);
708 IsEqual = Builder.CreateICmpEQ(
709 MemCmpCall, ConstantInt::get(Builder.getIntNTy(IntBits), 0));
710 }
711
712 BasicBlock *const PhiBB = Phi.getParent();
713 // Add a branch to the next basic block in the chain.
714 if (NextCmpBlock == PhiBB) {
715 // Continue to phi, passing it the comparison result.
716 Builder.CreateBr(PhiBB);
717 Phi.addIncoming(IsEqual, BB);
718 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
719 } else {
720 // Continue to next block if equal, exit to phi else.
721 auto *BI = Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
722 if (auto BranchWeights = computeMergedBranchWeights(Comparisons))
723 setBranchWeights(*BI, BranchWeights.value(), /*IsExpected=*/false);
724 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
725 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
726 {DominatorTree::Insert, BB, PhiBB}});
727 }
728 return BB;
729}
730
731bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
732 DomTreeUpdater &DTU) {
733 assert(atLeastOneMerged() && "simplifying trivial BCECmpChain");
734 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
735 << EntryBlock_->getName() << "\n");
736
737 // Effectively merge blocks. We go in the reverse direction from the phi block
738 // so that the next block is always available to branch to.
739 BasicBlock *InsertBefore = EntryBlock_;
740 BasicBlock *NextCmpBlock = Phi_.getParent();
741 for (const auto &Blocks : reverse(MergedBlocks_)) {
742 InsertBefore = NextCmpBlock = mergeComparisons(
743 Blocks, InsertBefore, NextCmpBlock, Phi_, TLI, AA, DTU);
744 }
745
746 // Replace the original cmp chain with the new cmp chain by pointing all
747 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
748 // blocks in the old chain unreachable.
749 while (!pred_empty(EntryBlock_)) {
750 BasicBlock* const Pred = *pred_begin(EntryBlock_);
751 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
752 << "\n");
753 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
754 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
755 {DominatorTree::Insert, Pred, NextCmpBlock}});
756 }
757
758 // If the old cmp chain was the function entry, we need to update the function
759 // entry.
760 const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
761 if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
762 LLVM_DEBUG(dbgs() << "Changing function entry from "
763 << EntryBlock_->getName() << " to "
764 << NextCmpBlock->getName() << "\n");
765 DTU.getDomTree().setNewRoot(NextCmpBlock);
766 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
767 }
768 EntryBlock_ = nullptr;
769
770 // Delete merged blocks. This also removes incoming values in phi.
771 SmallVector<BasicBlock *, 16> DeadBlocks;
772 for (const auto &Blocks : MergedBlocks_) {
773 for (const BCECmpBlock &Block : Blocks) {
774 LLVM_DEBUG(dbgs() << "Deleting merged block " << Block.BB->getName()
775 << "\n");
776 DeadBlocks.push_back(Block.BB);
777 }
778 }
779 DeleteDeadBlocks(DeadBlocks, &DTU);
780
781 MergedBlocks_.clear();
782 return true;
783}
784
785static std::vector<BasicBlock *>
786getOrderedBlocks(PHINode &Phi, BasicBlock *const LastBlock, int NumBlocks) {
787 // Walk up from the last block to find other blocks.
788 std::vector<BasicBlock *> Blocks(NumBlocks);
789 assert(LastBlock && "invalid last block");
790 BasicBlock *CurBlock = LastBlock;
791 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
792 if (CurBlock->hasAddressTaken()) {
793 // Somebody is jumping to the block through an address, all bets are
794 // off.
795 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
796 << " has its address taken\n");
797 return {};
798 }
799 Blocks[BlockIndex] = CurBlock;
800 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
801 if (!SinglePredecessor) {
802 // The block has two or more predecessors.
803 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
804 << " has two or more predecessors\n");
805 return {};
806 }
807 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
808 // The block does not link back to the phi.
809 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
810 << " does not link back to the phi\n");
811 return {};
812 }
813 CurBlock = SinglePredecessor;
814 }
815 Blocks[0] = CurBlock;
816 return Blocks;
817}
818
819static bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI,
821 LLVM_DEBUG(dbgs() << "processPhi()\n");
822 if (Phi.getNumIncomingValues() <= 1) {
823 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
824 return false;
825 }
826 // We are looking for something that has the following structure:
827 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
828 // \ \ \ \
829 // ne ne ne \
830 // \ \ \ v
831 // +------------+-----------+----------> bb_phi
832 //
833 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
834 // It's the only block that contributes a non-constant value to the Phi.
835 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
836 // them being the phi block.
837 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
838 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
839
840 // The blocks are not necessarily ordered in the phi, so we start from the
841 // last block and reconstruct the order.
842 BasicBlock *LastBlock = nullptr;
843 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
844 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
845 if (LastBlock) {
846 // There are several non-constant values.
847 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
848 return false;
849 }
850 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
851 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
852 Phi.getIncomingBlock(I)) {
853 // Non-constant incoming value is not from a cmp instruction or not
854 // produced by the last block. We could end up processing the value
855 // producing block more than once.
856 //
857 // This is an uncommon case, so we bail.
859 dbgs()
860 << "skip: non-constant value not from cmp or not from last block.\n");
861 return false;
862 }
863 LastBlock = Phi.getIncomingBlock(I);
864 }
865 if (!LastBlock) {
866 // There is no non-constant block.
867 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
868 return false;
869 }
870 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
871 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
872 return false;
873 }
874
875 const auto Blocks =
876 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
877 if (Blocks.empty()) return false;
878 BCECmpChain CmpChain(Blocks, Phi, AA);
879
880 if (!CmpChain.atLeastOneMerged()) {
881 LLVM_DEBUG(dbgs() << "skip: nothing merged\n");
882 return false;
883 }
884
885 return CmpChain.simplify(TLI, AA, DTU);
886}
887
888static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
890 DominatorTree *DT) {
891 LLVM_DEBUG(dbgs() << "MergeICmpsLegacyPass: " << F.getName() << "\n");
892
893 // We only try merging comparisons if the target wants to expand memcmp later.
894 // The rationale is to avoid turning small chains into memcmp calls.
895 if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
896 return false;
897
898 // If we don't have memcmp avaiable we can't emit calls to it.
899 if (!TLI.has(LibFunc_memcmp))
900 return false;
901
902 DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
903 DomTreeUpdater::UpdateStrategy::Eager);
904
905 bool MadeChange = false;
906
907 for (BasicBlock &BB : llvm::drop_begin(F)) {
908 // A Phi operation is always first in a basic block.
909 if (auto *const Phi = dyn_cast<PHINode>(&*BB.begin()))
910 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
911 }
912
913 return MadeChange;
914}
915
916namespace {
917class MergeICmpsLegacyPass : public FunctionPass {
918public:
919 static char ID;
920
921 MergeICmpsLegacyPass() : FunctionPass(ID) {
923 }
924
925 bool runOnFunction(Function &F) override {
926 if (skipFunction(F)) return false;
927 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
928 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
929 // MergeICmps does not need the DominatorTree, but we update it if it's
930 // already available.
931 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
932 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
933 return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() : nullptr);
934 }
935
936 private:
937 void getAnalysisUsage(AnalysisUsage &AU) const override {
938 AU.addRequired<TargetLibraryInfoWrapperPass>();
939 AU.addRequired<TargetTransformInfoWrapperPass>();
940 AU.addRequired<AAResultsWrapperPass>();
941 AU.addPreserved<GlobalsAAWrapperPass>();
942 AU.addPreserved<DominatorTreeWrapperPass>();
943 }
944};
945
946} // namespace
947
948char MergeICmpsLegacyPass::ID = 0;
949INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps",
950 "Merge contiguous icmps into a memcmp", false, false)
954INITIALIZE_PASS_END(MergeICmpsLegacyPass, "mergeicmps",
955 "Merge contiguous icmps into a memcmp", false, false)
956
957Pass *llvm::createMergeICmpsLegacyPass() { return new MergeICmpsLegacyPass(); }
958
961 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
962 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
963 auto &AA = AM.getResult<AAManager>(F);
965 const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
966 if (!MadeChanges)
967 return PreservedAnalyses::all();
970 return PA;
971}
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, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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< SmallVector< uint32_t, 2 > > computeMergedBranchWeights(ArrayRef< BCECmpBlock > Comparisons)
Determine the branch weights for the resulting conditional branch, resulting after merging Comparison...
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
This file contains the declarations for profiling metadata utility functions.
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:40
iterator end() const
Definition ArrayRef.h:131
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
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:449
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:675
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:278
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:159
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.
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:2811
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
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
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:267
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
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:440
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:457
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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:532
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
cl::opt< bool > ProfcheckDisableMetadataFixes
Definition Metadata.cpp:64
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:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
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:1746
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.
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
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:1753
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:74
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:1917
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
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:1772
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
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:872
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)