LLVM 24.0.0git
SelectOptimize.cpp
Go to the documentation of this file.
1//===--- SelectOptimize.cpp - Convert select to branches if profitable ---===//
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 converts selects to conditional jumps when profitable.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CodeGenOptions.h"
15#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
24#include "llvm/CodeGen/Passes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instruction.h"
37#include "llvm/Pass.h"
41#include <algorithm>
42#include <queue>
43#include <stack>
44
45using namespace llvm;
46using namespace llvm::PatternMatch;
47
48#define DEBUG_TYPE "select-optimize"
49
50STATISTIC(NumSelectOptAnalyzed,
51 "Number of select groups considered for conversion to branch");
52STATISTIC(NumSelectConvertedExpColdOperand,
53 "Number of select groups converted due to expensive cold operand");
54STATISTIC(NumSelectConvertedHighPred,
55 "Number of select groups converted due to high-predictability");
56STATISTIC(NumSelectUnPred,
57 "Number of select groups not converted due to unpredictability");
58STATISTIC(NumSelectColdBB,
59 "Number of select groups not converted due to cold basic block");
60STATISTIC(NumSelectConvertedLoop,
61 "Number of select groups converted due to loop-level analysis");
62STATISTIC(NumSelectsConverted, "Number of selects converted");
63
64namespace llvm {
66}
67
68namespace {
69
70class SelectOptimizeImpl {
71 const CodeGenOptions *Opts = nullptr;
72 const TargetMachine *TM = nullptr;
73 const TargetSubtargetInfo *TSI = nullptr;
74 const TargetLowering *TLI = nullptr;
75 const TargetTransformInfo *TTI = nullptr;
76 const LoopInfo *LI = nullptr;
77 BlockFrequencyInfo *BFI;
78 ProfileSummaryInfo *PSI = nullptr;
79 OptimizationRemarkEmitter *ORE = nullptr;
80 TargetSchedModel TSchedModel;
81
82public:
83 SelectOptimizeImpl() = default;
84 SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){};
85 PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
86 bool runOnFunction(Function &F, Pass &P);
87
88 using Scaled64 = ScaledNumber<uint64_t>;
89
90 struct CostInfo {
91 /// Predicated cost (with selects as conditional moves).
92 Scaled64 PredCost;
93 /// Non-predicated cost (with selects converted to branches).
94 Scaled64 NonPredCost;
95 };
96
97 /// SelectLike is an abstraction over SelectInst and other operations that can
98 /// act like selects. For example Or(Zext(icmp), X) can be treated like
99 /// select(icmp, X|1, X).
100 class SelectLike {
101 /// The select (/or) instruction.
102 Instruction *I;
103 /// Whether this select is inverted, "not(cond), FalseVal, TrueVal", as
104 /// opposed to the original condition.
105 bool Inverted = false;
106
107 /// The index of the operand that depends on condition. Only for select-like
108 /// instruction such as Or/Add.
109 unsigned CondIdx;
110
111 public:
112 SelectLike(Instruction *I, bool Inverted = false, unsigned CondIdx = 0)
113 : I(I), Inverted(Inverted), CondIdx(CondIdx) {}
114
115 Instruction *getI() { return I; }
116 const Instruction *getI() const { return I; }
117
118 Type *getType() const { return I->getType(); }
119
120 unsigned getConditionOpIndex() { return CondIdx; };
121
122 /// Return the true value for the SelectLike instruction. Note this may not
123 /// exist for all SelectLike instructions. For example, for `or(zext(c), x)`
124 /// the true value would be `or(x,1)`. As this value does not exist, nullptr
125 /// is returned.
126 Value *getTrueValue(bool HonorInverts = true) const {
127 if (Inverted && HonorInverts)
128 return getFalseValue(/*HonorInverts=*/false);
129 if (auto *Sel = dyn_cast<SelectInst>(I))
130 return Sel->getTrueValue();
131 // Or(zext) case - The true value is Or(X), so return nullptr as the value
132 // does not yet exist.
133 if (isa<BinaryOperator>(I))
134 return nullptr;
135
136 llvm_unreachable("Unhandled case in getTrueValue");
137 }
138
139 /// Return the false value for the SelectLike instruction. For example the
140 /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is
141 /// `select(c, x|1, x)`)
142 Value *getFalseValue(bool HonorInverts = true) const {
143 if (Inverted && HonorInverts)
144 return getTrueValue(/*HonorInverts=*/false);
145 if (auto *Sel = dyn_cast<SelectInst>(I))
146 return Sel->getFalseValue();
147 // We are on the branch where the condition is zero, which means BinOp
148 // does not perform any computation, and we can simply return the operand
149 // that is not related to the condition
150 if (auto *BO = dyn_cast<BinaryOperator>(I))
151 return BO->getOperand(1 - CondIdx);
152
153 llvm_unreachable("Unhandled case in getFalseValue");
154 }
155
156 /// Return the NonPredCost cost of the op on \p isTrue branch, given the
157 /// costs in \p InstCostMap. This may need to be generated for select-like
158 /// instructions.
159 Scaled64 getOpCostOnBranch(
160 bool IsTrue, const DenseMap<const Instruction *, CostInfo> &InstCostMap,
161 const TargetTransformInfo *TTI) {
162 auto *V = IsTrue ? getTrueValue() : getFalseValue();
163 if (V) {
164 if (auto *IV = dyn_cast<Instruction>(V)) {
165 auto It = InstCostMap.find(IV);
166 return It != InstCostMap.end() ? It->second.NonPredCost
168 }
169 return Scaled64::getZero();
170 }
171 // If getTrue(False)Value() return nullptr, it means we are dealing with
172 // select-like instructions on the branch where the actual computation is
173 // happening. In that case the cost is equal to the cost of computation +
174 // cost of non-dependant on condition operand
176 getI()->getOpcode(), I->getType(), TargetTransformInfo::TCK_Latency,
177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
178 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
179 auto TotalCost = Scaled64::get(Cost.getValue());
180 if (auto *OpI = dyn_cast<Instruction>(I->getOperand(1 - CondIdx))) {
181 auto It = InstCostMap.find(OpI);
182 if (It != InstCostMap.end())
183 TotalCost += It->second.NonPredCost;
184 }
185 return TotalCost;
186 }
187 };
188
189private:
190 // Select groups consist of consecutive select-like instructions with the same
191 // condition. Between select-likes could be any number of auxiliary
192 // instructions related to the condition like not, zext, ashr/lshr
193 struct SelectGroup {
194 Value *Condition;
196
197 bool isUnpredictable() const {
198 return any_of(Selects, [](const SelectLike &SI) {
199 return SI.getI()->getMetadata(LLVMContext::MD_unpredictable);
200 });
201 }
202 };
203 using SelectGroups = SmallVector<SelectGroup, 2>;
204
205 // Converts select instructions of a function to conditional jumps when deemed
206 // profitable. Returns true if at least one select was converted.
207 bool optimizeSelects(Function &F);
208
209 // Heuristics for determining which select instructions can be profitably
210 // conveted to branches. Separate heuristics for selects in inner-most loops
211 // and the rest of code regions (base heuristics for non-inner-most loop
212 // regions).
213 void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
214 void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
215
216 // Converts to branches the select groups that were deemed
217 // profitable-to-convert.
218 void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
219
220 // Splits selects of a given basic block into select groups.
221 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
222
223 // Determines for which select groups it is profitable converting to branches
224 // (base and inner-most-loop heuristics).
225 void findProfitableSIGroupsBase(SelectGroups &SIGroups,
226 SelectGroups &ProfSIGroups);
227 void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
228 SelectGroups &ProfSIGroups);
229
230 // Determines if a select group should be converted to a branch (base
231 // heuristics).
232 bool isConvertToBranchProfitableBase(const SelectGroup &ASI);
233
234 // Returns true if there are expensive instructions in the cold value
235 // operand's (if any) dependence slice of any of the selects of the given
236 // group.
237 bool hasExpensiveColdOperand(const SelectGroup &ASI);
238
239 // For a given source instruction, collect its backwards dependence slice
240 // consisting of instructions exclusively computed for producing the operands
241 // of the source instruction. When sinking, the slice stops at members of
242 // \p Group.
243 void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice,
244 Instruction *SI, bool ForSinking = false,
245 const SelectGroup *Group = nullptr);
246
247 // Returns true if the condition of the select is highly predictable.
248 bool isSelectHighlyPredictable(const SelectLike SI);
249
250 // Loop-level checks to determine if a non-predicated version (with branches)
251 // of the given loop is more profitable than its predicated version.
252 bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
253
254 // Computes instruction and loop-critical-path costs for both the predicated
255 // and non-predicated version of the given loop.
256 bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
257 DenseMap<const Instruction *, CostInfo> &InstCostMap,
258 CostInfo *LoopCost);
259
260 // Returns a set of all the select instructions in the given select groups.
261 SmallDenseMap<const Instruction *, SelectLike, 2>
262 getSImap(const SelectGroups &SIGroups);
263
264 // Returns a map from select-like instructions to the corresponding select
265 // group.
266 SmallDenseMap<const Instruction *, const SelectGroup *, 2>
267 getSGmap(const SelectGroups &SIGroups);
268
269 // Returns the latency cost of a given instruction.
270 std::optional<uint64_t> computeInstCost(const Instruction *I);
271
272 // Returns the misprediction cost of a given select when converted to branch.
273 Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost);
274
275 // Returns the cost of a branch when the prediction is correct.
276 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
277 const SelectLike SI);
278
279 // Returns true if the target architecture supports lowering a given select.
280 bool isSelectKindSupported(const SelectLike SI);
281};
282
283class SelectOptimize : public FunctionPass {
284 SelectOptimizeImpl Impl;
285
286public:
287 static char ID;
288
289 SelectOptimize() : FunctionPass(ID) {}
290
291 bool runOnFunction(Function &F) override {
292 if (skipFunction(F))
293 return false;
294
295 return Impl.runOnFunction(F, *this);
296 }
297
298 void getAnalysisUsage(AnalysisUsage &AU) const override {
299 AU.addRequired<ProfileSummaryInfoWrapperPass>();
300 AU.addRequired<TargetPassConfig>();
301 AU.addRequired<TargetTransformInfoWrapperPass>();
302 AU.addRequired<LoopInfoWrapperPass>();
303 AU.addRequired<BlockFrequencyInfoWrapperPass>();
304 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
305 }
306};
307
308} // namespace
309
312 SelectOptimizeImpl Impl(TM);
313 return Impl.run(F, FAM);
314}
315
316char SelectOptimize::ID = 0;
317
318INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
319 false)
326INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
327 false)
328
329FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
330
331PreservedAnalyses SelectOptimizeImpl::run(Function &F,
333 TSI = TM->getSubtargetImpl(F);
334 TLI = TSI->getTargetLowering();
335
336 // If none of the select types are supported then skip this pass.
337 // This is an optimization pass. Legality issues will be handled by
338 // instruction selection.
339 if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
340 !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
341 !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
342 return PreservedAnalyses::all();
343
344 TTI = &FAM.getResult<TargetIRAnalysis>(F);
345 if (!TTI->enableSelectOptimize())
346 return PreservedAnalyses::all();
347
349 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
350 if (!PSI)
351 reportFatalUsageError("this pass requires the profile-summary module "
352 "analysis to be available");
353 BFI = &FAM.getResult<BlockFrequencyAnalysis>(F);
354
355 // When optimizing for size, selects are preferable over branches.
356 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
357 return PreservedAnalyses::all();
358
359 LI = &FAM.getResult<LoopAnalysis>(F);
360 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
361 TSchedModel.init(TSI);
362
363 bool Changed = optimizeSelects(F);
365}
366
367bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) {
368 TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
369 TSI = TM->getSubtargetImpl(F);
370 TLI = TSI->getTargetLowering();
371
372 // If none of the select types are supported then skip this pass.
373 // This is an optimization pass. Legality issues will be handled by
374 // instruction selection.
378 return false;
379
380 TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
381
382 if (!TTI->enableSelectOptimize())
383 return false;
384
385 LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
386 BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
387 PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
388 ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
389 TSchedModel.init(TSI);
390
391 // When optimizing for size, selects are preferable over branches.
392 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
393 return false;
394
395 return optimizeSelects(F);
396}
397
398bool SelectOptimizeImpl::optimizeSelects(Function &F) {
399 Opts = &getCodeGenOptions(F);
400 // Determine for which select groups it is profitable converting to branches.
401 SelectGroups ProfSIGroups;
402 // Base heuristics apply only to non-loops and outer loops.
403 optimizeSelectsBase(F, ProfSIGroups);
404 // Separate heuristics for inner-most loops.
405 optimizeSelectsInnerLoops(F, ProfSIGroups);
406
407 // Convert to branches the select groups that were deemed
408 // profitable-to-convert.
409 convertProfitableSIGroups(ProfSIGroups);
410
411 // Code modified if at least one select group was converted.
412 return !ProfSIGroups.empty();
413}
414
415void SelectOptimizeImpl::optimizeSelectsBase(Function &F,
416 SelectGroups &ProfSIGroups) {
417 // Collect all the select groups.
418 SelectGroups SIGroups;
419 for (BasicBlock &BB : F) {
420 // Base heuristics apply only to non-loops and outer loops.
421 Loop *L = LI->getLoopFor(&BB);
422 if (L && L->isInnermost())
423 continue;
424 collectSelectGroups(BB, SIGroups);
425 }
426
427 // Determine for which select groups it is profitable converting to branches.
428 findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
429}
430
431void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F,
432 SelectGroups &ProfSIGroups) {
434 // Need to check size on each iteration as we accumulate child loops.
435 for (unsigned long i = 0; i < Loops.size(); ++i)
436 llvm::append_range(Loops, Loops[i]->getSubLoops());
437
438 for (Loop *L : Loops) {
439 if (!L->isInnermost())
440 continue;
441
442 SelectGroups SIGroups;
443 for (BasicBlock *BB : L->getBlocks())
444 collectSelectGroups(*BB, SIGroups);
445
446 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
447 }
448}
449
450/// Returns optimised value on \p IsTrue branch. For SelectInst that would be
451/// either True or False value. For (BinaryOperator) instructions, where the
452/// condition may be skipped, the operation will use a non-conditional operand.
453/// For example, for `or(V,zext(cond))` this function would return V.
454/// However, if the conditional operand on \p IsTrue branch matters, we create a
455/// clone of instruction at the end of that branch \p B and replace the
456/// condition operand with a constant.
457///
458/// Also /p OptSelects contains previously optimised select-like instructions.
459/// If the current value uses one of the optimised values, we can optimise it
460/// further by replacing it with the corresponding value on the given branch
462 SelectOptimizeImpl::SelectLike &SI, bool isTrue,
463 SmallDenseMap<Instruction *, std::pair<Value *, Value *>, 2> &OptSelects,
464 BasicBlock *B) {
465 Value *V = isTrue ? SI.getTrueValue() : SI.getFalseValue();
466 if (V) {
467 if (auto *IV = dyn_cast<Instruction>(V))
468 if (auto It = OptSelects.find(IV); It != OptSelects.end())
469 return isTrue ? It->second.first : It->second.second;
470 return V;
471 }
472
473 auto *BO = cast<BinaryOperator>(SI.getI());
474 assert((BO->getOpcode() == Instruction::Add ||
475 BO->getOpcode() == Instruction::Or ||
476 BO->getOpcode() == Instruction::Sub) &&
477 "Only currently handling Add, Or and Sub binary operators.");
478
479 auto *CBO = BO->clone();
480 auto CondIdx = SI.getConditionOpIndex();
481 auto *AuxI = cast<Instruction>(CBO->getOperand(CondIdx));
482 if (isa<ZExtInst>(AuxI) || isa<LShrOperator>(AuxI)) {
483 CBO->setOperand(CondIdx, ConstantInt::get(CBO->getType(), 1));
484 } else {
485 assert((isa<AShrOperator>(AuxI) || isa<SExtInst>(AuxI)) &&
486 "Unexpected opcode");
487 CBO->setOperand(CondIdx, ConstantInt::getAllOnesValue(CBO->getType()));
488 }
489
490 unsigned OtherIdx = 1 - CondIdx;
491 if (auto *IV = dyn_cast<Instruction>(CBO->getOperand(OtherIdx))) {
492 if (auto It = OptSelects.find(IV); It != OptSelects.end())
493 CBO->setOperand(OtherIdx, isTrue ? It->second.first : It->second.second);
494 }
495 CBO->insertBefore(B->getTerminator()->getIterator());
496 return CBO;
497}
498
499void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
500 for (SelectGroup &ASI : ProfSIGroups) {
501 // The code transformation here is a modified version of the sinking
502 // transformation in CodeGenPrepare::optimizeSelectInst with a more
503 // aggressive strategy of which instructions to sink.
504 //
505 // TODO: eliminate the redundancy of logic transforming selects to branches
506 // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
507 // selects for all cases (with and without profile information).
508
509 // Transform a sequence like this:
510 // start:
511 // %cmp = cmp uge i32 %a, %b
512 // %sel = select i1 %cmp, i32 %c, i32 %d
513 //
514 // Into:
515 // start:
516 // %cmp = cmp uge i32 %a, %b
517 // %cmp.frozen = freeze %cmp
518 // br i1 %cmp.frozen, label %select.true, label %select.false
519 // select.true:
520 // br label %select.end
521 // select.false:
522 // br label %select.end
523 // select.end:
524 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
525 //
526 // %cmp should be frozen, otherwise it may introduce undefined behavior.
527 // In addition, we may sink instructions that produce %c or %d into the
528 // destination(s) of the new branch.
529 // If the true or false blocks do not contain a sunken instruction, that
530 // block and its branch may be optimized away. In that case, one side of the
531 // first branch will point directly to select.end, and the corresponding PHI
532 // predecessor block will be the start block.
533
534 // Find all the instructions that can be soundly sunk to the true/false
535 // blocks. These are instructions that are computed solely for producing the
536 // operands of the select instructions in the group and can be sunk without
537 // breaking the semantics of the LLVM IR (e.g., cannot sink instructions
538 // with side effects).
539 SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices;
540 typedef std::stack<Instruction *>::size_type StackSizeType;
541 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
542 Instruction *SelectWithProfile = nullptr;
543 bool SelectWithProfileIsInverted = false;
544 for (SelectLike &SI : ASI.Selects) {
545 if (!isa<SelectInst>(SI.getI()))
546 continue;
547 // For each select, compute the sinkable dependence chains of the true and
548 // false operands.
549 if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) {
550 std::stack<Instruction *> TrueSlice;
551 getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true, &ASI);
552 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
553 TrueSlices.push_back(TrueSlice);
554 }
555 if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) {
556 if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) {
557 std::stack<Instruction *> FalseSlice;
558 getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true, &ASI);
559 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
560 FalseSlices.push_back(FalseSlice);
561 }
562 }
563 // Also see if the select has profile data that we can propagate later
564 // to the conditional branch.
565 Value *SelectCondition = cast<SelectInst>(SI.getI())->getCondition();
566 if (hasProfMD(*SI.getI()) && ASI.Condition == SelectCondition) {
567 SelectWithProfile = SI.getI();
568 } else if (hasProfMD(*SI.getI()) &&
569 match(SelectCondition, m_Not(m_Value(ASI.Condition)))) {
570 SelectWithProfile = SI.getI();
571 SelectWithProfileIsInverted = true;
572 }
573 }
574 // In the case of multiple select instructions in the same group, the order
575 // of non-dependent instructions (instructions of different dependence
576 // slices) in the true/false blocks appears to affect performance.
577 // Interleaving the slices seems to experimentally be the optimal approach.
578 // This interleaving scheduling allows for more ILP (with a natural downside
579 // of increasing a bit register pressure) compared to a simple ordering of
580 // one whole chain after another. One would expect that this ordering would
581 // not matter since the scheduling in the backend of the compiler would
582 // take care of it, but apparently the scheduler fails to deliver optimal
583 // ILP with a naive ordering here.
584 SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved;
585 for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) {
586 for (auto &S : TrueSlices) {
587 if (!S.empty()) {
588 TrueSlicesInterleaved.push_back(S.top());
589 S.pop();
590 }
591 }
592 }
593 for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) {
594 for (auto &S : FalseSlices) {
595 if (!S.empty()) {
596 FalseSlicesInterleaved.push_back(S.top());
597 S.pop();
598 }
599 }
600 }
601
602 // We split the block containing the select(s) into two blocks.
603 SelectLike &SI = ASI.Selects.front();
604 SelectLike &LastSI = ASI.Selects.back();
605 BasicBlock *StartBlock = SI.getI()->getParent();
606 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI()));
607 // With RemoveDIs turned off, SplitPt can be a dbg.* intrinsic. With
608 // RemoveDIs turned on, SplitPt would instead point to the next
609 // instruction. To match existing dbg.* intrinsic behaviour with RemoveDIs,
610 // tell splitBasicBlock that we want to include any DbgVariableRecords
611 // attached to SplitPt in the splice.
612 SplitPt.setHeadBit(true);
613 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
614 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
615 // Delete the unconditional branch that was just created by the split.
616 StartBlock->getTerminator()->eraseFromParent();
617
618 // Hoist any pseudo and auxiliary instructions that were in-between the
619 // select group before the group, since the true/false values may use them.
621 auto DIt = SI.getI()->getIterator();
622 auto NIt = ASI.Selects.begin();
623 while (&*DIt != LastSI.getI()) {
624 if (NIt != ASI.Selects.end() && &*DIt == NIt->getI())
625 ++NIt;
626 else
627 HoistInstrs.push_back(&*DIt);
628 DIt++;
629 }
630 for (auto *HI : HoistInstrs)
631 HI->moveBefore(SI.getI()->getIterator());
632
633 // Duplicate implementation for DbgRecords, the non-instruction debug-info
634 // format. Helper lambda for moving DbgRecords to the end block.
635 auto TransferDbgRecords = [&](Instruction &I) {
636 for (auto &DbgRecord :
637 llvm::make_early_inc_range(I.getDbgRecordRange())) {
640 EndBlock->getFirstInsertionPt());
641 }
642 };
643
644 // Iterate over all instructions in between SI and LastSI, not including
645 // SI itself. These are all the variable assignments that happen "in the
646 // middle" of the select group.
647 auto R = make_range(std::next(SI.getI()->getIterator()),
648 std::next(LastSI.getI()->getIterator()));
649 llvm::for_each(R, TransferDbgRecords);
650
651 // These are the new basic blocks for the conditional branch.
652 // At least one will become an actual new basic block.
653 BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
654 UncondBrInst *TrueBranch = nullptr, *FalseBranch = nullptr;
655 // Checks if select-like instruction would materialise on the given branch
656 auto HasSelectLike = [](SelectGroup &SG, bool IsTrue) {
657 for (auto &SL : SG.Selects) {
658 if ((IsTrue ? SL.getTrueValue() : SL.getFalseValue()) == nullptr)
659 return true;
660 }
661 return false;
662 };
663 if (!TrueSlicesInterleaved.empty() || HasSelectLike(ASI, true)) {
664 TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink",
665 EndBlock->getParent(), EndBlock);
666 TrueBranch = UncondBrInst::Create(EndBlock, TrueBlock);
667 TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
668 for (Instruction *TrueInst : TrueSlicesInterleaved)
669 TrueInst->moveBefore(TrueBranch->getIterator());
670 }
671 if (!FalseSlicesInterleaved.empty() || HasSelectLike(ASI, false)) {
672 FalseBlock =
673 BasicBlock::Create(EndBlock->getContext(), "select.false.sink",
674 EndBlock->getParent(), EndBlock);
675 FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
676 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
677 for (Instruction *FalseInst : FalseSlicesInterleaved)
678 FalseInst->moveBefore(FalseBranch->getIterator());
679 }
680 // If there was nothing to sink, then arbitrarily choose the 'false' side
681 // for a new input value to the PHI.
682 if (TrueBlock == FalseBlock) {
683 assert(TrueBlock == nullptr &&
684 "Unexpected basic block transform while optimizing select");
685
686 FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false",
687 EndBlock->getParent(), EndBlock);
688 auto *FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
689 FalseBranch->setDebugLoc(SI.getI()->getDebugLoc());
690 }
691
692 // Insert the real conditional branch based on the original condition.
693 // If we did not create a new block for one of the 'true' or 'false' paths
694 // of the condition, it means that side of the branch goes to the end block
695 // directly and the path originates from the start block from the point of
696 // view of the new PHI.
697 BasicBlock *TT, *FT;
698 if (TrueBlock == nullptr) {
699 TT = EndBlock;
700 FT = FalseBlock;
701 TrueBlock = StartBlock;
702 } else if (FalseBlock == nullptr) {
703 TT = TrueBlock;
704 FT = EndBlock;
705 FalseBlock = StartBlock;
706 } else {
707 TT = TrueBlock;
708 FT = FalseBlock;
709 }
710 IRBuilder<> IB(SI.getI());
711 auto *CondFr =
712 IB.CreateFreeze(ASI.Condition, ASI.Condition->getName() + ".frozen");
713
715
716 // Use reverse iterator because later select may use the value of the
717 // earlier select, and we need to propagate value through earlier select
718 // to get the PHI operand.
719 auto InsertionPoint = EndBlock->begin();
720 for (SelectLike &SI : ASI.Selects) {
721 // The select itself is replaced with a PHI Node.
722 PHINode *PN = PHINode::Create(SI.getType(), 2, "");
723 PN->insertBefore(InsertionPoint);
724 PN->takeName(SI.getI());
725 // Current instruction might be a condition of some other group, so we
726 // need to replace it there to avoid dangling pointer
727 if (PN->getType()->isIntegerTy(1)) {
728 for (auto &SG : ProfSIGroups) {
729 if (SG.Condition == SI.getI())
730 SG.Condition = PN;
731 }
732 }
733 SI.getI()->replaceAllUsesWith(PN);
734 auto *TV = getTrueOrFalseValue(SI, true, INS, TrueBlock);
735 auto *FV = getTrueOrFalseValue(SI, false, INS, FalseBlock);
736 INS[PN] = {TV, FV};
737 PN->addIncoming(TV, TrueBlock);
738 PN->addIncoming(FV, FalseBlock);
739 PN->setDebugLoc(SI.getI()->getDebugLoc());
740 ++NumSelectsConverted;
741 }
742 Instruction *CondBr = IB.CreateCondBr(CondFr, TT, FT, SI.getI());
743 if (!ProfcheckDisableMetadataFixes && SelectWithProfile) {
744 CondBr->copyMetadata(*SelectWithProfile, {llvm::LLVMContext::MD_prof});
745 if (SelectWithProfileIsInverted)
746 CondBr->swapProfMetadata();
747 } else {
749 }
750
751 // Remove the old select instructions, now that they are not longer used.
752 for (SelectLike &SI : ASI.Selects)
753 SI.getI()->eraseFromParent();
754 }
755}
756
757void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB,
758 SelectGroups &SIGroups) {
759 // Represents something that can be considered as select instruction.
760 // Auxiliary instruction are instructions that depends on a condition and have
761 // zero or some constant value on True/False branch, such as:
762 // * ZExt(1bit)
763 // * SExt(1bit)
764 // * Not(1bit)
765 // * A(L)Shr(Val), ValBitSize - 1, where there is a condition like `Val <= 0`
766 // earlier in the BB. For conditions that check the sign of the Val compiler
767 // may generate shifts instead of ZExt/SExt.
768 struct SelectLikeInfo {
769 Value *Cond;
770 bool IsAuxiliary;
771 bool IsInverted;
772 unsigned ConditionIdx;
773 };
774
776 // Keeps visited comparisons to help identify AShr/LShr variants of auxiliary
777 // instructions.
779
780 // Check if the instruction is SelectLike or might be part of SelectLike
781 // expression, put information into SelectInfo and return the iterator to the
782 // inserted position.
783 auto ProcessSelectInfo = [&SelectInfo, &SeenCmp](Instruction *I) {
784 if (auto *Cmp = dyn_cast<CmpInst>(I)) {
785 SeenCmp.insert(Cmp);
786 return SelectInfo.end();
787 }
788
789 Value *Cond;
791 Cond->getType()->isIntegerTy(1)) {
792 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
793 return SelectInfo.insert({I, {Cond, true, Inverted, 0}}).first;
794 }
795
796 if (match(I, m_Not(m_Value(Cond)))) {
797 return SelectInfo.insert({I, {Cond, true, true, 0}}).first;
798 }
799
800 // Select instruction are what we are usually looking for.
801 if (match(I, m_Select(m_Value(Cond), m_Value(), m_Value()))) {
802 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
803 return SelectInfo.insert({I, {Cond, false, Inverted, 0}}).first;
804 }
805 Value *Val;
806 ConstantInt *Shift;
807 if (match(I, m_Shr(m_Value(Val), m_ConstantInt(Shift))) &&
808 I->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1) {
809 for (auto *CmpI : SeenCmp) {
810 auto Pred = CmpI->getPredicate();
811 if (Val != CmpI->getOperand(0))
812 continue;
813 if ((Pred == CmpInst::ICMP_SGT &&
814 match(CmpI->getOperand(1), m_ConstantInt<-1>())) ||
816 match(CmpI->getOperand(1), m_Zero())) ||
818 match(CmpI->getOperand(1), m_Zero())) ||
820 match(CmpI->getOperand(1), m_ConstantInt<-1>()))) {
821 bool Inverted =
823 return SelectInfo.insert({I, {CmpI, true, Inverted, 0}}).first;
824 }
825 }
826 return SelectInfo.end();
827 }
828
829 // An BinOp(Aux(X), Y) can also be treated like a select, with condition X
830 // and values Y|1 and Y.
831 // `Aux` can be either `ZExt(1bit)`, `SExt(1bit)` or `XShr(Val), ValBitSize
832 // - 1` `BinOp` can be Add, Sub, Or
833 Value *X;
834 auto MatchZExtOrSExtPattern =
836 auto MatchShiftPattern =
838
839 // This check is unnecessary, but it prevents costly access to the
840 // SelectInfo map.
841 if ((match(I, MatchZExtOrSExtPattern) && X->getType()->isIntegerTy(1)) ||
842 (match(I, MatchShiftPattern) &&
843 X->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1)) {
844 if (I->getOpcode() != Instruction::Add &&
845 I->getOpcode() != Instruction::Sub &&
846 I->getOpcode() != Instruction::Or)
847 return SelectInfo.end();
848
849 // The BinOp(Aux(X), Y) form models a select whose `Aux` widens i1 X to
850 // the BinOp's type. An i1-typed BinOp can't have such an `Aux`: ZExt/SExt
851 // must widen, and the only i1 auxiliaries (`Not`, and the identity
852 // `lshr/ashr i1 %x, 0`) are not ones `getTrueOrFalseValue()` can
853 // materialize. Bail out rather than form a group that would assert.
854 if (I->getType()->isIntegerTy(1))
855 return SelectInfo.end();
856
857 // Iterate through operands and find dependant on recognised sign
858 // extending auxiliary select-like instructions. The operand index does
859 // not matter for Add and Or. However, for Sub, we can only safely
860 // transform when the operand is second.
861 unsigned Idx = I->getOpcode() == Instruction::Sub ? 1 : 0;
862 for (; Idx < 2; Idx++) {
863 auto *Op = I->getOperand(Idx);
864 auto It = SelectInfo.find(Op);
865 if (It != SelectInfo.end() && It->second.IsAuxiliary) {
866 Cond = It->second.Cond;
867 bool Inverted = It->second.IsInverted;
868 return SelectInfo.insert({I, {Cond, false, Inverted, Idx}}).first;
869 }
870 }
871 }
872 return SelectInfo.end();
873 };
874
875 bool AlreadyProcessed = false;
876 BasicBlock::iterator BBIt = BB.begin();
878 while (BBIt != BB.end()) {
879 Instruction *I = &*BBIt++;
881 continue;
882
883 if (!AlreadyProcessed)
884 It = ProcessSelectInfo(I);
885 else
886 AlreadyProcessed = false;
887
888 if (It == SelectInfo.end() || It->second.IsAuxiliary)
889 continue;
890
891 if (!TTI->shouldTreatInstructionLikeSelect(I))
892 continue;
893
894 Value *Cond = It->second.Cond;
895 // Vector conditions are not supported.
896 if (!Cond->getType()->isIntegerTy(1))
897 continue;
898
899 SelectGroup SIGroup = {Cond, {}};
900 SIGroup.Selects.emplace_back(I, It->second.IsInverted,
901 It->second.ConditionIdx);
902
903 // If the select type is not supported, no point optimizing it.
904 // Instruction selection will take care of it.
905 if (!isSelectKindSupported(SIGroup.Selects.front()))
906 continue;
907
908 while (BBIt != BB.end()) {
909 Instruction *NI = &*BBIt;
910 // Pseudo instructions should be skipped and not prevent the
911 // formation of a select group.
912 if (isa<PseudoProbeInst>(NI)) {
913 ++BBIt;
914 continue;
915 }
916
917 It = ProcessSelectInfo(NI);
918 if (It == SelectInfo.end()) {
919 AlreadyProcessed = true;
920 break;
921 }
922
923 // Auxiliary with same condition
924 auto [CurrCond, IsAux, IsRev, CondIdx] = It->second;
925 if (Cond != CurrCond) {
926 AlreadyProcessed = true;
927 break;
928 }
929
930 if (!IsAux)
931 SIGroup.Selects.emplace_back(NI, IsRev, CondIdx);
932 ++BBIt;
933 }
934 LLVM_DEBUG({
935 dbgs() << "New Select group (" << SIGroup.Selects.size() << ") with\n";
936 for (auto &SI : SIGroup.Selects)
937 dbgs() << " " << *SI.getI() << "\n";
938 });
939
940 SIGroups.push_back(SIGroup);
941 }
942}
943
944void SelectOptimizeImpl::findProfitableSIGroupsBase(
945 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
946 for (SelectGroup &ASI : SIGroups) {
947 ++NumSelectOptAnalyzed;
948 if (isConvertToBranchProfitableBase(ASI))
949 ProfSIGroups.push_back(ASI);
950 }
951}
952
955 LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n");
956 ORE->emit(Rem);
957}
958
959void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
960 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
961 NumSelectOptAnalyzed += SIGroups.size();
962 // For each select group in an inner-most loop,
963 // a branch is more preferable than a select/conditional-move if:
964 // i) conversion to branches for all the select groups of the loop satisfies
965 // loop-level heuristics including reducing the loop's critical path by
966 // some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and
967 // ii) the total cost of the select group is cheaper with a branch compared
968 // to its predicated version. The cost is in terms of latency and the cost
969 // of a select group is the cost of its most expensive select instruction
970 // (assuming infinite resources and thus fully leveraging available ILP).
971
972 // Unpredictable selects should never be converted to branches.
973 erase_if(SIGroups, [&](const SelectGroup &ASI) {
974 if (!ASI.isUnpredictable())
975 return false;
976 ++NumSelectUnPred;
977 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
978 ASI.Selects.front().getI());
979 ORmiss << "Not converted to branch because of unpredictable branch. ";
980 EmitAndPrintRemark(ORE, ORmiss);
981 return true;
982 });
983
985 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
986 {Scaled64::getZero(), Scaled64::getZero()}};
987 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
988 !checkLoopHeuristics(L, LoopCost)) {
989 return;
990 }
991
992 for (SelectGroup &ASI : SIGroups) {
993 // Assuming infinite resources, the cost of a group of instructions is the
994 // cost of the most expensive instruction of the group.
995 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
996 for (SelectLike &SI : ASI.Selects) {
997 const auto &ICM = InstCostMap[SI.getI()];
998 SelectCost = std::max(SelectCost, ICM.PredCost);
999 BranchCost = std::max(BranchCost, ICM.NonPredCost);
1000 }
1001 if (BranchCost < SelectCost) {
1002 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti",
1003 ASI.Selects.front().getI());
1004 OR << "Profitable to convert to branch (loop analysis). BranchCost="
1005 << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
1006 << ". ";
1007 EmitAndPrintRemark(ORE, OR);
1008 ++NumSelectConvertedLoop;
1009 ProfSIGroups.push_back(ASI);
1010 } else {
1011 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1012 ASI.Selects.front().getI());
1013 ORmiss << "Select is more profitable (loop analysis). BranchCost="
1014 << BranchCost.toString()
1015 << ", SelectCost=" << SelectCost.toString() << ". ";
1016 EmitAndPrintRemark(ORE, ORmiss);
1017 }
1018 }
1019}
1020
1021bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
1022 const SelectGroup &ASI) {
1023 const SelectLike &SI = ASI.Selects.front();
1024 LLVM_DEBUG(dbgs() << "Analyzing select group containing " << *SI.getI()
1025 << "\n");
1026 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI());
1027 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI());
1028
1029 // Skip cold basic blocks. Better to optimize for size for cold blocks.
1030 if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) {
1031 ++NumSelectColdBB;
1032 ORmiss << "Not converted to branch because of cold basic block. ";
1033 EmitAndPrintRemark(ORE, ORmiss);
1034 return false;
1035 }
1036
1037 // If unpredictable, branch form is less profitable.
1038 if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
1039 ++NumSelectUnPred;
1040 ORmiss << "Not converted to branch because of unpredictable branch. ";
1041 EmitAndPrintRemark(ORE, ORmiss);
1042 return false;
1043 }
1044
1045 // If highly predictable, branch form is more profitable, unless a
1046 // predictable select is inexpensive in the target architecture.
1047 if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
1048 ++NumSelectConvertedHighPred;
1049 OR << "Converted to branch because of highly predictable branch. ";
1050 EmitAndPrintRemark(ORE, OR);
1051 return true;
1052 }
1053
1054 // Look for expensive instructions in the cold operand's (if any) dependence
1055 // slice of any of the selects in the group.
1056 if (hasExpensiveColdOperand(ASI)) {
1057 ++NumSelectConvertedExpColdOperand;
1058 OR << "Converted to branch because of expensive cold operand.";
1059 EmitAndPrintRemark(ORE, OR);
1060 return true;
1061 }
1062
1063 // If latch has a select group with several elements, it is usually profitable
1064 // to convert it to branches. We let `optimizeSelectsInnerLoops` decide if
1065 // conversion is profitable for innermost loops.
1066 auto *BB = SI.getI()->getParent();
1067 auto *L = LI->getLoopFor(BB);
1068 if (L && !L->isInnermost() && L->getLoopLatch() == BB &&
1069 ASI.Selects.size() >= 3) {
1070 OR << "Converted to branch because select group in the latch block is big.";
1071 EmitAndPrintRemark(ORE, OR);
1072 return true;
1073 }
1074
1075 ORmiss << "Not profitable to convert to branch (base heuristic).";
1076 EmitAndPrintRemark(ORE, ORmiss);
1077 return false;
1078}
1079
1081 uint64_t Denominator) {
1082 return (Numerator + (Denominator / 2)) / Denominator;
1083}
1084
1085static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,
1086 uint64_t &TrueVal, uint64_t &FalseVal) {
1087 if (isa<SelectInst>(SI.getI()))
1088 return extractBranchWeights(*SI.getI(), TrueVal, FalseVal);
1089 return false;
1090}
1091
1092bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) {
1093 bool ColdOperand = false;
1094 uint64_t TrueWeight, FalseWeight, TotalWeight;
1095 if (extractBranchWeights(ASI.Selects.front(), TrueWeight, FalseWeight)) {
1096 uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
1097 TotalWeight = TrueWeight + FalseWeight;
1098 // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
1099 ColdOperand = TotalWeight * Opts->cold_operand_threshold > 100 * MinWeight;
1100 } else if (PSI->hasProfileSummary()) {
1101 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1102 ASI.Selects.front().getI());
1103 ORmiss << "Profile data available but missing branch-weights metadata for "
1104 "select instruction. ";
1105 EmitAndPrintRemark(ORE, ORmiss);
1106 }
1107 if (!ColdOperand)
1108 return false;
1109 // Check if the cold path's dependence slice is expensive for any of the
1110 // selects of the group.
1111 for (SelectLike SI : ASI.Selects) {
1112 Instruction *ColdI = nullptr;
1113 uint64_t HotWeight;
1114 if (TrueWeight < FalseWeight) {
1115 ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue());
1116 HotWeight = FalseWeight;
1117 } else {
1118 ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue());
1119 HotWeight = TrueWeight;
1120 }
1121 if (ColdI) {
1122 std::stack<Instruction *> ColdSlice;
1123 getExclBackwardsSlice(ColdI, ColdSlice, SI.getI());
1124 InstructionCost SliceCost = 0;
1125 while (!ColdSlice.empty()) {
1126 SliceCost += TTI->getInstructionCost(ColdSlice.top(),
1128 ColdSlice.pop();
1129 }
1130 // The colder the cold value operand of the select is the more expensive
1131 // the cmov becomes for computing the cold value operand every time. Thus,
1132 // the colder the cold operand is the more its cost counts.
1133 // Get nearest integer cost adjusted for coldness.
1134 InstructionCost AdjSliceCost =
1135 divideNearest(SliceCost * HotWeight, TotalWeight);
1136 if (AdjSliceCost >= Opts->cold_operand_max_cost_multiplier *
1138 return true;
1139 }
1140 }
1141 return false;
1142}
1143
1144// Check if it is safe to move LoadI next to the SI.
1145// Conservatively assume it is safe only if there is no instruction
1146// modifying memory in-between the load and the select instruction.
1148 // Assume loads from different basic blocks are unsafe to move.
1149 if (LoadI->getParent() != SI->getParent())
1150 return false;
1151 auto It = LoadI->getIterator();
1152 while (&*It != SI) {
1153 if (It->mayWriteToMemory())
1154 return false;
1155 It++;
1156 }
1157 return true;
1158}
1159
1160// For a given source instruction, collect its backwards dependence slice
1161// consisting of instructions exclusively computed for the purpose of producing
1162// the operands of the source instruction. As an approximation
1163// (sufficiently-accurate in practice), we populate this set with the
1164// instructions of the backwards dependence slice that only have one-use and
1165// form an one-use chain that leads to the source instruction.
1166void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I,
1167 std::stack<Instruction *> &Slice,
1168 Instruction *SI, bool ForSinking,
1169 const SelectGroup *Group) {
1171 std::queue<Instruction *> Worklist;
1172 Worklist.push(I);
1173 while (!Worklist.empty()) {
1174 Instruction *II = Worklist.front();
1175 Worklist.pop();
1176
1177 // Avoid cycles.
1178 if (!Visited.insert(II).second)
1179 continue;
1180
1181 if (!II->hasOneUse())
1182 continue;
1183
1184 // Cannot soundly sink instructions with side-effects.
1185 // Terminator or phi instructions cannot be sunk.
1186 // Avoid sinking other select instructions (should be handled separetely).
1187 if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() ||
1189 continue;
1190
1191 // Select-like members of the group are replaced separately, and their
1192 // operands may still be needed on the other branch.
1193 if (ForSinking && Group &&
1194 llvm::any_of(Group->Selects, [&](auto &S) { return S.getI() == II; }))
1195 continue;
1196
1197 // Avoid sinking loads in order not to skip state-modifying instructions,
1198 // that may alias with the loaded address.
1199 // Only allow sinking of loads within the same basic block that are
1200 // conservatively proven to be safe.
1201 if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI))
1202 continue;
1203
1204 // Avoid considering instructions with less frequency than the source
1205 // instruction (i.e., avoid colder code regions of the dependence slice).
1206 if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
1207 continue;
1208
1209 // Eligible one-use instruction added to the dependence slice.
1210 Slice.push(II);
1211
1212 // Explore all the operands of the current instruction to expand the slice.
1213 for (Value *Op : II->operand_values())
1214 if (auto *OpI = dyn_cast<Instruction>(Op))
1215 Worklist.push(OpI);
1216 }
1217}
1218
1219bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) {
1220 uint64_t TrueWeight, FalseWeight;
1221 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1222 uint64_t Max = std::max(TrueWeight, FalseWeight);
1223 uint64_t Sum = TrueWeight + FalseWeight;
1224 if (Sum != 0) {
1225 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
1226 if (Probability > TTI->getPredictableBranchThreshold())
1227 return true;
1228 }
1229 }
1230 return false;
1231}
1232
1233bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L,
1234 const CostInfo LoopCost[2]) {
1235 // Loop-level checks to determine if a non-predicated version (with branches)
1236 // of the loop is more profitable than its predicated version.
1237
1238 if (!Opts->select_opti_loop_level_heuristics)
1239 return true;
1240
1241 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
1242 &*L->getHeader()->getFirstNonPHIIt());
1243
1244 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1245 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1246 ORmissL << "No select conversion in the loop due to no reduction of loop's "
1247 "critical path. ";
1248 EmitAndPrintRemark(ORE, ORmissL);
1249 return false;
1250 }
1251
1252 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1253 LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1254
1255 // Profitably converting to branches need to reduce the loop's critical path
1256 // by at least some threshold (absolute gain of GainCycleThreshold cycles and
1257 // relative gain of 12.5%).
1258 if (Gain[1] < Scaled64::get(Opts->select_opti_loop_cycle_gain_threshold) ||
1259 Gain[1] * Scaled64::get(Opts->select_opti_loop_relative_gain_threshold) <
1260 LoopCost[1].PredCost) {
1261 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1262 ORmissL << "No select conversion in the loop due to small reduction of "
1263 "loop's critical path. Gain="
1264 << Gain[1].toString()
1265 << ", RelativeGain=" << RelativeGain.toString() << "%. ";
1266 EmitAndPrintRemark(ORE, ORmissL);
1267 return false;
1268 }
1269
1270 // If the loop's critical path involves loop-carried dependences, the gradient
1271 // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
1272 // This check ensures that the latency reduction for the loop's critical path
1273 // keeps decreasing with sufficient rate beyond the two analyzed loop
1274 // iterations.
1275 if (Gain[1] > Gain[0]) {
1276 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1277 (LoopCost[1].PredCost - LoopCost[0].PredCost);
1278 if (GradientGain <
1279 Scaled64::get(Opts->select_opti_loop_gradient_gain_threshold)) {
1280 ORmissL << "No select conversion in the loop due to small gradient gain. "
1281 "GradientGain="
1282 << GradientGain.toString() << "%. ";
1283 EmitAndPrintRemark(ORE, ORmissL);
1284 return false;
1285 }
1286 }
1287 // If the gain decreases it is not profitable to convert.
1288 else if (Gain[1] < Gain[0]) {
1289 ORmissL
1290 << "No select conversion in the loop due to negative gradient gain. ";
1291 EmitAndPrintRemark(ORE, ORmissL);
1292 return false;
1293 }
1294
1295 // Non-predicated version of the loop is more profitable than its
1296 // predicated version.
1297 return true;
1298}
1299
1300// Computes instruction and loop-critical-path costs for both the predicated
1301// and non-predicated version of the given loop.
1302// Returns false if unable to compute these costs due to invalid cost of loop
1303// instruction(s).
1304bool SelectOptimizeImpl::computeLoopCosts(
1305 const Loop *L, const SelectGroups &SIGroups,
1306 DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
1307 LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop "
1308 << L->getHeader()->getName() << "\n");
1309 const auto SImap = getSImap(SIGroups);
1310 const auto SGmap = getSGmap(SIGroups);
1311 // Compute instruction and loop-critical-path costs across two iterations for
1312 // both predicated and non-predicated version.
1313 const unsigned Iterations = 2;
1314 for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
1315 // Cost of the loop's critical path.
1316 CostInfo &MaxCost = LoopCost[Iter];
1317 for (BasicBlock *BB : L->getBlocks()) {
1318 for (const Instruction &I : *BB) {
1320 continue;
1321 // Compute the predicated and non-predicated cost of the instruction.
1322 Scaled64 IPredCost = Scaled64::getZero(),
1323 INonPredCost = Scaled64::getZero();
1324
1325 // Assume infinite resources that allow to fully exploit the available
1326 // instruction-level parallelism.
1327 // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
1328 for (const Use &U : I.operands()) {
1329 auto UI = dyn_cast<Instruction>(U.get());
1330 if (!UI)
1331 continue;
1332 if (auto It = InstCostMap.find(UI); It != InstCostMap.end()) {
1333 IPredCost = std::max(IPredCost, It->second.PredCost);
1334 INonPredCost = std::max(INonPredCost, It->second.NonPredCost);
1335 }
1336 }
1337 auto ILatency = computeInstCost(&I);
1338 if (!ILatency) {
1339 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
1340 ORmissL << "Invalid instruction cost preventing analysis and "
1341 "optimization of the inner-most loop containing this "
1342 "instruction. ";
1343 EmitAndPrintRemark(ORE, ORmissL);
1344 return false;
1345 }
1346 IPredCost += Scaled64::get(*ILatency);
1347 INonPredCost += Scaled64::get(*ILatency);
1348
1349 // For a select that can be converted to branch,
1350 // compute its cost as a branch (non-predicated cost).
1351 //
1352 // BranchCost = PredictedPathCost + MispredictCost
1353 // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
1354 // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
1355 if (auto It = SImap.find(&I); It != SImap.end()) {
1356 auto SI = It->second;
1357 const auto *SG = SGmap.at(&I);
1358 Scaled64 TrueOpCost = SI.getOpCostOnBranch(true, InstCostMap, TTI);
1359 Scaled64 FalseOpCost = SI.getOpCostOnBranch(false, InstCostMap, TTI);
1360 Scaled64 PredictedPathCost =
1361 getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
1362
1363 Scaled64 CondCost = Scaled64::getZero();
1364 if (auto *CI = dyn_cast<Instruction>(SG->Condition))
1365 if (auto It = InstCostMap.find(CI); It != InstCostMap.end())
1366 CondCost = It->second.NonPredCost;
1367 Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
1368
1369 INonPredCost = PredictedPathCost + MispredictCost;
1370 }
1371 LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/"
1372 << INonPredCost << " for " << I << "\n");
1373
1374 InstCostMap[&I] = {IPredCost, INonPredCost};
1375 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1376 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1377 }
1378 }
1379 LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1
1380 << " MaxCost = " << MaxCost.PredCost << " "
1381 << MaxCost.NonPredCost << "\n");
1382 }
1383 return true;
1384}
1385
1387SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) {
1389 for (const SelectGroup &ASI : SIGroups)
1390 for (const SelectLike &SI : ASI.Selects)
1391 SImap.try_emplace(SI.getI(), SI);
1392 return SImap;
1393}
1394
1396SelectOptimizeImpl::getSGmap(const SelectGroups &SIGroups) {
1398 for (const SelectGroup &ASI : SIGroups)
1399 for (const SelectLike &SI : ASI.Selects)
1400 SImap.try_emplace(SI.getI(), &ASI);
1401 return SImap;
1402}
1403
1404std::optional<uint64_t>
1405SelectOptimizeImpl::computeInstCost(const Instruction *I) {
1406 InstructionCost ICost =
1407 TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
1408 if (ICost.isValid())
1409 return std::optional<uint64_t>(ICost.getValue());
1410 return std::nullopt;
1411}
1412
1414SelectOptimizeImpl::getMispredictionCost(const SelectLike SI,
1415 const Scaled64 CondCost) {
1416 uint64_t MispredictPenalty = TSI->getMispredictionPenalty();
1417
1418 // Account for the default misprediction rate when using a branch
1419 // (conservatively set to 25% by default).
1420 uint64_t MispredictRate = Opts->mispredict_default_rate;
1421 // If the select condition is obviously predictable, then the misprediction
1422 // rate is zero.
1423 if (isSelectHighlyPredictable(SI))
1424 MispredictRate = 0;
1425
1426 // CondCost is included to account for cases where the computation of the
1427 // condition is part of a long dependence chain (potentially loop-carried)
1428 // that would delay detection of a misprediction and increase its cost.
1429 Scaled64 MispredictCost =
1430 std::max(Scaled64::get(MispredictPenalty), CondCost) *
1431 Scaled64::get(MispredictRate);
1432 MispredictCost /= Scaled64::get(100);
1433
1434 return MispredictCost;
1435}
1436
1437// Returns the cost of a branch when the prediction is correct.
1438// TrueCost * TrueProbability + FalseCost * FalseProbability.
1440SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1441 const SelectLike SI) {
1442 Scaled64 PredPathCost;
1443 uint64_t TrueWeight, FalseWeight;
1444 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1445 uint64_t SumWeight = TrueWeight + FalseWeight;
1446 if (SumWeight != 0) {
1447 PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1448 FalseCost * Scaled64::get(FalseWeight);
1449 PredPathCost /= Scaled64::get(SumWeight);
1450 return PredPathCost;
1451 }
1452 }
1453 // Without branch weight metadata, we assume 75% for the one path and 25% for
1454 // the other, and pick the result with the biggest cost.
1455 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1456 FalseCost * Scaled64::get(3) + TrueCost);
1457 PredPathCost /= Scaled64::get(4);
1458 return PredPathCost;
1459}
1460
1461bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) {
1463 if (SI.getType()->isVectorTy())
1465 else
1467 return TLI->isSelectSupported(SelectKind);
1468}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Hardware Loops
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:667
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI)
static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, DiagnosticInfoOptimizationBase &Rem)
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition blake3_impl.h:83
AnalysisUsage & addRequired()
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
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:236
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
iterator end() const
iterator begin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool hasProfileSummary() const
Returns true if profile summary is available.
bool isColdBlock(const BBType *BB, BFIT *BFI) const
Returns true if BasicBlock BB is considered cold.
Simple representation of a scaled number.
static ScaledNumber get(uint64_t N)
static ScaledNumber getZero()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
virtual bool isSelectSupported(SelectSupportKind) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual unsigned getMispredictionPenalty() const
Return the number of extra cycles the processor takes to recover from a branch misprediction.
virtual const TargetLowering * getTargetLowering() const
Wrapper pass for TargetTransformInfo.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const
This is an approximation of reciprocal throughput of a math/logic op.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
InstructionCost Cost
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI FunctionPass * createSelectOptimizePass()
This pass converts conditional moves to conditional jumps when profitable.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
TargetTransformInfo TTI
LLVM_ABI bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177