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 /// Tries to simplify binary operations which some other binary
532 /// operation distributes over.
533 ///
534 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
535 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
536 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
537 /// value, or null if it didn't simplify.
538 Value *foldUsingDistributiveLaws(BinaryOperator &I);
539
540 /// Tries to simplify add operations using the definition of remainder.
541 ///
542 /// The definition of remainder is X % C = X - (X / C ) * C. The add
543 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
544 /// X % (C0 * C1)
545 Value *SimplifyAddWithRemainder(BinaryOperator &I);
546
547 // Binary Op helper for select operations where the expression can be
548 // efficiently reorganized.
549 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
550 Value *RHS);
551
552 // If `I` has operand `(ctpop (not x))`, fold `I` with `(sub nuw nsw
553 // BitWidth(x), (ctpop x))`.
554 Instruction *tryFoldInstWithCtpopWithNot(Instruction *I);
555
556 // (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
557 // -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
558 // (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
559 // -> (BinOp (logic_shift (BinOp X, Y)), Mask)
560 Instruction *foldBinOpShiftWithShift(BinaryOperator &I);
561
562 /// Tries to simplify binops of select and cast of the select condition.
563 ///
564 /// (Binop (cast C), (select C, T, F))
565 /// -> (select C, C0, C1)
566 Instruction *foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I);
567 /// Fold both forms of the div_ceil idiom:
568 /// (add (udiv X, Y), (zext (icmp ne (urem X, Y), 0)))
569 /// -> (udiv (add nuw X, Y-1), Y)
570 /// (add (zext (udiv X, Y)), (zext (icmp ne (urem X, Y), 0)))
571 /// -> (zext (udiv (add nuw X, Y-1), Y))
572 Instruction *foldDivCeil(BinaryOperator &I);
573
574 /// This tries to simplify binary operations by factorizing out common terms
575 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
576 Value *tryFactorizationFolds(BinaryOperator &I);
577
578 /// Match a select chain which produces one of three values based on whether
579 /// the LHS is less than, equal to, or greater than RHS respectively.
580 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
581 /// Equal and Greater values are saved in the matching process and returned to
582 /// the caller.
583 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
584 ConstantInt *&Less, ConstantInt *&Equal,
585 ConstantInt *&Greater);
586
587 /// Attempts to replace I with a simpler value based on the demanded
588 /// bits.
589 Value *SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask,
590 KnownBits &Known, const SimplifyQuery &Q,
591 unsigned Depth = 0);
592 using InstCombiner::SimplifyDemandedBits;
593 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
594 const APInt &DemandedMask, KnownBits &Known,
595 const SimplifyQuery &Q,
596 unsigned Depth = 0) override;
597
598 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
599 /// bits. It also tries to handle simplifications that can be done based on
600 /// DemandedMask, but without modifying the Instruction.
601 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
602 const APInt &DemandedMask,
603 KnownBits &Known,
604 const SimplifyQuery &Q,
605 unsigned Depth = 0);
606
607 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
608 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
609 Value *simplifyShrShlDemandedBits(
610 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
611 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
612
613 /// Tries to simplify operands to an integer instruction based on its
614 /// demanded bits.
615 bool SimplifyDemandedInstructionBits(Instruction &Inst);
616 bool SimplifyDemandedInstructionBits(Instruction &Inst, KnownBits &Known);
617
618 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
619 APInt &PoisonElts, unsigned Depth = 0,
620 bool AllowMultipleUsers = false) override;
621
622 /// Attempts to replace V with a simpler value based on the demanded
623 /// floating-point classes
624 Value *SimplifyDemandedUseFPClass(Instruction *I, FPClassTest DemandedMask,
625 KnownFPClass &Known, const SimplifyQuery &Q,
626 unsigned Depth = 0);
627 Value *SimplifyMultipleUseDemandedFPClass(Instruction *I,
628 FPClassTest DemandedMask,
629 KnownFPClass &Known,
630 const SimplifyQuery &Q,
631 unsigned Depth);
632
633 bool SimplifyDemandedFPClass(Instruction *I, unsigned Op,
634 FPClassTest DemandedMask, KnownFPClass &Known,
635 const SimplifyQuery &Q, unsigned Depth = 0);
636
637 bool SimplifyDemandedInstructionFPClass(Instruction &Inst);
638
639 /// Common transforms for add / disjoint or
640 Instruction *foldAddLikeCommutative(Value *LHS, Value *RHS, bool NSW,
641 bool NUW);
642
643 /// Canonicalize the position of binops relative to shufflevector.
644 Instruction *foldVectorBinop(BinaryOperator &Inst);
645 Instruction *foldVectorSelect(SelectInst &Sel);
646 Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf);
647 Constant *unshuffleConstant(ArrayRef<int> ShMask, Constant *C,
648 VectorType *NewCTy);
649
650 /// Given a binary operator, cast instruction, or select which has a PHI node
651 /// as operand #0, see if we can fold the instruction into the PHI (which is
652 /// only possible if all operands to the PHI are constants).
653 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN,
654 bool AllowMultipleUses = false);
655
656 /// Try to fold binary operators whose operands are simple interleaved
657 /// recurrences to a single recurrence. This is a common pattern in reduction
658 /// operations.
659 /// Example:
660 /// %phi1 = phi [init1, %BB1], [%op1, %BB2]
661 /// %phi2 = phi [init2, %BB1], [%op2, %BB2]
662 /// %op1 = binop %phi1, constant1
663 /// %op2 = binop %phi2, constant2
664 /// %rdx = binop %op1, %op2
665 /// -->
666 /// %phi_combined = phi [init_combined, %BB1], [%op_combined, %BB2]
667 /// %rdx_combined = binop %phi_combined, constant_combined
668 Instruction *foldBinopWithRecurrence(BinaryOperator &BO);
669
670 /// For a binary operator with 2 phi operands, try to hoist the binary
671 /// operation before the phi. This can result in fewer instructions in
672 /// patterns where at least one set of phi operands simplifies.
673 /// Example:
674 /// BB3: binop (phi [X, BB1], [C1, BB2]), (phi [Y, BB1], [C2, BB2])
675 /// -->
676 /// BB1: BO = binop X, Y
677 /// BB3: phi [BO, BB1], [(binop C1, C2), BB2]
678 Instruction *foldBinopWithPhiOperands(BinaryOperator &BO);
679
680 /// Given an instruction with a select as one operand and a constant as the
681 /// other operand, try to fold the binary operator into the select arguments.
682 /// This also works for Cast instructions, which obviously do not have a
683 /// second operand.
684 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
685 bool FoldWithMultiUse = false,
686 bool SimplifyBothArms = false);
687
688 Instruction *foldBinOpSelectBinOp(BinaryOperator &Op);
689
690 /// This is a convenience wrapper function for the above two functions.
691 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
692
693 Instruction *foldAddWithConstant(BinaryOperator &Add);
694
695 Instruction *foldSquareSumInt(BinaryOperator &I);
696 Instruction *foldSquareSumFP(BinaryOperator &I);
697
698 /// Try to rotate an operation below a PHI node, using PHI nodes for
699 /// its operands.
700 Instruction *foldPHIArgOpIntoPHI(PHINode &PN);
701 Instruction *foldPHIArgBinOpIntoPHI(PHINode &PN);
702 Instruction *foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN);
703 Instruction *foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN);
704 Instruction *foldPHIArgGEPIntoPHI(PHINode &PN);
705 Instruction *foldPHIArgLoadIntoPHI(PHINode &PN);
706 Instruction *foldPHIArgZextsIntoPHI(PHINode &PN);
707 Instruction *foldPHIArgIntToPtrToPHI(PHINode &PN);
708
709 /// If the phi is within a phi web, which is formed by the def-use chain
710 /// of phis and all the phis in the web are only used in the other phis.
711 /// In this case, these phis are dead and we will remove all of them.
712 bool foldDeadPhiWeb(PHINode &PN);
713
714 /// If an integer typed PHI has only one use which is an IntToPtr operation,
715 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
716 /// insert a new pointer typed PHI and replace the original one.
717 bool foldIntegerTypedPHI(PHINode &PN);
718
719 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
720 /// folded operation.
721 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
722
723 Value *foldPtrToIntOrAddrOfGEP(Type *IntTy, Value *Ptr);
724 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond,
725 Instruction &I);
726 Instruction *foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS,
727 const ICmpInst &I);
728 bool foldAllocaCmp(AllocaInst *Alloca);
729 Instruction *foldCmpLoadFromIndexedGlobal(LoadInst *LI,
730 GetElementPtrInst *GEP,
731 CmpInst &ICI,
732 ConstantInt *AndCst = nullptr);
733 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
734 Constant *RHSC);
735 Instruction *foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred);
736 Instruction *foldCmpSelectOfConstants(CmpInst &I);
737 Instruction *foldICmpWithCastOp(ICmpInst &ICmp);
738 Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp);
739
740 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
741 Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
742 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
743 Instruction *foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp);
744 Instruction *foldICmpUsingBoolRange(ICmpInst &I);
745 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
746 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
747 Instruction *foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
748 const APInt &C);
749 Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
750 Instruction *foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax,
751 Value *Z, CmpPredicate Pred);
752 Instruction *foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min);
753 Instruction *foldICmpEquality(ICmpInst &Cmp);
754 Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
755 Instruction *foldSignBitTest(ICmpInst &I);
756 Instruction *foldICmpWithZero(ICmpInst &Cmp);
757
758 Value *foldMultiplicationOverflowCheck(ICmpInst &Cmp);
759
760 Instruction *foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO,
761 const APInt &C);
762 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
763 ConstantInt *C);
764 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
765 const APInt &C);
766 Instruction *foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
767 const SimplifyQuery &Q);
768 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
769 const APInt &C);
770 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
771 const APInt &C);
772 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
773 const APInt &C);
774 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
775 const APInt &C);
776 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
777 const APInt &C);
778 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
779 const APInt &C);
780 Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
781 const APInt &C);
782 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
783 const APInt &C);
784 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
785 const APInt &C);
786 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
787 const APInt &C);
788 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
789 const APInt &C);
790 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
791 const APInt &C1);
792 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
793 const APInt &C1, const APInt &C2);
794 Instruction *foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor,
795 const APInt &C);
796 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
797 const APInt &C2);
798 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
799 const APInt &C2);
800
801 Instruction *foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp,
802 BinaryOperator *BO,
803 const APInt &C);
804 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
805 BinaryOperator *BO,
806 const APInt &C);
807 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
808 const APInt &C);
809 Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
810 const APInt &C);
811 Instruction *foldICmpBitCast(ICmpInst &Cmp);
812 Instruction *foldICmpWithTrunc(ICmpInst &Cmp);
813 Instruction *foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1,
814 ICmpInst &CtxI);
815
816 // Helpers of visitSelectInst().
817 Instruction *foldSelectOfBools(SelectInst &SI);
818 Instruction *foldSelectToCmp(SelectInst &SI);
819 Instruction *foldSelectExtConst(SelectInst &Sel);
820 Instruction *foldSelectEqualityTest(SelectInst &SI);
821 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
822 Instruction *foldSelectIntrinsic(SelectInst &SI);
823 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
824 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
825 Value *A, Value *B, Instruction &Outer,
826 SelectPatternFlavor SPF2, Value *C);
827 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
828 Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
829 Value *FalseVal);
830 Instruction *foldSelectValueEquivalence(SelectInst &SI, CmpInst &CI);
831
832 Instruction *foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt);
833
834 bool replaceInInstruction(Value *V, Value *Old, Value *New,
835 unsigned Depth = 0);
836
837 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
838 bool isSigned, bool Inside);
839 bool mergeStoreIntoSuccessor(StoreInst &SI);
840
841 /// Given an initial instruction, check to see if it is the root of a
842 /// bswap/bitreverse idiom. If so, return the equivalent bswap/bitreverse
843 /// intrinsic.
844 Instruction *matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps,
845 bool MatchBitReversals);
846
847 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
848 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
849
850 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
851
852 bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock);
853 void tryToSinkInstructionDbgVariableRecords(
854 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
855 BasicBlock *DestBlock, SmallVectorImpl<DbgVariableRecord *> &DPUsers);
856
857 bool removeInstructionsBeforeUnreachable(Instruction &I);
858 void addDeadEdge(BasicBlock *From, BasicBlock *To,
859 SmallVectorImpl<BasicBlock *> &Worklist);
860 void handleUnreachableFrom(Instruction *I,
861 SmallVectorImpl<BasicBlock *> &Worklist);
862 void handlePotentiallyDeadBlocks(SmallVectorImpl<BasicBlock *> &Worklist);
863 void handlePotentiallyDeadSuccessors(BasicBlock *BB, BasicBlock *LiveSucc);
864 void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser = nullptr);
865
866 /// Take the exact integer log2 of the value. If DoFold is true, create the
867 /// actual instructions, otherwise return a non-null dummy value. Return
868 /// nullptr on failure. Note, if DoFold is true the caller must ensure that
869 /// takeLog2 will succeed, otherwise it may create stray instructions.
870 Value *takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold);
871
872 Value *tryGetLog2(Value *Op, bool AssumeNonZero) {
873 if (takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: false))
874 return takeLog2(Op, /*Depth=*/Depth: 0, AssumeNonZero, /*DoFold=*/DoFold: true);
875 return nullptr;
876 }
877};
878
879class Negator final {
880 /// Top-to-bottom, def-to-use negated instruction tree we produced.
881 SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
882
883 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
884 BuilderTy Builder;
885
886 const DominatorTree &DT;
887
888 const bool IsTrulyNegation;
889
890 const unsigned MaxDepth;
891
892 SmallDenseMap<Value *, Value *> NegationsCache;
893
894 Negator(Module &M, const DominatorTree &DT, bool IsTrulyNegation,
895 unsigned MaxDepth);
896
897#if LLVM_ENABLE_STATS
898 unsigned NumValuesVisitedInThisNegator = 0;
899 ~Negator();
900#endif
901
902 using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
903 Value * /*NegatedRoot*/>;
904
905 std::array<Value *, 2> getSortedOperandsOfBinOp(Instruction *I);
906
907 [[nodiscard]] Value *visitImpl(Value *V, bool IsNSW, unsigned Depth);
908
909 [[nodiscard]] Value *negate(Value *V, bool IsNSW, unsigned Depth);
910
911 /// Recurse depth-first and attempt to sink the negation.
912 /// FIXME: use worklist?
913 [[nodiscard]] std::optional<Result> run(Value *Root, bool IsNSW);
914
915 Negator(const Negator &) = delete;
916 Negator(Negator &&) = delete;
917 Negator &operator=(const Negator &) = delete;
918 Negator &operator=(Negator &&) = delete;
919
920public:
921 /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
922 /// otherwise returns negated value.
923 [[nodiscard]] static Value *Negate(bool LHSIsZero, bool IsNSW, Value *Root,
924 InstCombinerImpl &IC);
925};
926
927struct CommonPointerBase {
928 /// Common base pointer.
929 Value *Ptr = nullptr;
930 /// LHS GEPs until common base.
931 SmallVector<GEPOperator *> LHSGEPs;
932 /// RHS GEPs until common base.
933 SmallVector<GEPOperator *> RHSGEPs;
934 /// LHS GEP NoWrapFlags until common base.
935 GEPNoWrapFlags LHSNW = GEPNoWrapFlags::all();
936 /// RHS GEP NoWrapFlags until common base.
937 GEPNoWrapFlags RHSNW = GEPNoWrapFlags::all();
938
939 static CommonPointerBase compute(Value *LHS, Value *RHS);
940
941 /// Whether expanding the GEP chains is expensive.
942 bool isExpensive() const;
943};
944
945} // end namespace llvm
946
947#undef DEBUG_TYPE
948
949#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
950