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
157 // This pass only works correctly when all of the compared elements have
158 // byte-multiple sizes.
159 const auto &DL = LoadI->getDataLayout();
160 if (!DL.typeSizeEqualsStoreSize(LoadI->getType())) {
161 LLVM_DEBUG(dbgs() << "type size is not a byte multiple\n");
162 return {};
163 }
164
165 APInt Offset = APInt(DL.getIndexTypeSizeInBits(Addr->getType()), 0);
166 Value *Base = Addr;
167 auto *GEP = dyn_cast<GetElementPtrInst>(Addr);
168 if (GEP) {
169 LLVM_DEBUG(dbgs() << "GEP\n");
170 if (GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
171 LLVM_DEBUG(dbgs() << "used outside of block\n");
172 return {};
173 }
174 if (!GEP->accumulateConstantOffset(DL, Offset))
175 return {};
176 Base = GEP->getPointerOperand();
177 }
178 return BCEAtom(GEP, LoadI, BaseId.getBaseId(Base), Offset);
179}
180
181namespace {
182// A comparison between two BCE atoms, e.g. `a == o.a` in the example at the
183// top.
184// Note: the terminology is misleading: the comparison is symmetric, so there
185// is no real {l/r}hs. What we want though is to have the same base on the
186// left (resp. right), so that we can detect consecutive loads. To ensure this
187// we put the smallest atom on the left.
188struct BCECmp {
189 BCEAtom Lhs;
190 BCEAtom Rhs;
191 int SizeBits;
192 const ICmpInst *CmpI;
193
194 BCECmp(BCEAtom L, BCEAtom R, int SizeBits, const ICmpInst *CmpI)
195 : Lhs(std::move(L)), Rhs(std::move(R)), SizeBits(SizeBits), CmpI(CmpI) {
196 if (Rhs < Lhs) std::swap(Rhs, Lhs);
197 }
198};
199
200// A basic block with a comparison between two BCE atoms.
201// The block might do extra work besides the atom comparison, in which case
202// doesOtherWork() returns true. Under some conditions, the block can be
203// split into the atom comparison part and the "other work" part
204// (see canSplit()).
205class BCECmpBlock {
206 public:
207 typedef SmallDenseSet<const Instruction *, 8> InstructionSet;
208
209 BCECmpBlock(BCECmp Cmp, BasicBlock *BB, InstructionSet BlockInsts)
210 : BB(BB), BlockInsts(std::move(BlockInsts)), Cmp(std::move(Cmp)) {}
211
212 const BCEAtom &Lhs() const { return Cmp.Lhs; }
213 const BCEAtom &Rhs() const { return Cmp.Rhs; }
214 int SizeBits() const { return Cmp.SizeBits; }
215
216 // Returns true if the block does other works besides comparison.
217 bool doesOtherWork() const;
218
219 // Returns true if the non-BCE-cmp instructions can be separated from BCE-cmp
220 // instructions in the block.
221 // SplitAt is set to the instruction before which the block will have to be
222 // split.
223 bool canSplit(AliasAnalysis &AA, Instruction *&SplitAt) 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, Instruction *&SplitAt) const {
289 SplitAt = nullptr;
290 for (Instruction &Inst : *BB) {
291 if (!BlockInsts.count(&Inst)) {
292 SplitAt = Inst.getNextNode();
293 if (!canSinkBCECmpInst(&Inst, AA))
294 return false;
295 }
296 }
297 return true;
298}
299
300bool BCECmpBlock::doesOtherWork() const {
301 // TODO(courbet): Can we allow some other things ? This is very conservative.
302 // We might be able to get away with anything does not have any side
303 // effects outside of the basic block.
304 // Note: The GEPs and/or loads are not necessarily in the same block.
305 for (const Instruction &Inst : *BB) {
306 if (!BlockInsts.count(&Inst))
307 return true;
308 }
309 return false;
310}
311
312// Visit the given comparison. If this is a comparison between two valid
313// BCE atoms, returns the comparison.
314static std::optional<BCECmp>
315visitICmp(const ICmpInst *const CmpI,
316 const ICmpInst::Predicate ExpectedPredicate, BaseIdentifier &BaseId) {
317 // The comparison can only be used once:
318 // - For intermediate blocks, as a branch condition.
319 // - For the final block, as an incoming value for the Phi.
320 // If there are any other uses of the comparison, we cannot merge it with
321 // other comparisons as we would create an orphan use of the value.
322 if (!CmpI->hasOneUse()) {
323 LLVM_DEBUG(dbgs() << "cmp has several uses\n");
324 return std::nullopt;
325 }
326 if (CmpI->getPredicate() != ExpectedPredicate)
327 return std::nullopt;
328 LLVM_DEBUG(dbgs() << "cmp "
329 << (ExpectedPredicate == ICmpInst::ICMP_EQ ? "eq" : "ne")
330 << "\n");
331 auto Lhs = visitICmpLoadOperand(CmpI->getOperand(0), BaseId);
332 if (!Lhs.BaseId)
333 return std::nullopt;
334 auto Rhs = visitICmpLoadOperand(CmpI->getOperand(1), BaseId);
335 if (!Rhs.BaseId)
336 return std::nullopt;
337
338 const auto &DL = CmpI->getDataLayout();
339 return BCECmp(std::move(Lhs), std::move(Rhs),
340 DL.getTypeSizeInBits(CmpI->getOperand(0)->getType()), CmpI);
341}
342
343// Visit the given comparison block. If this is a comparison between two valid
344// BCE atoms, returns the comparison.
345static std::optional<BCECmpBlock>
347 const BasicBlock *const PhiBlock, BaseIdentifier &BaseId) {
348 if (Block->empty())
349 return std::nullopt;
350 auto *Term = Block->getTerminator();
351 Value *Cond;
352 ICmpInst::Predicate ExpectedPredicate;
353 if (isa<UncondBrInst>(Term)) {
354 // In this case, we expect an incoming value which is the result of the
355 // comparison. This is the last link in the chain of comparisons (note
356 // that this does not mean that this is the last incoming value, blocks
357 // can be reordered).
358 Cond = Val;
359 ExpectedPredicate = ICmpInst::ICMP_EQ;
360 } else if (auto *BranchI = dyn_cast<CondBrInst>(Term)) {
361 // In this case, we expect a constant incoming value (the comparison is
362 // chained).
363 const auto *const Const = cast<ConstantInt>(Val);
364 LLVM_DEBUG(dbgs() << "const\n");
365 if (!Const->isZero())
366 return std::nullopt;
367 LLVM_DEBUG(dbgs() << "false\n");
368 assert(BranchI->getNumSuccessors() == 2 && "expecting a cond branch");
369 BasicBlock *const FalseBlock = BranchI->getSuccessor(1);
370 Cond = BranchI->getCondition();
371 ExpectedPredicate =
372 FalseBlock == PhiBlock ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
373 } else
374 return std::nullopt;
375
376 auto *CmpI = dyn_cast<ICmpInst>(Cond);
377 if (!CmpI)
378 return std::nullopt;
379 LLVM_DEBUG(dbgs() << "icmp\n");
380
381 std::optional<BCECmp> Result = visitICmp(CmpI, ExpectedPredicate, BaseId);
382 if (!Result)
383 return std::nullopt;
384
385 BCECmpBlock::InstructionSet BlockInsts(
386 {Result->Lhs.LoadI, Result->Rhs.LoadI, Result->CmpI, Term});
387 if (Result->Lhs.GEP)
388 BlockInsts.insert(Result->Lhs.GEP);
389 if (Result->Rhs.GEP)
390 BlockInsts.insert(Result->Rhs.GEP);
391 return BCECmpBlock(std::move(*Result), Block, BlockInsts);
392}
393
394static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
395 BCECmpBlock &&Comparison) {
396 LLVM_DEBUG(dbgs() << "Block '" << Comparison.BB->getName()
397 << "': Found cmp of " << Comparison.SizeBits()
398 << " bits between " << Comparison.Lhs().BaseId << " + "
399 << Comparison.Lhs().Offset << " and "
400 << Comparison.Rhs().BaseId << " + "
401 << Comparison.Rhs().Offset << "\n");
402 LLVM_DEBUG(dbgs() << "\n");
403 Comparison.OrigOrder = Comparisons.size();
404 Comparisons.push_back(std::move(Comparison));
405}
406
407namespace {
408// A chain of comparisons.
409class BCECmpChain {
410public:
411 using ContiguousBlocks = std::vector<BCECmpBlock>;
412
413 BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
414 AliasAnalysis &AA);
415
416 bool isDereferenceable();
417
418 bool simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
419 DomTreeUpdater &DTU);
420
421 bool atLeastOneMerged() const {
422 return any_of(MergedBlocks_,
423 [](const auto &Blocks) { return Blocks.size() > 1; });
424 }
425
426private:
427 PHINode &Phi_;
428 // The list of all blocks in the chain, grouped by contiguity.
429 std::vector<ContiguousBlocks> MergedBlocks_;
430 // The original entry block (before sorting);
431 BasicBlock *EntryBlock_;
432 // The instruction before which the entry block needs to be split (or null
433 // if no splitting required).
434 Instruction *SplitAt = nullptr;
435};
436} // namespace
437
438static bool areContiguous(const BCECmpBlock &First, const BCECmpBlock &Second) {
439 return First.Lhs().BaseId == Second.Lhs().BaseId &&
440 First.Rhs().BaseId == Second.Rhs().BaseId &&
441 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
442 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
443}
444
445static unsigned getMinOrigOrder(const BCECmpChain::ContiguousBlocks &Blocks) {
446 unsigned MinOrigOrder = std::numeric_limits<unsigned>::max();
447 for (const BCECmpBlock &Block : Blocks)
448 MinOrigOrder = std::min(MinOrigOrder, Block.OrigOrder);
449 return MinOrigOrder;
450}
451
452/// Given a chain of comparison blocks, groups the blocks into contiguous
453/// ranges that can be merged together into a single comparison.
454static std::vector<BCECmpChain::ContiguousBlocks>
455mergeBlocks(std::vector<BCECmpBlock> &&Blocks) {
456 std::vector<BCECmpChain::ContiguousBlocks> MergedBlocks;
457
458 // Sort to detect continuous offsets.
459 llvm::sort(Blocks,
460 [](const BCECmpBlock &LhsBlock, const BCECmpBlock &RhsBlock) {
461 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
462 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
463 });
464
465 BCECmpChain::ContiguousBlocks *LastMergedBlock = nullptr;
466 for (BCECmpBlock &Block : Blocks) {
467 if (!LastMergedBlock || !areContiguous(LastMergedBlock->back(), Block)) {
468 MergedBlocks.emplace_back();
469 LastMergedBlock = &MergedBlocks.back();
470 } else {
471 LLVM_DEBUG(dbgs() << "Merging block " << Block.BB->getName() << " into "
472 << LastMergedBlock->back().BB->getName() << "\n");
473 }
474 LastMergedBlock->push_back(std::move(Block));
475 }
476
477 // While we allow reordering for merging, do not reorder unmerged comparisons.
478 // Doing so may introduce branch on poison.
479 llvm::sort(MergedBlocks, [](const BCECmpChain::ContiguousBlocks &LhsBlocks,
480 const BCECmpChain::ContiguousBlocks &RhsBlocks) {
481 return getMinOrigOrder(LhsBlocks) < getMinOrigOrder(RhsBlocks);
482 });
483
484 return MergedBlocks;
485}
486
487BCECmpChain::BCECmpChain(const std::vector<BasicBlock *> &Blocks, PHINode &Phi,
488 AliasAnalysis &AA)
489 : Phi_(Phi) {
490 assert(!Blocks.empty() && "a chain should have at least one block");
491 // Now look inside blocks to check for BCE comparisons.
492 std::vector<BCECmpBlock> Comparisons;
493 BaseIdentifier BaseId;
494 for (BasicBlock *const Block : Blocks) {
495 assert(Block && "invalid block");
496 if (Block->hasAddressTaken()) {
497 LLVM_DEBUG(dbgs() << "cannot merge blocks with blockaddress\n");
498 return;
499 }
500 std::optional<BCECmpBlock> Comparison = visitCmpBlock(
501 Phi.getIncomingValueForBlock(Block), Block, Phi.getParent(), BaseId);
502 if (!Comparison) {
503 LLVM_DEBUG(dbgs() << "chain with invalid BCECmpBlock, no merge.\n");
504 return;
505 }
506 if (Comparison->doesOtherWork()) {
507 LLVM_DEBUG(dbgs() << "block '" << Comparison->BB->getName()
508 << "' does extra work besides compare\n");
509 if (Comparisons.empty()) {
510 // This is the initial block in the chain, in case this block does other
511 // work, we can try to split the block and move the irrelevant
512 // instructions to the predecessor.
513 //
514 // If this is not the initial block in the chain, splitting it wont
515 // work.
516 //
517 // As once split, there will still be instructions before the BCE cmp
518 // instructions that do other work in program order, i.e. within the
519 // chain before sorting. Unless we can abort the chain at this point
520 // and start anew.
521 //
522 // NOTE: we only handle blocks a with single predecessor for now.
523 if (Comparison->canSplit(AA, SplitAt)) {
525 << "Split initial block '" << Comparison->BB->getName()
526 << "' that does extra work besides compare\n");
527 Comparison->RequireSplit = true;
528 enqueueBlock(Comparisons, std::move(*Comparison));
529 } else {
530 SplitAt = nullptr;
532 << "ignoring initial block '" << Comparison->BB->getName()
533 << "' that does extra work besides compare\n");
534 }
535 continue;
536 }
537 // TODO(courbet): Right now we abort the whole chain. We could be
538 // merging only the blocks that don't do other work and resume the
539 // chain from there. For example:
540 // if (a[0] == b[0]) { // bb1
541 // if (a[1] == b[1]) { // bb2
542 // some_value = 3; //bb3
543 // if (a[2] == b[2]) { //bb3
544 // do a ton of stuff //bb4
545 // }
546 // }
547 // }
548 //
549 // This is:
550 //
551 // bb1 --eq--> bb2 --eq--> bb3* -eq--> bb4 --+
552 // \ \ \ \
553 // ne ne ne \
554 // \ \ \ v
555 // +------------+-----------+----------> bb_phi
556 //
557 // We can only merge the first two comparisons, because bb3* does
558 // "other work" (setting some_value to 3).
559 // We could still merge bb1 and bb2 though.
560 return;
561 }
562 enqueueBlock(Comparisons, std::move(*Comparison));
563 }
564
565 // It is possible we have no suitable comparison to merge.
566 if (Comparisons.empty()) {
567 LLVM_DEBUG(dbgs() << "chain with no BCE basic blocks, no merge\n");
568 return;
569 }
570 EntryBlock_ = Comparisons[0].BB;
571 MergedBlocks_ = mergeBlocks(std::move(Comparisons));
572}
573
574namespace {
575
576// A class to compute the name of a set of merged basic blocks.
577// This is optimized for the common case of no block names.
578class MergedBlockName {
579 // Storage for the uncommon case of several named blocks.
580 SmallString<16> Scratch;
581
582public:
583 explicit MergedBlockName(ArrayRef<BCECmpBlock> Comparisons)
584 : Name(makeName(Comparisons)) {}
585 const StringRef Name;
586
587private:
588 StringRef makeName(ArrayRef<BCECmpBlock> Comparisons) {
589 assert(!Comparisons.empty() && "no basic block");
590 // Fast path: only one block, or no names at all.
591 if (Comparisons.size() == 1)
592 return Comparisons[0].BB->getName();
593 const int size = std::accumulate(Comparisons.begin(), Comparisons.end(), 0,
594 [](int i, const BCECmpBlock &Cmp) {
595 return i + Cmp.BB->getName().size();
596 });
597 if (size == 0)
598 return StringRef("", 0);
599
600 // Slow path: at least two blocks, at least one block with a name.
601 Scratch.clear();
602 // We'll have `size` bytes for name and `Comparisons.size() - 1` bytes for
603 // separators.
604 Scratch.reserve(size + Comparisons.size() - 1);
605 const auto append = [this](StringRef str) {
606 Scratch.append(str.begin(), str.end());
607 };
608 append(Comparisons[0].BB->getName());
609 for (int I = 1, E = Comparisons.size(); I < E; ++I) {
610 const BasicBlock *const BB = Comparisons[I].BB;
611 if (!BB->getName().empty()) {
612 append("+");
613 append(BB->getName());
614 }
615 }
616 return Scratch.str();
617 }
618};
619} // namespace
620
621/// Determine the branch weights for the resulting conditional branch, resulting
622/// after merging \p Comparisons.
623static std::optional<SmallVector<uint32_t, 2>>
625 assert(!Comparisons.empty());
627 return std::nullopt;
628 if (Comparisons.size() == 1) {
630 if (!extractBranchWeights(*Comparisons[0].BB->getTerminator(), Weights))
631 return std::nullopt;
632 return Weights;
633 }
634 // The probability to go to the phi block is the disjunction of the
635 // probability to go to the phi block from the individual Comparisons. We'll
636 // swap the weights because `getDisjunctionWeights` computes the disjunction
637 // for the "true" branch, then swap back.
638 SmallVector<uint64_t, 2> Weights{0, 1};
639 // At this point, Weights encodes "0-probability" for the "true" side.
640 for (const auto &C : Comparisons) {
642 if (!extractBranchWeights(*C.BB->getTerminator(), W))
643 return std::nullopt;
644
645 std::swap(W[0], W[1]);
646 Weights = getDisjunctionWeights(Weights, W);
647 }
648 std::swap(Weights[0], Weights[1]);
649 return fitWeights(Weights);
650}
651
652// Merges the given contiguous comparison blocks into one memcmp block.
654 BasicBlock *const InsertBefore,
655 BasicBlock *const NextCmpBlock,
656 PHINode &Phi, const TargetLibraryInfo &TLI,
658 assert(!Comparisons.empty() && "merging zero comparisons");
659 LLVMContext &Context = NextCmpBlock->getContext();
660 const BCECmpBlock &FirstCmp = Comparisons[0];
661
662 // Create a new cmp block before next cmp block.
663 BasicBlock *const BB =
664 BasicBlock::Create(Context, MergedBlockName(Comparisons).Name,
665 NextCmpBlock->getParent(), InsertBefore);
666 IRBuilder<> Builder(BB);
667 // Add the GEPs from the first BCECmpBlock.
668 Value *Lhs, *Rhs;
669 if (FirstCmp.Lhs().GEP)
670 Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
671 else
672 Lhs = FirstCmp.Lhs().LoadI->getPointerOperand();
673 if (FirstCmp.Rhs().GEP)
674 Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
675 else
676 Rhs = FirstCmp.Rhs().LoadI->getPointerOperand();
677
678 Value *IsEqual = nullptr;
679 LLVM_DEBUG(dbgs() << "Merging " << Comparisons.size() << " comparisons -> "
680 << BB->getName() << "\n");
681
682 // If there is one block that requires splitting, we do it now, i.e.
683 // just before we know we will collapse the chain. The instructions
684 // can be executed before any of the instructions in the chain.
685 const auto *ToSplit = llvm::find_if(
686 Comparisons, [](const BCECmpBlock &B) { return B.RequireSplit; });
687 if (ToSplit != Comparisons.end()) {
688 LLVM_DEBUG(dbgs() << "Splitting non_BCE work to header\n");
689 ToSplit->split(BB, AA);
690 }
691
692 if (Comparisons.size() == 1) {
693 LLVM_DEBUG(dbgs() << "Only one comparison, updating branches\n");
694 // Use clone to keep the metadata
695 Instruction *const LhsLoad = Builder.Insert(FirstCmp.Lhs().LoadI->clone());
696 Instruction *const RhsLoad = Builder.Insert(FirstCmp.Rhs().LoadI->clone());
697 LhsLoad->replaceUsesOfWith(LhsLoad->getOperand(0), Lhs);
698 RhsLoad->replaceUsesOfWith(RhsLoad->getOperand(0), Rhs);
699 // There are no blocks to merge, just do the comparison.
700 // If we condition on this IsEqual, we already have its probabilities.
701 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
702 } else {
703 const unsigned TotalSizeBits = std::accumulate(
704 Comparisons.begin(), Comparisons.end(), 0u,
705 [](int Size, const BCECmpBlock &C) { return Size + C.SizeBits(); });
706
707 // memcmp expects a 'size_t' argument and returns 'int'.
708 unsigned SizeTBits = TLI.getSizeTSize(*Phi.getModule());
709 unsigned IntBits = TLI.getIntSize();
710
711 // Create memcmp() == 0.
712 const auto &DL = Phi.getDataLayout();
713 Value *const MemCmpCall = emitMemCmp(
714 Lhs, Rhs,
715 ConstantInt::get(Builder.getIntNTy(SizeTBits), TotalSizeBits / 8),
716 Builder, DL, &TLI);
717 IsEqual = Builder.CreateICmpEQ(
718 MemCmpCall, ConstantInt::get(Builder.getIntNTy(IntBits), 0));
719 }
720
721 BasicBlock *const PhiBB = Phi.getParent();
722 // Add a branch to the next basic block in the chain.
723 if (NextCmpBlock == PhiBB) {
724 // Continue to phi, passing it the comparison result.
725 Builder.CreateBr(PhiBB);
726 Phi.addIncoming(IsEqual, BB);
727 DTU.applyUpdates({{DominatorTree::Insert, BB, PhiBB}});
728 } else {
729 // Continue to next block if equal, exit to phi else.
730 auto *BI = Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
731 if (auto BranchWeights = computeMergedBranchWeights(Comparisons))
732 setBranchWeights(*BI, BranchWeights.value(), /*IsExpected=*/false);
733 Phi.addIncoming(ConstantInt::getFalse(Context), BB);
734 DTU.applyUpdates({{DominatorTree::Insert, BB, NextCmpBlock},
735 {DominatorTree::Insert, BB, PhiBB}});
736 }
737 return BB;
738}
739
740// The transform may change the order in which the comparison is performed,
741// in which case we may perform loads that were not performed by the original
742// program. As such, we need to ensure that all the accessed memory is
743// dereferenceable.
744bool BCECmpChain::isDereferenceable() {
745 // We know that there can be no frees inside the merged blocks, so it's
746 // sufficient for dereferenceability to hold at the entry block. One
747 // exception to this is if the entry block performs "other work" and will
748 // get split. In that case, we need to consider frees prior to the splitting
749 // point.
750 Instruction *CxtI = SplitAt ? SplitAt : &EntryBlock_->front();
751
752 for (const auto &Blocks : MergedBlocks_) {
753 const BCECmpBlock &LowestBlock = Blocks.front();
754 const Value *Lhs = LowestBlock.Lhs().LoadI->getPointerOperand();
755 const Value *Rhs = LowestBlock.Rhs().LoadI->getPointerOperand();
756 const DataLayout &DL = LowestBlock.Lhs().LoadI->getDataLayout();
757
758 unsigned SizeInBits = 0;
759 for (const BCECmpBlock &Block : Blocks)
760 SizeInBits += Block.SizeBits();
761
762 APInt Size(64, SizeInBits / 8);
763 SimplifyQuery SQ(DL, CxtI);
764 if (!isDereferenceableAndAlignedPointer(Lhs, Align(1), Size, SQ) ||
766 return false;
767 }
768 return true;
769}
770
771bool BCECmpChain::simplify(const TargetLibraryInfo &TLI, AliasAnalysis &AA,
772 DomTreeUpdater &DTU) {
773 assert(atLeastOneMerged() && "simplifying trivial BCECmpChain");
774 LLVM_DEBUG(dbgs() << "Simplifying comparison chain starting at block "
775 << EntryBlock_->getName() << "\n");
776
777 // Effectively merge blocks. We go in the reverse direction from the phi block
778 // so that the next block is always available to branch to.
779 BasicBlock *InsertBefore = EntryBlock_;
780 BasicBlock *NextCmpBlock = Phi_.getParent();
781 for (const auto &Blocks : reverse(MergedBlocks_)) {
782 InsertBefore = NextCmpBlock = mergeComparisons(
783 Blocks, InsertBefore, NextCmpBlock, Phi_, TLI, AA, DTU);
784 }
785
786 // Replace the original cmp chain with the new cmp chain by pointing all
787 // predecessors of EntryBlock_ to NextCmpBlock instead. This makes all cmp
788 // blocks in the old chain unreachable.
789 while (!pred_empty(EntryBlock_)) {
790 BasicBlock* const Pred = *pred_begin(EntryBlock_);
791 LLVM_DEBUG(dbgs() << "Updating jump into old chain from " << Pred->getName()
792 << "\n");
793 Pred->getTerminator()->replaceUsesOfWith(EntryBlock_, NextCmpBlock);
794 DTU.applyUpdates({{DominatorTree::Delete, Pred, EntryBlock_},
795 {DominatorTree::Insert, Pred, NextCmpBlock}});
796 }
797
798 // If the old cmp chain was the function entry, we need to update the function
799 // entry.
800 const bool ChainEntryIsFnEntry = EntryBlock_->isEntryBlock();
801 if (ChainEntryIsFnEntry && DTU.hasDomTree()) {
802 LLVM_DEBUG(dbgs() << "Changing function entry from "
803 << EntryBlock_->getName() << " to "
804 << NextCmpBlock->getName() << "\n");
805 DTU.getDomTree().setNewRoot(NextCmpBlock);
806 DTU.applyUpdates({{DominatorTree::Delete, NextCmpBlock, EntryBlock_}});
807 }
808 EntryBlock_ = nullptr;
809
810 // Delete merged blocks. This also removes incoming values in phi.
811 SmallVector<BasicBlock *, 16> DeadBlocks;
812 for (const auto &Blocks : MergedBlocks_) {
813 for (const BCECmpBlock &Block : Blocks) {
814 LLVM_DEBUG(dbgs() << "Deleting merged block " << Block.BB->getName()
815 << "\n");
816 DeadBlocks.push_back(Block.BB);
817 }
818 }
819 DeleteDeadBlocks(DeadBlocks, &DTU);
820
821 MergedBlocks_.clear();
822 return true;
823}
824
825static std::vector<BasicBlock *>
826getOrderedBlocks(PHINode &Phi, BasicBlock *const LastBlock, int NumBlocks) {
827 // Walk up from the last block to find other blocks.
828 std::vector<BasicBlock *> Blocks(NumBlocks);
829 assert(LastBlock && "invalid last block");
830 BasicBlock *CurBlock = LastBlock;
831 for (int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
832 if (CurBlock->hasAddressTaken()) {
833 // Somebody is jumping to the block through an address, all bets are
834 // off.
835 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
836 << " has its address taken\n");
837 return {};
838 }
839 Blocks[BlockIndex] = CurBlock;
840 auto *SinglePredecessor = CurBlock->getSinglePredecessor();
841 if (!SinglePredecessor) {
842 // The block has two or more predecessors.
843 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
844 << " has two or more predecessors\n");
845 return {};
846 }
847 if (Phi.getBasicBlockIndex(SinglePredecessor) < 0) {
848 // The block does not link back to the phi.
849 LLVM_DEBUG(dbgs() << "skip: block " << BlockIndex
850 << " does not link back to the phi\n");
851 return {};
852 }
853 CurBlock = SinglePredecessor;
854 }
855 Blocks[0] = CurBlock;
856 return Blocks;
857}
858
859static bool processPhi(PHINode &Phi, const TargetLibraryInfo &TLI,
861 LLVM_DEBUG(dbgs() << "processPhi()\n");
862 if (Phi.getNumIncomingValues() <= 1) {
863 LLVM_DEBUG(dbgs() << "skip: only one incoming value in phi\n");
864 return false;
865 }
866 // We are looking for something that has the following structure:
867 // bb1 --eq--> bb2 --eq--> bb3 --eq--> bb4 --+
868 // \ \ \ \
869 // ne ne ne \
870 // \ \ \ v
871 // +------------+-----------+----------> bb_phi
872 //
873 // - The last basic block (bb4 here) must branch unconditionally to bb_phi.
874 // It's the only block that contributes a non-constant value to the Phi.
875 // - All other blocks (b1, b2, b3) must have exactly two successors, one of
876 // them being the phi block.
877 // - All intermediate blocks (bb2, bb3) must have only one predecessor.
878 // - Blocks cannot do other work besides the comparison, see doesOtherWork()
879
880 // The blocks are not necessarily ordered in the phi, so we start from the
881 // last block and reconstruct the order.
882 BasicBlock *LastBlock = nullptr;
883 for (unsigned I = 0; I < Phi.getNumIncomingValues(); ++I) {
884 if (isa<ConstantInt>(Phi.getIncomingValue(I))) continue;
885 if (LastBlock) {
886 // There are several non-constant values.
887 LLVM_DEBUG(dbgs() << "skip: several non-constant values\n");
888 return false;
889 }
890 if (!isa<ICmpInst>(Phi.getIncomingValue(I)) ||
891 cast<ICmpInst>(Phi.getIncomingValue(I))->getParent() !=
892 Phi.getIncomingBlock(I)) {
893 // Non-constant incoming value is not from a cmp instruction or not
894 // produced by the last block. We could end up processing the value
895 // producing block more than once.
896 //
897 // This is an uncommon case, so we bail.
899 dbgs()
900 << "skip: non-constant value not from cmp or not from last block.\n");
901 return false;
902 }
903 LastBlock = Phi.getIncomingBlock(I);
904 }
905 if (!LastBlock) {
906 // There is no non-constant block.
907 LLVM_DEBUG(dbgs() << "skip: no non-constant block\n");
908 return false;
909 }
910 if (LastBlock->getSingleSuccessor() != Phi.getParent()) {
911 LLVM_DEBUG(dbgs() << "skip: last block non-phi successor\n");
912 return false;
913 }
914
915 const auto Blocks =
916 getOrderedBlocks(Phi, LastBlock, Phi.getNumIncomingValues());
917 if (Blocks.empty()) return false;
918 BCECmpChain CmpChain(Blocks, Phi, AA);
919
920 if (!CmpChain.atLeastOneMerged()) {
921 LLVM_DEBUG(dbgs() << "skip: nothing merged\n");
922 return false;
923 }
924
925 if (!CmpChain.isDereferenceable()) {
926 LLVM_DEBUG(dbgs() << "not dereferenceable\n");
927 return false;
928 }
929
930 return CmpChain.simplify(TLI, AA, DTU);
931}
932
933static bool runImpl(Function &F, const TargetLibraryInfo &TLI,
935 DominatorTree *DT) {
936 LLVM_DEBUG(dbgs() << "MergeICmpsPass: " << F.getName() << "\n");
937
938 // We only try merging comparisons if the target wants to expand memcmp later.
939 // The rationale is to avoid turning small chains into memcmp calls.
940 if (!TTI.enableMemCmpExpansion(F.hasOptSize(), true))
941 return false;
942
943 // Make sure we can emit calls to memcmp().
944 if (!isLibFuncEmittable(F.getParent(), &TLI, LibFunc_memcmp))
945 return false;
946
947 DomTreeUpdater DTU(DT, /*PostDominatorTree*/ nullptr,
948 DomTreeUpdater::UpdateStrategy::Eager);
949
950 bool MadeChange = false;
951
952 for (BasicBlock &BB : llvm::drop_begin(F)) {
953 // A Phi operation is always first in a basic block.
954 if (auto *const Phi = dyn_cast<PHINode>(&*BB.begin()))
955 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
956 }
957
958 return MadeChange;
959}
960
963 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
964 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
965 auto &AA = AM.getResult<AAManager>(F);
967 const bool MadeChanges = runImpl(F, TLI, TTI, AA, DT);
968 if (!MadeChanges)
969 return PreservedAnalyses::all();
972 return PA;
973}
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:119
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
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.
const Instruction & front() const
Definition BasicBlock.h:484
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:740
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
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:151
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:2868
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
Check if the string is empty.
Definition StringRef.h:141
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
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:319
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:190
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
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:467
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:315
@ Offset
Definition DWP.cpp:558
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI 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:1668
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 bool isLibFuncEmittable(const Module *M, const TargetLibraryInfo *TLI, LibFunc TheLibFunc)
Check whether the library function is available on target and also that it in the current Module is a...
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:1745
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:407
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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:1752
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
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:245
ArrayRef(const T &OneElt) -> ArrayRef< T >
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:1916
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:1771
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:107
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:862
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)