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