1//===- InstCombineInternal.h - InstCombine pass internals -------*- C++ -*-===//
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/// \file
10///
11/// This file provides internal interfaces used to implement the InstCombine.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17
18#include "InstCombineCLOptions.h"
19#include "llvm/ADT/PostOrderIterator.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/TargetFolder.h"
23#include "llvm/Analysis/ValueTracking.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/InstVisitor.h"
26#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/ProfDataUtils.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/KnownBits.h"
31#include "llvm/Support/KnownFPClass.h"
32#include "llvm/Transforms/InstCombine/InstCombiner.h"
33#include "llvm/Transforms/Utils/Local.h"
34#include <cassert>
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Utils/InstructionWorklist.h"
38
39// Let's guesstimate that most often we will end up visiting/producing
40// fairly small number of new instructions.
41static constexpr unsigned NegatorMaxNodesSSO = 16;
42
43namespace llvm {
44
45class AAResults;
46class APInt;
47class AssumptionCache;
48class BlockFrequencyInfo;
49class DataLayout;
50class DominatorTree;
51class GEPOperator;
52class GlobalVariable;
53class OptimizationRemarkEmitter;
54class ProfileSummaryInfo;
55class TargetLibraryInfo;
56class User;
57
58/// Enum to specify how shift operations should be evaluated in
59/// canEvaluateShifted.
60/// Lossy: Allows lossy transformations
61/// Signed: Requires lossless transformation, using ashr to restore for shl,
62/// or represents ashr handling for right shifts
63/// Unsigned: Requires lossless transformation, using lshr to restore for shl,
64/// or represents lshr handling for right shifts
65enum class ShiftSemantics { Lossy, Signed, Unsigned };
66
67class LLVM_LIBRARY_VISIBILITY InstCombinerImpl final
68 : public InstCombiner,
69 public InstVisitor<InstCombinerImpl, Instruction *> {
70public:
71 InstCombinerImpl(InstructionWorklist &Worklist, Function &F, AAResults *AA,
72 AssumptionCache &AC, TargetLibraryInfo &TLI,
73 TargetTransformInfo &TTI, DominatorTree &DT,
74 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
75 BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI,
76 const DataLayout &DL,
77 ReversePostOrderTraversal<BasicBlock *> &RPOT,
78 const InstCombineCLOptions &CLOpts)
79 : InstCombiner(Worklist, F, AA, AC, TLI, TTI, DT, ORE, BFI, BPI, PSI, DL,
80 RPOT),
81 CLOpts(CLOpts) {}
82
83 ~InstCombinerImpl() override = default;
84
85 const InstCombineCLOptions &CLOpts;
86
87 /// Perform early cleanup and prepare the InstCombine worklist.
88 bool prepareWorklist(Function &F);
89
90 /// Run the combiner over the entire worklist until it is empty.
91 ///
92 /// \returns true if the IR is changed.
93 bool run();
94
95 // Visitation implementation - Implement instruction combining for different
96 // instruction types. The semantics are as follows:
97 // Return Value:
98 // null - No change was made
99 // I - Change was made, I is still valid, I may be dead though
100 // otherwise - Change was made, replace I with returned instruction
101 //
102 Instruction *visitFNeg(UnaryOperator &I);
103 Instruction *visitAdd(BinaryOperator &I);
104 Instruction *visitFAdd(BinaryOperator &I);
105 Value *OptimizePointerDifference(
106 Value *LHS, Value *RHS, Type *Ty, bool isNUW);
107 Instruction *visitSub(BinaryOperator &I);
108 Instruction *visitFSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *foldPowiReassoc(BinaryOperator &I);
111 Instruction *foldFMulReassoc(BinaryOperator &I);
112 Instruction *visitFMul(BinaryOperator &I);
113 Instruction *visitURem(BinaryOperator &I);
114 Instruction *visitSRem(BinaryOperator &I);
115 Instruction *visitFRem(BinaryOperator &I);
116 bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
117 Instruction *commonIDivRemTransforms(BinaryOperator &I);
118 Instruction *commonIRemTransforms(BinaryOperator &I);
119 Instruction *commonIDivTransforms(BinaryOperator &I);
120 Instruction *visitUDiv(BinaryOperator &I);
121 Instruction *visitSDiv(BinaryOperator &I);
122 Instruction *visitFDiv(BinaryOperator &I);
123 Value *simplifyRangeCheck(CmpPredicate PredL, Value *LHS0, Value *LHS1,
124 CmpPredicate PredR, Value *RHS0, Value *RHS1,
125 Instruction *CtxI, bool Inverted);
126 Instruction *FoldOrOfLogicalAnds(Value *Op0, Value *Op1);
127 Instruction *visitAnd(BinaryOperator &I);
128 Instruction *visitOr(BinaryOperator &I);
129 bool sinkNotIntoLogicalOp(Instruction &I);
130 bool sinkNotIntoOtherHandOfLogicalOp(Instruction &I);
131 Instruction *visitXor(BinaryOperator &I);
132 Instruction *visitShl(BinaryOperator &I);
133 Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
134 BinaryOperator *Sh0, const SimplifyQuery &SQ,
135 bool AnalyzeForSignBitExtraction = false);
136 Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
137 BinaryOperator &I);
138 Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
139 BinaryOperator &OldAShr);
140 Instruction *visitAShr(BinaryOperator &I);
141 Instruction *visitLShr(BinaryOperator &I);
142 Instruction *commonShiftTransforms(BinaryOperator &I);
143 Instruction *visitFCmpInst(FCmpInst &I);
144 CmpInst *canonicalizeICmpPredicate(CmpInst &I);
145 Instruction *visitICmpInst(ICmpInst &I);
146 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
147 BinaryOperator &I);
148 Instruction *commonCastTransforms(CastInst &CI);
149 Instruction *visitTrunc(TruncInst &CI);
150 Instruction *visitZExt(ZExtInst &Zext);
151 Instruction *visitSExt(SExtInst &Sext);
152 Instruction *visitFPTrunc(FPTruncInst &CI);
153 Instruction *visitFPExt(CastInst &CI);
154 Instruction *visitFPToUI(FPToUIInst &FI);
155 Instruction *visitFPToSI(FPToSIInst &FI);
156 Instruction *visitUIToFP(CastInst &CI);
157 Instruction *visitSIToFP(CastInst &CI);
158 Instruction *visitPtrToInt(PtrToIntInst &CI);
159 Instruction *visitPtrToAddr(PtrToAddrInst &CI);
160 Instruction *visitIntToPtr(IntToPtrInst &CI);
161 Instruction *visitBitCast(BitCastInst &CI);
162 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
163 template <typename FPToIntTy> Instruction *foldItoFPtoI(FPToIntTy &FI);
164 Instruction *visitSelectInst(SelectInst &SI);
165 Instruction *foldShuffledIntrinsicOperands(IntrinsicInst *II);
166 Value *foldReversedIntrinsicOperands(IntrinsicInst *II);
167 Instruction *visitCallInst(CallInst &CI);
168 Instruction *visitInvokeInst(InvokeInst &II);
169 Instruction *visitCallBrInst(CallBrInst &CBI);
170
171 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
172 Instruction *visitPHINode(PHINode &PN);
173 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
174 Instruction *visitGEPOfGEP(GetElementPtrInst &GEP, GEPOperator *Src);
175 Instruction *visitAllocaInst(AllocaInst &AI);
176 Instruction *visitAllocSite(Instruction &FI);
177 Instruction *visitFree(CallInst &FI, Value *FreedOp);
178 Instruction *visitLoadInst(LoadInst &LI);
179 Instruction *visitStoreInst(StoreInst &SI);
180 Instruction *visitAtomicRMWInst(AtomicRMWInst &SI);
181 Instruction *visitUncondBrInst(UncondBrInst &BI);
182 Instruction *visitCondBrInst(CondBrInst &BI);
183 Instruction *visitFenceInst(FenceInst &FI);
184 Instruction *visitSwitchInst(SwitchInst &SI);
185 Instruction *visitReturnInst(ReturnInst &RI);
186 Instruction *visitUnreachableInst(UnreachableInst &I);
187 Instruction *
188 foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI);
189 Instruction *visitInsertValueInst(InsertValueInst &IV);
190 Instruction *visitInsertElementInst(InsertElementInst &IE);
191 Instruction *visitExtractElementInst(ExtractElementInst &EI);
192 Instruction *simplifyBinOpSplats(ShuffleVectorInst &SVI);
193 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
194 Instruction *visitExtractValueInst(ExtractValueInst &EV);
195 Instruction *visitLandingPadInst(LandingPadInst &LI);
196 Instruction *visitVAEndInst(VAEndInst &I);
197 Value *pushFreezeToPreventPoisonFromPropagating(FreezeInst &FI);
198 bool freezeOtherUses(FreezeInst &FI);
199 Instruction *foldFreezeIntoRecurrence(FreezeInst &I, PHINode *PN);
200 Instruction *visitFreeze(FreezeInst &I);
201
202 /// Specify what to return for unhandled instructions.
203 Instruction *visitInstruction(Instruction &I) { return nullptr; }
204
205 /// True when DB dominates all uses of DI except UI.
206 /// UI must be in the same block as DI.
207 /// The routine checks that the DI parent and DB are different.
208 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
209 const BasicBlock *DB) const;
210
211 /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
212 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
213 const unsigned SIOpd);
214
215 LoadInst *combineLoadToNewType(LoadInst &LI, Type *NewTy,
216 const Twine &Suffix = "");
217
218 /// Check if fmul \p MulVal, +0.0 will yield +0.0 (or signed zero is
219 /// ignorable).
220 bool fmulByZeroIsZero(Value *MulVal, FastMathFlags FMF,
221 const Instruction *CtxI) const;
222
223 std::optional<std::pair<Intrinsic::ID, SmallVector<Value *, 3>>>
224 convertOrOfShiftsToFunnelShift(Instruction &Or);
225
226private:
227 bool annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI);
228 bool isDesirableIntType(unsigned BitWidth) const;
229 bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
230 bool shouldChangeType(Type *From, Type *To) const;
231 Value *dyn_castNegVal(Value *V) const;
232
233 /// Classify whether a cast is worth optimizing.
234 ///
235 /// This is a helper to decide whether the simplification of
236 /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
237 ///
238 /// \param CI The cast we are interested in.
239 ///
240 /// \return true if this cast actually results in any code being generated and
241 /// if it cannot already be eliminated by some other transformation.
242 bool shouldOptimizeCast(CastInst *CI);
243
244 /// Try to optimize a sequence of instructions checking if an operation
245 /// on LHS and RHS overflows.
246 ///
247 /// If this overflow check is done via one of the overflow check intrinsics,
248 /// then CtxI has to be the call instruction calling that intrinsic. If this
249 /// overflow check is done by arithmetic followed by a compare, then CtxI has
250 /// to be the arithmetic instruction.
251 ///
252 /// If a simplification is possible, stores the simplified result of the
253 /// operation in OperationResult and result of the overflow check in
254 /// OverflowResult, and return true. If no simplification is possible,
255 /// returns false.
256 bool OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, bool IsSigned,
257 Value *LHS, Value *RHS,
258 Instruction &CtxI, Value *&OperationResult,
259 Constant *&OverflowResult);
260
261 Instruction *visitCallBase(CallBase &Call);
262 Instruction *tryOptimizeCall(CallInst *CI);
263 bool transformConstExprCastCall(CallBase &Call);
264 Instruction *transformCallThroughTrampoline(CallBase &Call,
265 IntrinsicInst &Tramp);
266
267 /// Try to optimize a call to the result of a ptrauth intrinsic, potentially
268 /// into the ptrauth call bundle:
269 /// - call(ptrauth.resign(p)), ["ptrauth"()] -> call p, ["ptrauth"()]
270 /// - call(ptrauth.sign(p)), ["ptrauth"()] -> call p
271 /// as long as the key/discriminator are the same in sign and auth-bundle,
272 /// and we don't change the key in the bundle (to a potentially-invalid key.)
273 Instruction *foldPtrAuthIntrinsicCallee(CallBase &Call);
274
275 /// Try to optimize a call to a ptrauth constant, into its ptrauth bundle:
276 /// call(ptrauth(f)), ["ptrauth"()] -> call f
277 /// as long as the key/discriminator are the same in constant and bundle.
278 Instruction *foldPtrAuthConstantCallee(CallBase &Call);
279
280 // Return (a, b) if (LHS, RHS) is known to be (a, b) or (b, a).
281 // Otherwise, return std::nullopt
282 // Currently it matches:
283 // - LHS = (select c, a, b), RHS = (select c, b, a)
284 // - LHS = (phi [a, BB0], [b, BB1]), RHS = (phi [b, BB0], [a, BB1])
285 // - LHS = min(a, b), RHS = max(a, b)
286 std::optional<std::pair<Value *, Value *>> matchSymmetricPair(Value *LHS,
287 Value *RHS);
288
289 Value *simplifyMaskedLoad(IntrinsicInst &II);
290 Instruction *simplifyMaskedStore(IntrinsicInst &II);
291 Instruction *simplifyMaskedGather(IntrinsicInst &II);
292 Instruction *simplifyMaskedScatter(IntrinsicInst &II);
293
294 /// Transform (zext icmp) to bitwise / integer operations in order to
295 /// eliminate it.
296 ///
297 /// \param ICI The icmp of the (zext icmp) pair we are interested in.
298 /// \parem CI The zext of the (zext icmp) pair we are interested in.
299 ///
300 /// \return null if the transformation cannot be performed. If the
301 /// transformation can be performed the new instruction that replaces the
302 /// (zext icmp) pair will be returned.
303 Instruction *transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext);
304
305 Instruction *transformSExtICmp(ICmpInst *Cmp, SExtInst &Sext);
306
307 bool willNotOverflowSignedAdd(const WithCache<const Value *> &LHS,
308 const WithCache<const Value *> &RHS,
309 const Instruction &CtxI) const {
310 return computeOverflowForSignedAdd(LHS, RHS, CtxI: &CtxI) ==
311 OverflowResult::NeverOverflows;
312 }
313
314 bool willNotOverflowUnsignedAdd(const WithCache<const Value *> &LHS,
315 const WithCache<const Value *> &RHS,
316 const Instruction &CtxI) const {
317 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI: &CtxI) ==
318 OverflowResult::NeverOverflows;
319 }
320
321 bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
322 const Instruction &CtxI, bool IsSigned) const {
323 return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CtxI)
324 : willNotOverflowUnsignedAdd(LHS, RHS, CtxI);
325 }
326
327 bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
328 const Instruction &CtxI) const {
329 return computeOverflowForSignedSub(LHS, RHS, CtxI: &CtxI) ==
330 OverflowResult::NeverOverflows;
331 }
332
333 bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
334 const Instruction &CtxI) const {
335 return computeOverflowForUnsignedSub(LHS, RHS, CtxI: &CtxI) ==
336 OverflowResult::NeverOverflows;
337 }
338
339 bool willNotOverflowSub(const Value *LHS, const Value *RHS,
340 const Instruction &CtxI, bool IsSigned) const {
341 return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CtxI)
342 : willNotOverflowUnsignedSub(LHS, RHS, CtxI);
343 }
344
345 bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
346 const Instruction &CtxI) const {
347 return computeOverflowForSignedMul(LHS, RHS, CtxI: &CtxI) ==
348 OverflowResult::NeverOverflows;
349 }
350
351 bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
352 const Instruction &CtxI,
353 bool IsNSW = false) const {
354 return computeOverflowForUnsignedMul(LHS, RHS, CtxI: &CtxI, IsNSW) ==
355 OverflowResult::NeverOverflows;
356 }
357
358 bool willNotOverflowMul(const Value *LHS, const Value *RHS,
359 const Instruction &CtxI, bool IsSigned) const {
360 return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CtxI)
361 : willNotOverflowUnsignedMul(LHS, RHS, CtxI);
362 }
363
364 bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
365 const Value *RHS, const Instruction &CtxI,
366 bool IsSigned) const {
367 switch (Opcode) {
368 case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CtxI, IsSigned);
369 case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CtxI, IsSigned);
370 case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CtxI, IsSigned);
371 default: llvm_unreachable("Unexpected opcode for overflow query");
372 }
373 }
374
375 Value *EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP = false);
376 /// Emit sum of multiple GEP offsets. The GEPs are processed in reverse
377 /// order.
378 Value *EmitGEPOffsets(ArrayRef<GEPOperator *> GEPs, GEPNoWrapFlags NW,
379 Type *IdxTy, bool RewriteGEPs);
380 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
381 Instruction *foldBitcastExtElt(ExtractElementInst &ExtElt);
382 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
383 Instruction *foldFBinOpOfIntCasts(BinaryOperator &I);
384 // Should only be called by `foldFBinOpOfIntCasts`.
385 Instruction *foldFBinOpOfIntCastsFromSign(
386 BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
387 Constant *Op1FpC, SmallVectorImpl<WithCache<const Value *>> &OpsKnown);
388 Instruction *foldBinopOfSextBoolToSelect(BinaryOperator &I);
389 Instruction *narrowBinOp(TruncInst &Trunc);
390 Instruction *narrowMaskedBinOp(BinaryOperator &And);
391 Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
392 Instruction *narrowFunnelShift(TruncInst &Trunc);
393 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
394 Instruction *matchSAddSubSat(IntrinsicInst &MinMax1);
395 Instruction *foldNot(BinaryOperator &I);
396 Instruction *foldBinOpOfDisplacedShifts(BinaryOperator &I);
397
398 /// Determine if a pair of casts can be replaced by a single cast.
399 ///
400 /// \param CI1 The first of a pair of casts.
401 /// \param CI2 The second of a pair of casts.
402 ///
403 /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
404 /// Instruction::CastOps value for a cast that can replace the pair, casting
405 /// CI1->getSrcTy() to CI2->getDstTy().
406 ///
407 /// \see CastInst::isEliminableCastPair
408 Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
409 const CastInst *CI2);
410 Value *simplifyIntToPtrRoundTripCast(Value *Val);
411
412 Value *foldAndOrOfICmps(Value *LHS, Value *RHS, Instruction &I, bool IsAnd,
413 bool IsLogical = false);
414 Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Xor);
415
416 Value *foldEqOfParts(Value *Cmp0, Value *Cmp1, bool IsAnd);
417
418 Value *foldAndOrOfICmpsUsingRanges(CmpPredicate PredL, Value *LHS0,
419 Value *LHS1, bool LHSOneUse,
420 CmpPredicate PredR, Value *RHS0,
421 Value *RHS1, bool RHSOneUse, bool IsAnd);
422
423 /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
424 /// NOTE: Unlike most of instcombine, this returns a Value which should
425 /// already be inserted into the function.
426 Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd,
427 bool IsLogicalSelect = false);
428
429 Instruction *foldLogicOfIsFPClass(BinaryOperator &Operator, Value *LHS,
430 Value *RHS);
431
432 Value *foldBooleanAndOr(Value *LHS, Value *RHS, Instruction &I, bool IsAnd,
433 bool IsLogical);
434
435 Value *reassociateBooleanAndOr(Value *LHS, Value *X, Value *Y, Instruction &I,
436 bool IsAnd, bool RHSIsLogical);
437
438 Value *foldDisjointOr(Value *LHS, Value *RHS);
439
440 Value *reassociateDisjointOr(Value *LHS, Value *RHS);
441
442 Instruction *
443 canonicalizeConditionalNegationViaMathToSelect(BinaryOperator &i);
444
445 Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D,
446 bool InvertFalseVal = false);
447 Value *getSelectCondition(Value *A, Value *B, bool ABIsTheSame);
448
449 bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
450 ShiftSemantics Semantics, Instruction *CtxI);
451 Value *getShiftedValue(Value *V, unsigned NumBits, bool IsLeftShift,
452 ShiftSemantics Semantics);
453
454 Instruction *foldLShrOverflowBit(BinaryOperator &I);
455 Instruction *foldExtractOfOverflowIntrinsic(ExtractValueInst &EV);
456 Instruction *foldIntrinsicWithOverflowCommon(IntrinsicInst *II);
457 Instruction *foldIntrinsicIsFPClass(IntrinsicInst &II);
458 Instruction *foldFPSignBitOps(BinaryOperator &I);
459 Instruction *foldFDivConstantDivisor(BinaryOperator &I);
460
461 // Optimize one of these forms:
462 // and i1 Op, SI / select i1 Op, i1 SI, i1 false (if IsAnd = true)
463 // or i1 Op, SI / select i1 Op, i1 true, i1 SI (if IsAnd = false)
464 // into simplier select instruction using isImpliedCondition.
465 Instruction *foldAndOrOfSelectUsingImpliedCond(Value *Op, SelectInst &SI,
466 bool IsAnd);
467
468 Instruction *hoistFNegAboveFMulFDiv(Value *FNegOp, Instruction &FMFSource);
469
470 /// Simplify \p V given that it is known to be non-null.
471 /// Returns the simplified value if possible, otherwise returns nullptr.
472 /// If \p UseProvenance is true, the simplification will use provenance-based
473 /// reasoning (if the pointer is known to be dereferenceable in an
474 /// address-space where null is not defined).
475 Value *simplifyNonNullOperand(Value *V, bool UseProvenance,
476 unsigned Depth = 0);
477
478 /// Create `select C, S1, S2`. Use only when the profile cannot be calculated
479 /// from existing profile metadata: if the Function has profiles, this will
480 /// set the profile of this select to "unknown".
481 SelectInst *
482 createSelectInstWithUnknownProfile(Value *C, Value *S1, Value *S2,
483 const Twine &NameStr = "",
484 InsertPosition InsertBefore = nullptr) {
485 auto *Sel = SelectInst::Create(C, S1, S2, NameStr, InsertBefore, MDFrom: nullptr);
486 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *Sel, DEBUG_TYPE, F: &F);
487 return Sel;
488 }
489
490public:
491 /// Create and insert the idiom we use to indicate a block is unreachable
492 /// without having to rewrite the CFG from within InstCombine.
493 void CreateNonTerminatorUnreachable(Instruction *InsertAt) {
494 auto &Ctx = InsertAt->getContext();
495 auto *SI = new StoreInst(ConstantInt::getTrue(Context&: Ctx),
496 PoisonValue::get(T: PointerType::getUnqual(C&: Ctx)),
497 /*isVolatile*/ false, Align(1));
498 InsertNewInstWith(New: SI, Old: InsertAt->getIterator());
499 }
500
501 /// Combiner aware instruction erasure.
502 ///
503 /// When dealing with an instruction that has side effects or produces a void
504 /// value, we can't rely on DCE to delete the instruction. Instead, visit
505 /// methods should return the value returned by this function.
506 Instruction *eraseInstFromFunction(Instruction &I) override {
507 LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
508 assert(I.use_empty() && "Cannot erase instruction that is used!");
509 salvageDebugInfo(I);
510
511 // Make sure that we reprocess all operands now that we reduced their
512 // use counts.
513 SmallVector<Value *> Ops(I.operands());
514 Worklist.remove(I: &I);
515 DC.removeValue(V: &I);
516 I.eraseFromParent();
517 for (Value *Op : Ops)
518 Worklist.handleUseCountDecrement(V: Op);
519 MadeIRChange = true;
520 return nullptr; // Don't do anything with FI
521 }
522
523 OverflowResult computeOverflow(
524 Instruction::BinaryOps BinaryOp, bool IsSigned,
525 Value *LHS, Value *RHS, Instruction *CtxI) const;
526
527 /// Performs a few simplifications for operators which are associative
528 /// or commutative.
529 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
530
531 /// If InnerVal1 and OuterVal form a symmetric pair, and "op" is commutative:
532 /// "(InnerVal0 op InnerVal1) op OuterVal" ==> "(X op' Y) op InnerVal0".
533 /// "OuterVal op (InnerVal0 op InnerVal1)" ==> "InnerVal0 op (X op' Y)".
534 /// X and Y are the inputs to the symmetric pair. "op'" indicates that
535 /// InnerOp will have its poison-generating flags dropped.
536 bool tryReassociateAndFoldSymmetricPair(BinaryOperator &OuterOp,
537 BinaryOperator &InnerOp,
538 Value *InnerVal0, Value *InnerVal1,
539 Value *OuterVal);
540
541 /// Tries to simplify binary operations which some other binary
542 /// operation distributes over.
543 ///
544 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
545 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
546 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
547 /// value, or null if it didn't simplify.
548 Value *foldUsingDistributiveLaws(BinaryOperator &I);
549
550 /// Tries to simplify add operations using the definition of remainder.
551 ///
552 /// The definition of remainder is X % C = X - (X / C ) * C. The add
553 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
554 /// X % (C0 * C1)
555 Value *SimplifyAddWithRemainder(BinaryOperator &I);
556
557 // Binary Op helper for select operations where the expression can be
558 // efficiently reorganized.
559 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
560 Value *RHS);
561
562 // If `I` has operand `(ctpop (not x))`, fold `I` with `(sub nuw nsw
563 // BitWidth(x), (ctpop x))`.
564 Instruction *tryFoldInstWithCtpopWithNot(Instruction *I);
565
566 // (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
567 // -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
568 // (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
569 // -> (BinOp (logic_shift (BinOp X, Y)), Mask)
570 Instruction *foldBinOpShiftWithShift(BinaryOperator &I);
571
572 /// Tries to simplify binops of select and cast of the select condition.
573 ///
574 /// (Binop (cast C), (select C, T, F))
575 /// -> (select C, C0, C1)
576 Instruction *foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I);
577 /// Fold both forms of the div_ceil idiom:
578 /// (add (udiv X, Y), (zext (icmp ne (urem X, Y), 0)))
579 /// -> (udiv (add nuw X, Y-1), Y)
580 /// (add (zext (udiv X, Y)), (zext (icmp ne (urem X, Y), 0)))
581 /// -> (zext (udiv (add nuw X, Y-1), Y))
582 Instruction *foldDivCeil(BinaryOperator &I);
583
584 /// This tries to simplify binary operations by factorizing out common terms
585 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
586 Value *tryFactorizationFolds(BinaryOperator &I);
587
588 /// Match a select chain which produces one of three values based on whether
589 /// the LHS is less than, equal to, or greater than RHS respectively.
590 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
591 /// Equal and Greater values are saved in the matching process and returned to
592 /// the caller.
593 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
594 ConstantInt *&Less, ConstantInt *&Equal,
595 ConstantInt *&Greater);
596
597 /// Attempts to replace I with a simpler value based on the demanded
598 /// bits.
599 Value *SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask,
600 KnownBits &Known, const SimplifyQuery &Q,
601 unsigned Depth = 0);
602 using InstCombiner::SimplifyDemandedBits;
603 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
604 const APInt &DemandedMask, KnownBits &Known,
605 const SimplifyQuery &Q,
606 unsigned Depth = 0) override;
607
608 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
609 /// bits. It also tries to handle simplifications that can be done based on
610 /// DemandedMask, but without modifying the Instruction.
611 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
612 const APInt &DemandedMask,
613 KnownBits &Known,
614 const SimplifyQuery &Q,
615 unsigned Depth = 0);
616
617 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
618 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
619 Value *simplifyShrShlDemandedBits(
620 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
621 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
622
623 /// Tries to simplify operands to an integer instruction based on its
624 /// demanded bits.
625 bool SimplifyDemandedInstructionBits(Instruction &Inst);
626 bool SimplifyDemandedInstructionBits(Instruction &Inst, KnownBits &Known);
627
628 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
629 APInt &PoisonElts, unsigned Depth = 0,
630 bool AllowMultipleUsers = false) override;
631
632 /// Attempts to replace V with a simpler value based on the demanded
633 /// floating-point classes
634 Value *SimplifyDemandedUseFPClass(Instruction *I, FPClassTest DemandedMask,
635 KnownFPClass &Known, const SimplifyQuery &Q,
636 unsigned Depth = 0);
637 Value *SimplifyMultipleUseDemandedFPClass(Instruction *I,
638 FPClassTest DemandedMask,
639 KnownFPClass &Known,
640 const SimplifyQuery &Q,
641 unsigned Depth);
642
643 bool SimplifyDemandedFPClass(Instruction *I, unsigned Op,
644 FPClassTest DemandedMask, KnownFPClass &Known,
645 const SimplifyQuery &Q, unsigned Depth = 0);
646
647 bool SimplifyDemandedInstructionFPClass(Instruction &Inst);
648
649 /// Common transforms for add / disjoint or
650 Instruction *foldAddLikeCommutative(Value *LHS, Value *RHS, bool NSW,
651 bool NUW);
652
653 /// Canonicalize the position of binops relative to shufflevector.
654 Instruction *foldVectorBinop(BinaryOperator &Inst);
655 Instruction *foldVectorSelect(SelectInst &Sel);
656 Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf);
657 Constant *unshuffleConstant(ArrayRef<int> ShMask, Constant *C,
658 VectorType *NewCTy);
659
660 /// Given a binary operator, cast instruction, or select which has a PHI node
661 /// as operand #0, see if we can fold the instruction into the PHI (which is
662 /// only possible if all operands to the PHI are constants).
663 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN,
664 bool AllowMultipleUses = false);
665
666 /// Try to fold binary operators whose operands are simple interleaved
667 /// recurrences to a single recurrence. This is a common pattern in reduction
668 /// operations.
669 /// Example:
670 /// %phi1 = phi [init1, %BB1], [%op1, %BB2]
671 /// %phi2 = phi [init2, %BB1], [%op2, %BB2]
672 /// %op1 = binop %phi1, constant1
673 /// %op2 = binop %phi2, constant2
674 /// %rdx = binop %op1, %op2
675 /// -->
676 /// %phi_combined = phi [init_combined, %BB1], [%op_combined, %BB2]
677 /// %rdx_combined = binop %phi_combined, constant_combined
678 Instruction *foldBinopWithRecurrence(BinaryOperator &BO);
679
680 /// For a binary operator with 2 phi operands, try to hoist the binary
681 /// operation before the phi. This can result in fewer instructions in
682 /// patterns where at least one set of phi operands simplifies.
683 /// Example:
684 /// BB3: binop (phi [X, BB1], [C1, BB2]), (phi [Y, BB1], [C2, BB2])
685 /// -->
686 /// BB1: BO = binop X, Y
687 /// BB3: phi [BO, BB1], [(binop C1, C2), BB2]
688 Instruction *foldBinopWithPhiOperands(BinaryOperator &BO);
689
690 /// Given an instruction with a select as one operand and a constant as the
691 /// other operand, try to fold the binary operator into the select arguments.
692 /// This also works for Cast instructions, which obviously do not have a
693 /// second operand.
694 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
695 bool FoldWithMultiUse = false,
696 bool SimplifyBothArms = false);
697
698 Instruction *foldBinOpSelectBinOp(BinaryOperator &Op);
699
700 /// This is a convenience wrapper function for the above two functions.
701 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
702
703 Instruction *foldAddWithConstant(BinaryOperator &Add);
704
705 Instruction *foldSquareSumInt(BinaryOperator &I);
706 Instruction *foldSquareSumFP(BinaryOperator &I);
707
708 /// Try to rotate an operation below a PHI node, using PHI nodes for
709 /// its operands.
710 Instruction *foldPHIArgOpIntoPHI(PHINode &PN);
711 Instruction *foldPHIArgBinOpIntoPHI(PHINode &PN);
712 Instruction *foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN);
713 Instruction *foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN);
714 Instruction *foldPHIArgGEPIntoPHI(PHINode &PN);
715 Instruction *foldPHIArgLoadIntoPHI(PHINode &PN);
716 Instruction *foldPHIArgZextsIntoPHI(PHINode &PN);
717 Instruction *foldPHIArgIntToPtrToPHI(PHINode &PN);
718
719 /// If the phi is within a phi web, which is formed by the def-use chain
720 /// of phis and all the phis in the web are only used in the other phis.
721 /// In this case, these phis are dead and we will remove all of them.
722 bool foldDeadPhiWeb(PHINode &PN);
723
724 /// If an integer typed PHI has only one use which is an IntToPtr operation,
725 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
726 /// insert a new pointer typed PHI and replace the original one.
727 bool foldIntegerTypedPHI(PHINode &PN);
728
729 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
730 /// folded operation.
731 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
732
733 Value *foldPtrToIntOrAddrOfGEP(Type *IntTy, Value *Ptr);
734 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond,
735 Instruction &I);
736 Instruction *foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS,
737 const ICmpInst &I);
738 bool foldAllocaCmp(AllocaInst *Alloca);
739 Instruction *foldCmpLoadFromIndexedGlobal(LoadInst *LI,
740 GetElementPtrInst *GEP,
741 CmpInst &ICI,
742 ConstantInt *AndCst = nullptr);
743 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
744 Constant *RHSC);
745 Instruction *foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred);
746 Instruction *foldCmpSelectOfConstants(CmpInst &I);
747 Instruction *foldICmpWithCastOp(ICmpInst &ICmp);
748 Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp);
749
750 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
751 Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
752 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
753 Instruction *foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp);
754 Instruction *foldICmpUsingBoolRange(ICmpInst &I);
755 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
756 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
757 Instruction *foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
758 const APInt &C);
759 Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
760 Instruction *foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax,
761 Value *Z, CmpPredicate Pred);
762 Instruction *foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min);
763 Instruction *foldICmpEquality(ICmpInst &Cmp);
764 Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
765 Instruction *foldSignBitTest(ICmpInst &I);
766 Instruction *foldICmpWithZero(ICmpInst &Cmp);
767
768 Value *foldMultiplicationOverflowCheck(ICmpInst &Cmp);
769
770 Instruction *foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO,
771 const APInt &C);
772 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
773 ConstantInt *C);
774 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
775 const APInt &C);
776 Instruction *foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
777 const SimplifyQuery &Q);
778 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
779 const APInt &C);
780 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
781 const APInt &C);
782 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
783 const APInt &C);
784 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
785 const APInt &C);
786 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
787 const APInt &C);
788 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
789 const APInt &C);
790 Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
791 const APInt &C);
792 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
793 const APInt &C);
794 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
795 const APInt &C);
796 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
797 const APInt &C);
798 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
799 const APInt &C);
800 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
801 const APInt &C1);
802 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
803 const APInt &C1, const APInt &C2);
804 Instruction *foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor,
805 const APInt &C);
806 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
807 const APInt &C2);
808 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
809 const APInt &C2);
810
811 Instruction *foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp,
812 BinaryOperator *BO,
813 const APInt &C);
814 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
815 BinaryOperator *BO,
816 const APInt &C);
817 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
818 const APInt &C);
819 Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
820 const APInt &C);
821 Instruction *foldICmpBitCast(ICmpInst &Cmp);
822 Instruction *foldICmpWithTrunc(ICmpInst &Cmp);
823 Instruction *foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1,
824 ICmpInst &CtxI);
825
826 // Helpers of visitSelectInst().
827 Instruction *foldSelectOfBools(SelectInst &SI);
828 Instruction *foldSelectToCmp(SelectInst &SI);
829 Instruction *foldSelectExtConst(SelectInst &Sel);
830 Instruction *foldSelectEqualityTest(SelectInst &SI);
831 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
832 Instruction *foldSelectIntrinsic(SelectInst &SI);
833 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
834 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
835 Value *A, Value *B, Instruction &Outer,
836 SelectPatternFlavor SPF2, Value *C);
837 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
838 Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
839 Value *FalseVal);
840 Instruction *foldSelectValueEquivalence(SelectInst &SI, CmpInst &CI);
841
842 Instruction *foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt);
843
844 bool replaceInInstruction(Value *V, Value *Old, Value *New,
845 unsigned Depth = 0);
846
847 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
848 bool isSigned, bool Inside);
849 bool mergeStoreIntoSuccessor(StoreInst &SI);
850
851 /// Given an initial instruction, check to see if it is the root of a
852 /// bswap/bitreverse idiom. If so, return the equivalent bswap/bitreverse
853 /// intrinsic.
854 Instruction *matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps,
855 bool MatchBitReversals);
856
857 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
858 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
859
860 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
861
862 bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock);
863 void tryToSinkInstructionDbgVariableRecords(
864 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
865 BasicBlock *DestBlock, SmallVectorImpl<DbgVariableRecord *> &DPUsers);
866
867 bool removeInstructionsBeforeUnreachable(Instruction &I);
868 void addDeadEdge(BasicBlock *From, BasicBlock *To,
869 SmallVectorImpl<BasicBlock *> &Worklist);
870 void handleUnreachableFrom(Instruction *I,
871 SmallVectorImpl<BasicBlock *> &Worklist);
872 void handlePotentiallyDeadBlocks(SmallVectorImpl<BasicBlock *> &Worklist);
873 void handlePotentiallyDeadSuccessors(BasicBlock *BB, BasicBlock *LiveSucc);
874 void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser = nullptr);
875
876 /// Take the exact integer log2 of the value. If DoFold is true, create the
877 /// actual instructions, otherwise return a non-null dummy value. Return
878 /// nullptr on failure. Note, if DoFold is true the caller must ensure that
879 /// takeLog2 will succeed, otherwise it may create stray instructions.
880 Value *takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold);
881
882 Value *tryGetLog2(Value *Op, bool AssumeNonZero) {
883 if (takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: false))
884 return takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: true);
885 return nullptr;
886 }
887};
888
889class Negator final {
890 /// Top-to-bottom, def-to-use negated instruction tree we produced.
891 SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
892
893 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
894 BuilderTy Builder;
895
896 const DominatorTree &DT;
897
898 const bool IsTrulyNegation;
899
900 const unsigned MaxDepth;
901
902 SmallDenseMap<Value *, Value *> NegationsCache;
903
904 Negator(Module &M, const DominatorTree &DT, bool IsTrulyNegation,
905 unsigned MaxDepth);
906
907#if LLVM_ENABLE_STATS
908 unsigned NumValuesVisitedInThisNegator = 0;
909 ~Negator();
910#endif
911
912 using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
913 Value * /*NegatedRoot*/>;
914
915 std::array<Value *, 2> getSortedOperandsOfBinOp(Instruction *I);
916
917 [[nodiscard]] Value *visitImpl(Value *V, bool IsNSW, unsigned Depth);
918
919 [[nodiscard]] Value *negate(Value *V, bool IsNSW, unsigned Depth);
920
921 /// Recurse depth-first and attempt to sink the negation.
922 /// FIXME: use worklist?
923 [[nodiscard]] std::optional<Result> run(Value *Root, bool IsNSW);
924
925 Negator(const Negator &) = delete;
926 Negator(Negator &&) = delete;
927 Negator &operator=(const Negator &) = delete;
928 Negator &operator=(Negator &&) = delete;
929
930public:
931 /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
932 /// otherwise returns negated value.
933 [[nodiscard]] static Value *Negate(bool LHSIsZero, bool IsNSW, Value *Root,
934 InstCombinerImpl &IC);
935};
936
937struct CommonPointerBase {
938 /// Common base pointer.
939 Value *Ptr = nullptr;
940 /// LHS GEPs until common base.
941 SmallVector<GEPOperator *> LHSGEPs;
942 /// RHS GEPs until common base.
943 SmallVector<GEPOperator *> RHSGEPs;
944 /// LHS GEP NoWrapFlags until common base.
945 GEPNoWrapFlags LHSNW = GEPNoWrapFlags::all();
946 /// RHS GEP NoWrapFlags until common base.
947 GEPNoWrapFlags RHSNW = GEPNoWrapFlags::all();
948
949 static CommonPointerBase compute(Value *LHS, Value *RHS);
950
951 /// Whether expanding the GEP chains is expensive.
952 bool isExpensive() const;
953};
954
955} // end namespace llvm
956
957#undef DEBUG_TYPE
958
959#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
960