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