1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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// InstructionCombining - Combine instructions to form fewer, simple
10// instructions. This pass does not modify the CFG. This pass is where
11// algebraic simplification happens.
12//
13// This pass combines things like:
14// %Y = add i32 %X, 1
15// %Z = add i32 %Y, 1
16// into:
17// %Z = add i32 %X, 2
18//
19// This is a simple worklist driven algorithm.
20//
21// This pass guarantees that the following canonicalizations are performed on
22// the program:
23// 1. If a binary operator has a constant operand, it is moved to the RHS
24// 2. Bitwise operators with constant operands are always grouped so that
25// shifts are performed first, then or's, then and's, then xor's.
26// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27// 4. All cmp instructions on boolean values are replaced with logical ops
28// 5. add X, X is represented as (X*2) => (X << 1)
29// 6. Multiplies with a power-of-two constant argument are transformed into
30// shifts.
31// ... etc.
32//
33//===----------------------------------------------------------------------===//
34
35#include "InstCombineInternal.h"
36#include "llvm/ADT/APFloat.h"
37#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/DenseMap.h"
40#include "llvm/ADT/SetOperations.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/Analysis/AliasAnalysis.h"
45#include "llvm/Analysis/AssumptionCache.h"
46#include "llvm/Analysis/BasicAliasAnalysis.h"
47#include "llvm/Analysis/BlockFrequencyInfo.h"
48#include "llvm/Analysis/CFG.h"
49#include "llvm/Analysis/ConstantFolding.h"
50#include "llvm/Analysis/GlobalsModRef.h"
51#include "llvm/Analysis/InstructionSimplify.h"
52#include "llvm/Analysis/LastRunTrackingAnalysis.h"
53#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
54#include "llvm/Analysis/MemoryBuiltins.h"
55#include "llvm/Analysis/OptimizationRemarkEmitter.h"
56#include "llvm/Analysis/ProfileSummaryInfo.h"
57#include "llvm/Analysis/TargetFolder.h"
58#include "llvm/Analysis/TargetLibraryInfo.h"
59#include "llvm/Analysis/TargetTransformInfo.h"
60#include "llvm/Analysis/Utils/Local.h"
61#include "llvm/Analysis/ValueTracking.h"
62#include "llvm/Analysis/VectorUtils.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/CFG.h"
65#include "llvm/IR/Constant.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DIBuilder.h"
68#include "llvm/IR/DataLayout.h"
69#include "llvm/IR/DebugInfo.h"
70#include "llvm/IR/DerivedTypes.h"
71#include "llvm/IR/Dominators.h"
72#include "llvm/IR/EHPersonalities.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GetElementPtrTypeIterator.h"
75#include "llvm/IR/IRBuilder.h"
76#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
79#include "llvm/IR/IntrinsicInst.h"
80#include "llvm/IR/Intrinsics.h"
81#include "llvm/IR/LLVMContext.h"
82#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Operator.h"
84#include "llvm/IR/PassManager.h"
85#include "llvm/IR/PatternMatch.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/Use.h"
88#include "llvm/IR/User.h"
89#include "llvm/IR/Value.h"
90#include "llvm/IR/ValueHandle.h"
91#include "llvm/InitializePasses.h"
92#include "llvm/Support/Casting.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Debug.h"
95#include "llvm/Support/DebugCounter.h"
96#include "llvm/Support/ErrorHandling.h"
97#include "llvm/Support/KnownBits.h"
98#include "llvm/Support/KnownFPClass.h"
99#include "llvm/Support/raw_ostream.h"
100#include "llvm/Transforms/InstCombine/InstCombine.h"
101#include "llvm/Transforms/Utils/BasicBlockUtils.h"
102#include "llvm/Transforms/Utils/Local.h"
103#include <algorithm>
104#include <cassert>
105#include <cstdint>
106#include <memory>
107#include <optional>
108#include <string>
109#include <utility>
110
111#define DEBUG_TYPE "instcombine"
112#include "llvm/Transforms/Utils/InstructionWorklist.h"
113#include <optional>
114
115using namespace llvm;
116using namespace llvm::PatternMatch;
117
118STATISTIC(NumWorklistIterations,
119 "Number of instruction combining iterations performed");
120STATISTIC(NumOneIteration, "Number of functions with one iteration");
121STATISTIC(NumTwoIterations, "Number of functions with two iterations");
122STATISTIC(NumThreeIterations, "Number of functions with three iterations");
123STATISTIC(NumFourOrMoreIterations,
124 "Number of functions with four or more iterations");
125
126STATISTIC(NumCombined , "Number of insts combined");
127STATISTIC(NumConstProp, "Number of constant folds");
128STATISTIC(NumDeadInst , "Number of dead inst eliminated");
129STATISTIC(NumSunkInst , "Number of instructions sunk");
130STATISTIC(NumExpand, "Number of expansions");
131STATISTIC(NumFactor , "Number of factorizations");
132STATISTIC(NumReassoc , "Number of reassociations");
133DEBUG_COUNTER(VisitCounter, "instcombine-visit",
134 "Controls which instructions are visited");
135
136void InstCombiner::IRBuilderInstCombineInserter::InsertHelper(
137 Instruction *I, const Twine &Name, BasicBlock::iterator InsertPt) const {
138 IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
139 IC.Worklist.add(I);
140 if (auto *Assume = dyn_cast<AssumeInst>(Val: I))
141 IC.AC.registerAssumption(CI: Assume);
142 if (IC.AnnotationMetadataSource)
143 I->copyMetadata(SrcInst: *IC.AnnotationMetadataSource, WL: LLVMContext::MD_annotation);
144}
145
146std::optional<Instruction *>
147InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) {
148 // Handle target specific intrinsics
149 if (II.getCalledFunction()->isTargetIntrinsic()) {
150 return TTIForTargetIntrinsicsOnly.instCombineIntrinsic(IC&: *this, II);
151 }
152 return std::nullopt;
153}
154
155std::optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic(
156 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
157 bool &KnownBitsComputed) {
158 // Handle target specific intrinsics
159 if (II.getCalledFunction()->isTargetIntrinsic()) {
160 return TTIForTargetIntrinsicsOnly.simplifyDemandedUseBitsIntrinsic(
161 IC&: *this, II, DemandedMask, Known, KnownBitsComputed);
162 }
163 return std::nullopt;
164}
165
166std::optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic(
167 IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts,
168 APInt &PoisonElts2, APInt &PoisonElts3,
169 std::function<void(Instruction *, unsigned, APInt, APInt &)>
170 SimplifyAndSetOp) {
171 // Handle target specific intrinsics
172 if (II.getCalledFunction()->isTargetIntrinsic()) {
173 return TTIForTargetIntrinsicsOnly.simplifyDemandedVectorEltsIntrinsic(
174 IC&: *this, II, DemandedElts, UndefElts&: PoisonElts, UndefElts2&: PoisonElts2, UndefElts3&: PoisonElts3,
175 SimplifyAndSetOp);
176 }
177 return std::nullopt;
178}
179
180bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
181 // Approved exception for TTI use: This queries a legality property of the
182 // target, not an profitability heuristic. Ideally this should be part of
183 // DataLayout instead.
184 return TTIForTargetIntrinsicsOnly.isValidAddrSpaceCast(FromAS, ToAS);
185}
186
187Value *InstCombinerImpl::EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP) {
188 if (!RewriteGEP)
189 return llvm::emitGEPOffset(Builder: &Builder, DL, GEP);
190
191 IRBuilderBase::InsertPointGuard Guard(Builder);
192 auto *Inst = dyn_cast<Instruction>(Val: GEP);
193 if (Inst)
194 Builder.SetInsertPoint(Inst);
195
196 Value *Offset = EmitGEPOffset(GEP);
197 // Rewrite non-trivial GEPs to avoid duplicating the offset arithmetic.
198 if (Inst && !GEP->hasAllConstantIndices() &&
199 !GEP->getSourceElementType()->isIntegerTy(BitWidth: 8)) {
200 replaceInstUsesWith(
201 I&: *Inst, V: Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: GEP->getPointerOperand(),
202 IdxList: Offset, Name: "", NW: GEP->getNoWrapFlags()));
203 eraseInstFromFunction(I&: *Inst);
204 }
205 return Offset;
206}
207
208Value *InstCombinerImpl::EmitGEPOffsets(ArrayRef<GEPOperator *> GEPs,
209 GEPNoWrapFlags NW, Type *IdxTy,
210 bool RewriteGEPs) {
211 auto Add = [&](Value *Sum, Value *Offset) -> Value * {
212 if (Sum)
213 return Builder.CreateAdd(LHS: Sum, RHS: Offset, Name: "", HasNUW: NW.hasNoUnsignedWrap(),
214 HasNSW: NW.isInBounds());
215 else
216 return Offset;
217 };
218
219 Value *Sum = nullptr;
220 Value *OneUseSum = nullptr;
221 Value *OneUseBase = nullptr;
222 GEPNoWrapFlags OneUseFlags = GEPNoWrapFlags::all();
223 for (GEPOperator *GEP : reverse(C&: GEPs)) {
224 Value *Offset;
225 {
226 // Expand the offset at the point of the previous GEP to enable rewriting.
227 // However, use the original insertion point for calculating Sum.
228 IRBuilderBase::InsertPointGuard Guard(Builder);
229 auto *Inst = dyn_cast<Instruction>(Val: GEP);
230 if (RewriteGEPs && Inst)
231 Builder.SetInsertPoint(Inst);
232
233 Offset = llvm::emitGEPOffset(Builder: &Builder, DL, GEP);
234 if (Offset->getType() != IdxTy)
235 Offset = Builder.CreateVectorSplat(
236 EC: cast<VectorType>(Val: IdxTy)->getElementCount(), V: Offset);
237 if (GEP->hasOneUse()) {
238 // Offsets of one-use GEPs will be merged into the next multi-use GEP.
239 OneUseSum = Add(OneUseSum, Offset);
240 OneUseFlags = OneUseFlags.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
241 if (!OneUseBase)
242 OneUseBase = GEP->getPointerOperand();
243 continue;
244 }
245
246 if (OneUseSum)
247 Offset = Add(OneUseSum, Offset);
248
249 // Rewrite the GEP to reuse the computed offset. This also includes
250 // offsets from preceding one-use GEPs of matched type.
251 if (RewriteGEPs && Inst &&
252 Offset->getType()->isVectorTy() == GEP->getType()->isVectorTy() &&
253 !(GEP->getSourceElementType()->isIntegerTy(BitWidth: 8) &&
254 GEP->getOperand(i_nocapture: 1) == Offset)) {
255 replaceInstUsesWith(
256 I&: *Inst,
257 V: Builder.CreatePtrAdd(
258 Ptr: OneUseBase ? OneUseBase : GEP->getPointerOperand(), Offset, Name: "",
259 NW: OneUseFlags.intersectForOffsetAdd(Other: GEP->getNoWrapFlags())));
260 eraseInstFromFunction(I&: *Inst);
261 }
262 }
263
264 Sum = Add(Sum, Offset);
265 OneUseSum = OneUseBase = nullptr;
266 OneUseFlags = GEPNoWrapFlags::all();
267 }
268 if (OneUseSum)
269 Sum = Add(Sum, OneUseSum);
270 if (!Sum)
271 return Constant::getNullValue(Ty: IdxTy);
272 return Sum;
273}
274
275/// Legal integers and common types are considered desirable. This is used to
276/// avoid creating instructions with types that may not be supported well by the
277/// the backend.
278/// NOTE: This treats i8, i16 and i32 specially because they are common
279/// types in frontend languages.
280bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {
281 switch (BitWidth) {
282 case 8:
283 case 16:
284 case 32:
285 return true;
286 default:
287 return DL.isLegalInteger(Width: BitWidth);
288 }
289}
290
291/// Return true if it is desirable to convert an integer computation from a
292/// given bit width to a new bit width.
293/// We don't want to convert from a legal or desirable type (like i8) to an
294/// illegal type or from a smaller to a larger illegal type. A width of '1'
295/// is always treated as a desirable type because i1 is a fundamental type in
296/// IR, and there are many specialized optimizations for i1 types.
297/// Common/desirable widths are equally treated as legal to convert to, in
298/// order to open up more combining opportunities.
299bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
300 unsigned ToWidth) const {
301 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(Width: FromWidth);
302 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(Width: ToWidth);
303
304 // Convert to desirable widths even if they are not legal types.
305 // Only shrink types, to prevent infinite loops.
306 if (ToWidth < FromWidth && isDesirableIntType(BitWidth: ToWidth))
307 return true;
308
309 // If this is a legal or desiable integer from type, and the result would be
310 // an illegal type, don't do the transformation.
311 if ((FromLegal || isDesirableIntType(BitWidth: FromWidth)) && !ToLegal)
312 return false;
313
314 // Otherwise, if both are illegal, do not increase the size of the result. We
315 // do allow things like i160 -> i64, but not i64 -> i160.
316 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
317 return false;
318
319 return true;
320}
321
322/// Return true if it is desirable to convert a computation from 'From' to 'To'.
323/// We don't want to convert from a legal to an illegal type or from a smaller
324/// to a larger illegal type. i1 is always treated as a legal type because it is
325/// a fundamental type in IR, and there are many specialized optimizations for
326/// i1 types.
327bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
328 // TODO: This could be extended to allow vectors. Datalayout changes might be
329 // needed to properly support that.
330 if (!From->isIntegerTy() || !To->isIntegerTy())
331 return false;
332
333 unsigned FromWidth = From->getPrimitiveSizeInBits();
334 unsigned ToWidth = To->getPrimitiveSizeInBits();
335 return shouldChangeType(FromWidth, ToWidth);
336}
337
338// Return true, if No Signed Wrap should be maintained for I.
339// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
340// where both B and C should be ConstantInts, results in a constant that does
341// not overflow. This function only handles the Add/Sub/Mul opcodes. For
342// all other opcodes, the function conservatively returns false.
343static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
344 auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: &I);
345 if (!OBO || !OBO->hasNoSignedWrap())
346 return false;
347
348 const APInt *BVal, *CVal;
349 if (!match(V: B, P: m_APInt(Res&: BVal)) || !match(V: C, P: m_APInt(Res&: CVal)))
350 return false;
351
352 // We reason about Add/Sub/Mul Only.
353 bool Overflow = false;
354 switch (I.getOpcode()) {
355 case Instruction::Add:
356 (void)BVal->sadd_ov(RHS: *CVal, Overflow);
357 break;
358 case Instruction::Sub:
359 (void)BVal->ssub_ov(RHS: *CVal, Overflow);
360 break;
361 case Instruction::Mul:
362 (void)BVal->smul_ov(RHS: *CVal, Overflow);
363 break;
364 default:
365 // Conservatively return false for other opcodes.
366 return false;
367 }
368 return !Overflow;
369}
370
371static bool hasNoUnsignedWrap(BinaryOperator &I) {
372 auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: &I);
373 return OBO && OBO->hasNoUnsignedWrap();
374}
375
376static bool hasNoSignedWrap(BinaryOperator &I) {
377 auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: &I);
378 return OBO && OBO->hasNoSignedWrap();
379}
380
381/// Combine constant operands of associative operations either before or after a
382/// cast to eliminate one of the associative operations:
383/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
384/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
385static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1,
386 InstCombinerImpl &IC) {
387 auto *Cast = dyn_cast<CastInst>(Val: BinOp1->getOperand(i_nocapture: 0));
388 if (!Cast || !Cast->hasOneUse())
389 return false;
390
391 // TODO: Enhance logic for other casts and remove this check.
392 auto CastOpcode = Cast->getOpcode();
393 if (CastOpcode != Instruction::ZExt)
394 return false;
395
396 // TODO: Enhance logic for other BinOps and remove this check.
397 if (!BinOp1->isBitwiseLogicOp())
398 return false;
399
400 auto AssocOpcode = BinOp1->getOpcode();
401 auto *BinOp2 = dyn_cast<BinaryOperator>(Val: Cast->getOperand(i_nocapture: 0));
402 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
403 return false;
404
405 Constant *C1, *C2;
406 if (!match(V: BinOp1->getOperand(i_nocapture: 1), P: m_Constant(C&: C1)) ||
407 !match(V: BinOp2->getOperand(i_nocapture: 1), P: m_Constant(C&: C2)))
408 return false;
409
410 // TODO: This assumes a zext cast.
411 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
412 // to the destination type might lose bits.
413
414 // Fold the constants together in the destination type:
415 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
416 const DataLayout &DL = IC.getDataLayout();
417 Type *DestTy = C1->getType();
418 Constant *CastC2 = ConstantFoldCastOperand(Opcode: CastOpcode, C: C2, DestTy, DL);
419 if (!CastC2)
420 return false;
421 Constant *FoldedC = ConstantFoldBinaryOpOperands(Opcode: AssocOpcode, LHS: C1, RHS: CastC2, DL);
422 if (!FoldedC)
423 return false;
424
425 IC.replaceOperand(I&: *Cast, OpNum: 0, V: BinOp2->getOperand(i_nocapture: 0));
426 IC.replaceOperand(I&: *BinOp1, OpNum: 1, V: FoldedC);
427 BinOp1->dropPoisonGeneratingFlags();
428 Cast->dropPoisonGeneratingFlags();
429 return true;
430}
431
432// Simplifies IntToPtr/PtrToInt RoundTrip Cast.
433// inttoptr ( ptrtoint (x) ) --> x
434Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
435 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
436 if (IntToPtr && DL.getTypeSizeInBits(Ty: IntToPtr->getDestTy()) ==
437 DL.getTypeSizeInBits(Ty: IntToPtr->getSrcTy())) {
438 auto *PtrToInt = dyn_cast<PtrToIntInst>(Val: IntToPtr->getOperand(i_nocapture: 0));
439 Type *CastTy = IntToPtr->getDestTy();
440 if (PtrToInt &&
441 CastTy->getPointerAddressSpace() ==
442 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
443 DL.getTypeSizeInBits(Ty: PtrToInt->getSrcTy()) ==
444 DL.getTypeSizeInBits(Ty: PtrToInt->getDestTy()))
445 return PtrToInt->getOperand(i_nocapture: 0);
446 }
447 return nullptr;
448}
449
450/// This performs a few simplifications for operators that are associative or
451/// commutative:
452///
453/// Commutative operators:
454///
455/// 1. Order operands such that they are listed from right (least complex) to
456/// left (most complex). This puts constants before unary operators before
457/// binary operators.
458///
459/// Associative operators:
460///
461/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
462/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
463///
464/// Associative and commutative operators:
465///
466/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
467/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
468/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
469/// if C1 and C2 are constants.
470bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
471 Instruction::BinaryOps Opcode = I.getOpcode();
472 bool Changed = false;
473
474 do {
475 // Order operands such that they are listed from right (least complex) to
476 // left (most complex). This puts constants before unary operators before
477 // binary operators.
478 if (I.isCommutative() && getComplexity(V: I.getOperand(i_nocapture: 0)) <
479 getComplexity(V: I.getOperand(i_nocapture: 1)))
480 Changed = !I.swapOperands();
481
482 if (I.isCommutative()) {
483 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
484 replaceOperand(I, OpNum: 0, V: Pair->first);
485 replaceOperand(I, OpNum: 1, V: Pair->second);
486 Changed = true;
487 }
488 }
489
490 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 0));
491 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 1));
492
493 if (I.isAssociative()) {
494 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
495 if (Op0 && Op0->getOpcode() == Opcode) {
496 Value *A = Op0->getOperand(i_nocapture: 0);
497 Value *B = Op0->getOperand(i_nocapture: 1);
498 Value *C = I.getOperand(i_nocapture: 1);
499
500 // Does "B op C" simplify?
501 if (Value *V = simplifyBinOp(Opcode, LHS: B, RHS: C, Q: SQ.getWithInstruction(I: &I))) {
502 // It simplifies to V. Form "A op V".
503 replaceOperand(I, OpNum: 0, V: A);
504 replaceOperand(I, OpNum: 1, V);
505 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(I&: *Op0);
506 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(I&: *Op0);
507
508 // Conservatively clear all optional flags since they may not be
509 // preserved by the reassociation. Reset nsw/nuw based on the above
510 // analysis.
511 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(Val: &I))
512 PDI->setIsDisjoint(false);
513
514 // Note: this is only valid because SimplifyBinOp doesn't look at
515 // the operands to Op0.
516 if (isa<OverflowingBinaryOperator>(Val: I)) {
517 I.setHasNoUnsignedWrap(IsNUW);
518 I.setHasNoSignedWrap(IsNSW);
519 }
520
521 Changed = true;
522 ++NumReassoc;
523 continue;
524 }
525 }
526
527 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
528 if (Op1 && Op1->getOpcode() == Opcode) {
529 Value *A = I.getOperand(i_nocapture: 0);
530 Value *B = Op1->getOperand(i_nocapture: 0);
531 Value *C = Op1->getOperand(i_nocapture: 1);
532
533 // Does "A op B" simplify?
534 if (Value *V = simplifyBinOp(Opcode, LHS: A, RHS: B, Q: SQ.getWithInstruction(I: &I))) {
535 // It simplifies to V. Form "V op C".
536 replaceOperand(I, OpNum: 0, V);
537 replaceOperand(I, OpNum: 1, V: C);
538 // Conservatively clear the optional flags, since they may not be
539 // preserved by the reassociation.
540 if (!isa<FPMathOperator>(Val: I))
541 I.dropPoisonGeneratingFlags();
542 Changed = true;
543 ++NumReassoc;
544 continue;
545 }
546 }
547 }
548
549 if (I.isAssociative() && I.isCommutative()) {
550 if (simplifyAssocCastAssoc(BinOp1: &I, IC&: *this)) {
551 Changed = true;
552 ++NumReassoc;
553 continue;
554 }
555
556 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
557 if (Op0 && Op0->getOpcode() == Opcode) {
558 Value *A = Op0->getOperand(i_nocapture: 0);
559 Value *B = Op0->getOperand(i_nocapture: 1);
560 Value *C = I.getOperand(i_nocapture: 1);
561
562 // Does "C op A" simplify?
563 if (Value *V = simplifyBinOp(Opcode, LHS: C, RHS: A, Q: SQ.getWithInstruction(I: &I))) {
564 // It simplifies to V. Form "V op B".
565 replaceOperand(I, OpNum: 0, V);
566 replaceOperand(I, OpNum: 1, V: B);
567 // Conservatively clear the optional flags, since they may not be
568 // preserved by the reassociation.
569 if (!isa<FPMathOperator>(Val: I))
570 I.dropPoisonGeneratingFlags();
571 Changed = true;
572 ++NumReassoc;
573 continue;
574 }
575 }
576
577 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
578 if (Op1 && Op1->getOpcode() == Opcode) {
579 Value *A = I.getOperand(i_nocapture: 0);
580 Value *B = Op1->getOperand(i_nocapture: 0);
581 Value *C = Op1->getOperand(i_nocapture: 1);
582
583 // Does "C op A" simplify?
584 if (Value *V = simplifyBinOp(Opcode, LHS: C, RHS: A, Q: SQ.getWithInstruction(I: &I))) {
585 // It simplifies to V. Form "B op V".
586 replaceOperand(I, OpNum: 0, V: B);
587 replaceOperand(I, OpNum: 1, V);
588 // Conservatively clear the optional flags, since they may not be
589 // preserved by the reassociation.
590 if (!isa<FPMathOperator>(Val: I))
591 I.dropPoisonGeneratingFlags();
592 Changed = true;
593 ++NumReassoc;
594 continue;
595 }
596 }
597
598 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
599 // if C1 and C2 are constants.
600 Value *A, *B;
601 Constant *C1, *C2, *CRes;
602 if (Op0 && Op1 &&
603 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
604 match(V: Op0, P: m_OneUse(SubPattern: m_BinOp(L: m_Value(V&: A), R: m_Constant(C&: C1)))) &&
605 match(V: Op1, P: m_OneUse(SubPattern: m_BinOp(L: m_Value(V&: B), R: m_Constant(C&: C2)))) &&
606 (CRes = ConstantFoldBinaryOpOperands(Opcode, LHS: C1, RHS: C2, DL))) {
607 bool IsNUW = hasNoUnsignedWrap(I) &&
608 hasNoUnsignedWrap(I&: *Op0) &&
609 hasNoUnsignedWrap(I&: *Op1);
610 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
611 BinaryOperator::CreateNUW(Opc: Opcode, V1: A, V2: B) :
612 BinaryOperator::Create(Op: Opcode, S1: A, S2: B);
613
614 if (isa<FPMathOperator>(Val: NewBO)) {
615 FastMathFlags Flags = I.getFastMathFlags() &
616 Op0->getFastMathFlags() &
617 Op1->getFastMathFlags();
618 NewBO->setFastMathFlags(Flags);
619 }
620 InsertNewInstWith(New: NewBO, Old: I.getIterator());
621 NewBO->takeName(V: Op1);
622 replaceOperand(I, OpNum: 0, V: NewBO);
623 replaceOperand(I, OpNum: 1, V: CRes);
624 // Conservatively clear the optional flags, since they may not be
625 // preserved by the reassociation.
626 if (!isa<FPMathOperator>(Val: I))
627 I.dropPoisonGeneratingFlags();
628 if (IsNUW)
629 I.setHasNoUnsignedWrap(true);
630
631 Changed = true;
632 continue;
633 }
634 }
635
636 // No further simplifications.
637 return Changed;
638 } while (true);
639}
640
641/// Return whether "X LOp (Y ROp Z)" is always equal to
642/// "(X LOp Y) ROp (X LOp Z)".
643static bool leftDistributesOverRight(Instruction::BinaryOps LOp,
644 Instruction::BinaryOps ROp) {
645 // X & (Y | Z) <--> (X & Y) | (X & Z)
646 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
647 if (LOp == Instruction::And)
648 return ROp == Instruction::Or || ROp == Instruction::Xor;
649
650 // X | (Y & Z) <--> (X | Y) & (X | Z)
651 if (LOp == Instruction::Or)
652 return ROp == Instruction::And;
653
654 // X * (Y + Z) <--> (X * Y) + (X * Z)
655 // X * (Y - Z) <--> (X * Y) - (X * Z)
656 if (LOp == Instruction::Mul)
657 return ROp == Instruction::Add || ROp == Instruction::Sub;
658
659 return false;
660}
661
662/// Return whether "(X LOp Y) ROp Z" is always equal to
663/// "(X ROp Z) LOp (Y ROp Z)".
664static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,
665 Instruction::BinaryOps ROp) {
666 if (Instruction::isCommutative(Opcode: ROp))
667 return leftDistributesOverRight(LOp: ROp, ROp: LOp);
668
669 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
670 return Instruction::isBitwiseLogicOp(Opcode: LOp) && Instruction::isShift(Opcode: ROp);
671
672 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
673 // but this requires knowing that the addition does not overflow and other
674 // such subtleties.
675}
676
677/// This function returns identity value for given opcode, which can be used to
678/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
679static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
680 if (isa<Constant>(Val: V))
681 return nullptr;
682
683 return ConstantExpr::getBinOpIdentity(Opcode, Ty: V->getType());
684}
685
686/// This function predicates factorization using distributive laws. By default,
687/// it just returns the 'Op' inputs. But for special-cases like
688/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
689/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
690/// allow more factorization opportunities.
691static Instruction::BinaryOps
692getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,
693 Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) {
694 assert(Op && "Expected a binary operator");
695 LHS = Op->getOperand(i_nocapture: 0);
696 RHS = Op->getOperand(i_nocapture: 1);
697 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
698 Constant *C;
699 if (match(V: Op, P: m_Shl(L: m_Value(), R: m_ImmConstant(C)))) {
700 // X << C --> X * (1 << C)
701 RHS = ConstantFoldBinaryInstruction(
702 Opcode: Instruction::Shl, V1: ConstantInt::get(Ty: Op->getType(), V: 1), V2: C);
703 assert(RHS && "Constant folding of immediate constants failed");
704 return Instruction::Mul;
705 }
706 // TODO: We can add other conversions e.g. shr => div etc.
707 }
708 if (Instruction::isBitwiseLogicOp(Opcode: TopOpcode)) {
709 if (OtherOp && OtherOp->getOpcode() == Instruction::AShr &&
710 match(V: Op, P: m_LShr(L: m_NonNegative(), R: m_Value()))) {
711 // lshr nneg C, X --> ashr nneg C, X
712 return Instruction::AShr;
713 }
714 }
715 return Op->getOpcode();
716}
717
718/// This tries to simplify binary operations by factorizing out common terms
719/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
720static Value *tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ,
721 InstCombiner::BuilderTy &Builder,
722 Instruction::BinaryOps InnerOpcode, Value *A,
723 Value *B, Value *C, Value *D) {
724 assert(A && B && C && D && "All values must be provided");
725
726 Value *V = nullptr;
727 Value *RetVal = nullptr;
728 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
729 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
730
731 // Does "X op' Y" always equal "Y op' X"?
732 bool InnerCommutative = Instruction::isCommutative(Opcode: InnerOpcode);
733
734 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
735 if (leftDistributesOverRight(LOp: InnerOpcode, ROp: TopLevelOpcode)) {
736 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
737 // commutative case, "(A op' B) op (C op' A)"?
738 if (A == C || (InnerCommutative && A == D)) {
739 if (A != C)
740 std::swap(a&: C, b&: D);
741 // Consider forming "A op' (B op D)".
742 // If "B op D" simplifies then it can be formed with no cost.
743 V = simplifyBinOp(Opcode: TopLevelOpcode, LHS: B, RHS: D, Q: SQ.getWithInstruction(I: &I));
744
745 // If "B op D" doesn't simplify then only go on if one of the existing
746 // operations "A op' B" and "C op' D" will be zapped as no longer used.
747 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
748 V = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: B, RHS: D, Name: RHS->getName());
749 if (V)
750 RetVal = Builder.CreateBinOp(Opc: InnerOpcode, LHS: A, RHS: V);
751 }
752 }
753
754 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
755 if (!RetVal && rightDistributesOverLeft(LOp: TopLevelOpcode, ROp: InnerOpcode)) {
756 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
757 // commutative case, "(A op' B) op (B op' D)"?
758 if (B == D || (InnerCommutative && B == C)) {
759 if (B != D)
760 std::swap(a&: C, b&: D);
761 // Consider forming "(A op C) op' B".
762 // If "A op C" simplifies then it can be formed with no cost.
763 V = simplifyBinOp(Opcode: TopLevelOpcode, LHS: A, RHS: C, Q: SQ.getWithInstruction(I: &I));
764
765 // If "A op C" doesn't simplify then only go on if one of the existing
766 // operations "A op' B" and "C op' D" will be zapped as no longer used.
767 if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))
768 V = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: A, RHS: C, Name: LHS->getName());
769 if (V)
770 RetVal = Builder.CreateBinOp(Opc: InnerOpcode, LHS: V, RHS: B);
771 }
772 }
773
774 if (!RetVal)
775 return nullptr;
776
777 ++NumFactor;
778 RetVal->takeName(V: &I);
779
780 // Try to add no-overflow flags to the final value.
781 if (isa<BinaryOperator>(Val: RetVal)) {
782 bool HasNSW = false;
783 bool HasNUW = false;
784 if (isa<OverflowingBinaryOperator>(Val: &I)) {
785 HasNSW = I.hasNoSignedWrap();
786 HasNUW = I.hasNoUnsignedWrap();
787 }
788 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(Val: LHS)) {
789 HasNSW &= LOBO->hasNoSignedWrap();
790 HasNUW &= LOBO->hasNoUnsignedWrap();
791 }
792
793 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(Val: RHS)) {
794 HasNSW &= ROBO->hasNoSignedWrap();
795 HasNUW &= ROBO->hasNoUnsignedWrap();
796 }
797
798 if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {
799 // We can propagate 'nsw' if we know that
800 // %Y = mul nsw i16 %X, C
801 // %Z = add nsw i16 %Y, %X
802 // =>
803 // %Z = mul nsw i16 %X, C+1
804 //
805 // iff C+1 isn't INT_MIN
806 const APInt *CInt;
807 if (match(V, P: m_APInt(Res&: CInt)) && !CInt->isMinSignedValue())
808 cast<Instruction>(Val: RetVal)->setHasNoSignedWrap(HasNSW);
809
810 // nuw can be propagated with any constant or nuw value.
811 cast<Instruction>(Val: RetVal)->setHasNoUnsignedWrap(HasNUW);
812 }
813 }
814 return RetVal;
815}
816
817// If `I` has one Const operand and the other matches `(ctpop (not x))`,
818// replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.
819// This is only useful is the new subtract can fold so we only handle the
820// following cases:
821// 1) (add/sub/disjoint_or C, (ctpop (not x))
822// -> (add/sub/disjoint_or C', (ctpop x))
823// 1) (cmp pred C, (ctpop (not x))
824// -> (cmp pred C', (ctpop x))
825Instruction *InstCombinerImpl::tryFoldInstWithCtpopWithNot(Instruction *I) {
826 unsigned Opc = I->getOpcode();
827 unsigned ConstIdx = 1;
828 switch (Opc) {
829 default:
830 return nullptr;
831 // (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))
832 // We can fold the BitWidth(x) with add/sub/icmp as long the other operand
833 // is constant.
834 case Instruction::Sub:
835 ConstIdx = 0;
836 break;
837 case Instruction::ICmp:
838 // Signed predicates aren't correct in some edge cases like for i2 types, as
839 // well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed
840 // comparisons against it are simplfied to unsigned.
841 if (cast<ICmpInst>(Val: I)->isSigned())
842 return nullptr;
843 break;
844 case Instruction::Or:
845 if (!match(V: I, P: m_DisjointOr(L: m_Value(), R: m_Value())))
846 return nullptr;
847 [[fallthrough]];
848 case Instruction::Add:
849 break;
850 }
851
852 Value *Op;
853 // Find ctpop.
854 if (!match(V: I->getOperand(i: 1 - ConstIdx), P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: Op)))))
855 return nullptr;
856
857 Constant *C;
858 // Check other operand is ImmConstant.
859 if (!match(V: I->getOperand(i: ConstIdx), P: m_ImmConstant(C)))
860 return nullptr;
861
862 Type *Ty = Op->getType();
863 Constant *BitWidthC = ConstantInt::get(Ty, V: Ty->getScalarSizeInBits());
864 // Need extra check for icmp. Note if this check is true, it generally means
865 // the icmp will simplify to true/false.
866 if (Opc == Instruction::ICmp && !cast<ICmpInst>(Val: I)->isEquality()) {
867 Constant *Cmp =
868 ConstantFoldCompareInstOperands(Predicate: ICmpInst::ICMP_UGT, LHS: C, RHS: BitWidthC, DL);
869 if (!Cmp || !Cmp->isNullValue())
870 return nullptr;
871 }
872
873 // Check we can invert `(not x)` for free.
874 bool Consumes = false;
875 if (!isFreeToInvert(V: Op, WillInvertAllUses: Op->hasOneUse(), DoesConsume&: Consumes) || !Consumes)
876 return nullptr;
877 Value *NotOp = getFreelyInverted(V: Op, WillInvertAllUses: Op->hasOneUse(), Builder: &Builder);
878 assert(NotOp != nullptr &&
879 "Desync between isFreeToInvert and getFreelyInverted");
880
881 Value *CtpopOfNotOp = Builder.CreateIntrinsic(RetTy: Ty, ID: Intrinsic::ctpop, Args: NotOp);
882
883 Value *R = nullptr;
884
885 // Do the transformation here to avoid potentially introducing an infinite
886 // loop.
887 switch (Opc) {
888 case Instruction::Sub:
889 R = Builder.CreateAdd(LHS: CtpopOfNotOp, RHS: ConstantExpr::getSub(C1: C, C2: BitWidthC));
890 break;
891 case Instruction::Or:
892 case Instruction::Add:
893 R = Builder.CreateSub(LHS: ConstantExpr::getAdd(C1: C, C2: BitWidthC), RHS: CtpopOfNotOp);
894 break;
895 case Instruction::ICmp:
896 R = Builder.CreateICmp(P: cast<ICmpInst>(Val: I)->getSwappedPredicate(),
897 LHS: CtpopOfNotOp, RHS: ConstantExpr::getSub(C1: BitWidthC, C2: C));
898 break;
899 default:
900 llvm_unreachable("Unhandled Opcode");
901 }
902 assert(R != nullptr);
903 return replaceInstUsesWith(I&: *I, V: R);
904}
905
906// (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))
907// IFF
908// 1) the logic_shifts match
909// 2) either both binops are binops and one is `and` or
910// BinOp1 is `and`
911// (logic_shift (inv_logic_shift C1, C), C) == C1 or
912//
913// -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)
914//
915// (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))
916// IFF
917// 1) the logic_shifts match
918// 2) BinOp1 == BinOp2 (if BinOp == `add`, then also requires `shl`).
919//
920// -> (BinOp (logic_shift (BinOp X, Y)), Mask)
921//
922// (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt))
923// IFF
924// 1) Binop1 is bitwise logical operator `and`, `or` or `xor`
925// 2) Binop2 is `not`
926//
927// -> (arithmetic_shift Binop1((not X), Y), Amt)
928
929Instruction *InstCombinerImpl::foldBinOpShiftWithShift(BinaryOperator &I) {
930 const DataLayout &DL = I.getDataLayout();
931 auto IsValidBinOpc = [](unsigned Opc) {
932 switch (Opc) {
933 default:
934 return false;
935 case Instruction::And:
936 case Instruction::Or:
937 case Instruction::Xor:
938 case Instruction::Add:
939 // Skip Sub as we only match constant masks which will canonicalize to use
940 // add.
941 return true;
942 }
943 };
944
945 // Check if we can distribute binop arbitrarily. `add` + `lshr` has extra
946 // constraints.
947 auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2,
948 unsigned ShOpc) {
949 assert(ShOpc != Instruction::AShr);
950 return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||
951 ShOpc == Instruction::Shl;
952 };
953
954 auto GetInvShift = [](unsigned ShOpc) {
955 assert(ShOpc != Instruction::AShr);
956 return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;
957 };
958
959 auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2,
960 unsigned ShOpc, Constant *CMask,
961 Constant *CShift) {
962 // If the BinOp1 is `and` we don't need to check the mask.
963 if (BinOpc1 == Instruction::And)
964 return true;
965
966 // For all other possible transfers we need complete distributable
967 // binop/shift (anything but `add` + `lshr`).
968 if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))
969 return false;
970
971 // If BinOp2 is `and`, any mask works (this only really helps for non-splat
972 // vecs, otherwise the mask will be simplified and the following check will
973 // handle it).
974 if (BinOpc2 == Instruction::And)
975 return true;
976
977 // Otherwise, need mask that meets the below requirement.
978 // (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask
979 Constant *MaskInvShift =
980 ConstantFoldBinaryOpOperands(Opcode: GetInvShift(ShOpc), LHS: CMask, RHS: CShift, DL);
981 return ConstantFoldBinaryOpOperands(Opcode: ShOpc, LHS: MaskInvShift, RHS: CShift, DL) ==
982 CMask;
983 };
984
985 auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * {
986 Constant *CMask, *CShift;
987 Value *X, *Y, *ShiftedX, *Mask, *Shift;
988 if (!match(V: I.getOperand(i_nocapture: ShOpnum),
989 P: m_OneUse(SubPattern: m_Shift(L: m_Value(V&: Y), R: m_Value(V&: Shift)))))
990 return nullptr;
991 if (!match(
992 V: I.getOperand(i_nocapture: 1 - ShOpnum),
993 P: m_OneUse(SubPattern: m_c_BinOp(
994 L: m_CombineAnd(Ps: m_OneUse(SubPattern: m_Shift(L: m_Value(V&: X), R: m_Specific(V: Shift))),
995 Ps: m_Value(V&: ShiftedX)),
996 R: m_Value(V&: Mask)))))
997 return nullptr;
998 // Make sure we are matching instruction shifts and not ConstantExpr
999 auto *IY = dyn_cast<Instruction>(Val: I.getOperand(i_nocapture: ShOpnum));
1000 auto *IX = dyn_cast<Instruction>(Val: ShiftedX);
1001 if (!IY || !IX)
1002 return nullptr;
1003
1004 // LHS and RHS need same shift opcode
1005 unsigned ShOpc = IY->getOpcode();
1006 if (ShOpc != IX->getOpcode())
1007 return nullptr;
1008
1009 // Make sure binop is real instruction and not ConstantExpr
1010 auto *BO2 = dyn_cast<Instruction>(Val: I.getOperand(i_nocapture: 1 - ShOpnum));
1011 if (!BO2)
1012 return nullptr;
1013
1014 unsigned BinOpc = BO2->getOpcode();
1015 // Make sure we have valid binops.
1016 if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc))
1017 return nullptr;
1018
1019 if (ShOpc == Instruction::AShr) {
1020 if (Instruction::isBitwiseLogicOp(Opcode: I.getOpcode()) &&
1021 BinOpc == Instruction::Xor && match(V: Mask, P: m_AllOnes())) {
1022 Value *NotX = Builder.CreateNot(V: X);
1023 Value *NewBinOp = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: Y, RHS: NotX);
1024 return BinaryOperator::Create(
1025 Op: static_cast<Instruction::BinaryOps>(ShOpc), S1: NewBinOp, S2: Shift);
1026 }
1027
1028 return nullptr;
1029 }
1030
1031 // If BinOp1 == BinOp2 and it's bitwise or shl with add, then just
1032 // distribute to drop the shift irrelevant of constants.
1033 if (BinOpc == I.getOpcode() &&
1034 IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) {
1035 Value *NewBinOp2 = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: X, RHS: Y);
1036 Value *NewBinOp1 = Builder.CreateBinOp(
1037 Opc: static_cast<Instruction::BinaryOps>(ShOpc), LHS: NewBinOp2, RHS: Shift);
1038 return BinaryOperator::Create(Op: I.getOpcode(), S1: NewBinOp1, S2: Mask);
1039 }
1040
1041 // Otherwise we can only distribute by constant shifting the mask, so
1042 // ensure we have constants.
1043 if (!match(V: Shift, P: m_ImmConstant(C&: CShift)))
1044 return nullptr;
1045 if (!match(V: Mask, P: m_ImmConstant(C&: CMask)))
1046 return nullptr;
1047
1048 // Check if we can distribute the binops.
1049 if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift))
1050 return nullptr;
1051
1052 Constant *NewCMask =
1053 ConstantFoldBinaryOpOperands(Opcode: GetInvShift(ShOpc), LHS: CMask, RHS: CShift, DL);
1054 Value *NewBinOp2 = Builder.CreateBinOp(
1055 Opc: static_cast<Instruction::BinaryOps>(BinOpc), LHS: X, RHS: NewCMask);
1056 Value *NewBinOp1 = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: Y, RHS: NewBinOp2);
1057 return BinaryOperator::Create(Op: static_cast<Instruction::BinaryOps>(ShOpc),
1058 S1: NewBinOp1, S2: CShift);
1059 };
1060
1061 if (Instruction *R = MatchBinOp(0))
1062 return R;
1063 return MatchBinOp(1);
1064}
1065
1066// (Binop (zext C), (select C, T, F))
1067// -> (select C, (binop 1, T), (binop 0, F))
1068//
1069// (Binop (sext C), (select C, T, F))
1070// -> (select C, (binop -1, T), (binop 0, F))
1071//
1072// Attempt to simplify binary operations into a select with folded args, when
1073// one operand of the binop is a select instruction and the other operand is a
1074// zext/sext extension, whose value is the select condition.
1075Instruction *
1076InstCombinerImpl::foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I) {
1077 // TODO: this simplification may be extended to any speculatable instruction,
1078 // not just binops, and would possibly be handled better in FoldOpIntoSelect.
1079 Instruction::BinaryOps Opc = I.getOpcode();
1080 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1081 Value *A, *CondVal, *TrueVal, *FalseVal;
1082 Value *CastOp;
1083 Constant *CastTrueVal, *CastFalseVal;
1084
1085 auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) {
1086 return match(V: CastOp, P: m_SelectLike(C: m_Value(V&: A), TrueC: m_Constant(C&: CastTrueVal),
1087 FalseC: m_Constant(C&: CastFalseVal))) &&
1088 match(V: SelectOp, P: m_Select(C: m_Value(V&: CondVal), L: m_Value(V&: TrueVal),
1089 R: m_Value(V&: FalseVal)));
1090 };
1091
1092 // Make sure one side of the binop is a select instruction, and the other is a
1093 // zero/sign extension operating on a i1.
1094 if (MatchSelectAndCast(LHS, RHS))
1095 CastOp = LHS;
1096 else if (MatchSelectAndCast(RHS, LHS))
1097 CastOp = RHS;
1098 else
1099 return nullptr;
1100
1101 SelectInst *SI = cast<SelectInst>(Val: CastOp == LHS ? RHS : LHS);
1102
1103 auto NewFoldedConst = [&](bool IsTrueArm, Value *V) {
1104 bool IsCastOpRHS = (CastOp == RHS);
1105 Value *CastVal = IsTrueArm ? CastFalseVal : CastTrueVal;
1106
1107 return IsCastOpRHS ? Builder.CreateBinOp(Opc, LHS: V, RHS: CastVal)
1108 : Builder.CreateBinOp(Opc, LHS: CastVal, RHS: V);
1109 };
1110
1111 // If the value used in the zext/sext is the select condition, or the negated
1112 // of the select condition, the binop can be simplified.
1113 if (CondVal == A) {
1114 Value *NewTrueVal = NewFoldedConst(false, TrueVal);
1115 return SelectInst::Create(C: CondVal, S1: NewTrueVal,
1116 S2: NewFoldedConst(true, FalseVal), NameStr: "", InsertBefore: nullptr, MDFrom: SI);
1117 }
1118 if (match(V: A, P: m_Not(V: m_Specific(V: CondVal)))) {
1119 Value *NewTrueVal = NewFoldedConst(true, TrueVal);
1120 return SelectInst::Create(C: CondVal, S1: NewTrueVal,
1121 S2: NewFoldedConst(false, FalseVal), NameStr: "", InsertBefore: nullptr, MDFrom: SI);
1122 }
1123
1124 return nullptr;
1125}
1126
1127Value *InstCombinerImpl::tryFactorizationFolds(BinaryOperator &I) {
1128 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1129 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(Val: LHS);
1130 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(Val: RHS);
1131 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1132 Value *A, *B, *C, *D;
1133 Instruction::BinaryOps LHSOpcode, RHSOpcode;
1134
1135 if (Op0)
1136 LHSOpcode = getBinOpsForFactorization(TopOpcode: TopLevelOpcode, Op: Op0, LHS&: A, RHS&: B, OtherOp: Op1);
1137 if (Op1)
1138 RHSOpcode = getBinOpsForFactorization(TopOpcode: TopLevelOpcode, Op: Op1, LHS&: C, RHS&: D, OtherOp: Op0);
1139
1140 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
1141 // a common term.
1142 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
1143 if (Value *V = tryFactorization(I, SQ, Builder, InnerOpcode: LHSOpcode, A, B, C, D))
1144 return V;
1145
1146 // The instruction has the form "(A op' B) op (C)". Try to factorize common
1147 // term.
1148 if (Op0)
1149 if (Value *Ident = getIdentityValue(Opcode: LHSOpcode, V: RHS))
1150 if (Value *V =
1151 tryFactorization(I, SQ, Builder, InnerOpcode: LHSOpcode, A, B, C: RHS, D: Ident))
1152 return V;
1153
1154 // The instruction has the form "(B) op (C op' D)". Try to factorize common
1155 // term.
1156 if (Op1)
1157 if (Value *Ident = getIdentityValue(Opcode: RHSOpcode, V: LHS))
1158 if (Value *V =
1159 tryFactorization(I, SQ, Builder, InnerOpcode: RHSOpcode, A: LHS, B: Ident, C, D))
1160 return V;
1161
1162 return nullptr;
1163}
1164
1165/// This tries to simplify binary operations which some other binary operation
1166/// distributes over either by factorizing out common terms
1167/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
1168/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
1169/// Returns the simplified value, or null if it didn't simplify.
1170Value *InstCombinerImpl::foldUsingDistributiveLaws(BinaryOperator &I) {
1171 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1172 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(Val: LHS);
1173 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(Val: RHS);
1174 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
1175
1176 // Factorization.
1177 if (Value *R = tryFactorizationFolds(I))
1178 return R;
1179
1180 // Expansion.
1181 if (Op0 && rightDistributesOverLeft(LOp: Op0->getOpcode(), ROp: TopLevelOpcode)) {
1182 // The instruction has the form "(A op' B) op C". See if expanding it out
1183 // to "(A op C) op' (B op C)" results in simplifications.
1184 Value *A = Op0->getOperand(i_nocapture: 0), *B = Op0->getOperand(i_nocapture: 1), *C = RHS;
1185 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
1186
1187 // Disable the use of undef because it's not safe to distribute undef.
1188 auto SQDistributive = SQ.getWithInstruction(I: &I).getWithoutUndef();
1189 Value *L = simplifyBinOp(Opcode: TopLevelOpcode, LHS: A, RHS: C, Q: SQDistributive);
1190 Value *R = simplifyBinOp(Opcode: TopLevelOpcode, LHS: B, RHS: C, Q: SQDistributive);
1191
1192 // Do "A op C" and "B op C" both simplify?
1193 if (L && R) {
1194 // They do! Return "L op' R".
1195 ++NumExpand;
1196 C = Builder.CreateBinOp(Opc: InnerOpcode, LHS: L, RHS: R);
1197 C->takeName(V: &I);
1198 return C;
1199 }
1200
1201 // Does "A op C" simplify to the identity value for the inner opcode?
1202 if (L && L == ConstantExpr::getBinOpIdentity(Opcode: InnerOpcode, Ty: L->getType())) {
1203 // They do! Return "B op C".
1204 ++NumExpand;
1205 C = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: B, RHS: C);
1206 C->takeName(V: &I);
1207 return C;
1208 }
1209
1210 // Does "B op C" simplify to the identity value for the inner opcode?
1211 if (R && R == ConstantExpr::getBinOpIdentity(Opcode: InnerOpcode, Ty: R->getType())) {
1212 // They do! Return "A op C".
1213 ++NumExpand;
1214 C = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: A, RHS: C);
1215 C->takeName(V: &I);
1216 return C;
1217 }
1218 }
1219
1220 if (Op1 && leftDistributesOverRight(LOp: TopLevelOpcode, ROp: Op1->getOpcode())) {
1221 // The instruction has the form "A op (B op' C)". See if expanding it out
1222 // to "(A op B) op' (A op C)" results in simplifications.
1223 Value *A = LHS, *B = Op1->getOperand(i_nocapture: 0), *C = Op1->getOperand(i_nocapture: 1);
1224 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
1225
1226 // Disable the use of undef because it's not safe to distribute undef.
1227 auto SQDistributive = SQ.getWithInstruction(I: &I).getWithoutUndef();
1228 Value *L = simplifyBinOp(Opcode: TopLevelOpcode, LHS: A, RHS: B, Q: SQDistributive);
1229 Value *R = simplifyBinOp(Opcode: TopLevelOpcode, LHS: A, RHS: C, Q: SQDistributive);
1230
1231 // Do "A op B" and "A op C" both simplify?
1232 if (L && R) {
1233 // They do! Return "L op' R".
1234 ++NumExpand;
1235 A = Builder.CreateBinOp(Opc: InnerOpcode, LHS: L, RHS: R);
1236 A->takeName(V: &I);
1237 return A;
1238 }
1239
1240 // Does "A op B" simplify to the identity value for the inner opcode?
1241 if (L && L == ConstantExpr::getBinOpIdentity(Opcode: InnerOpcode, Ty: L->getType())) {
1242 // They do! Return "A op C".
1243 ++NumExpand;
1244 A = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: A, RHS: C);
1245 A->takeName(V: &I);
1246 return A;
1247 }
1248
1249 // Does "A op C" simplify to the identity value for the inner opcode?
1250 if (R && R == ConstantExpr::getBinOpIdentity(Opcode: InnerOpcode, Ty: R->getType())) {
1251 // They do! Return "A op B".
1252 ++NumExpand;
1253 A = Builder.CreateBinOp(Opc: TopLevelOpcode, LHS: A, RHS: B);
1254 A->takeName(V: &I);
1255 return A;
1256 }
1257 }
1258
1259 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
1260}
1261
1262static std::optional<std::pair<Value *, Value *>>
1263matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS) {
1264 if (LHS->getParent() != RHS->getParent())
1265 return std::nullopt;
1266
1267 if (LHS->getNumIncomingValues() < 2)
1268 return std::nullopt;
1269
1270 if (!equal(LRange: LHS->blocks(), RRange: RHS->blocks()))
1271 return std::nullopt;
1272
1273 Value *L0 = LHS->getIncomingValue(i: 0);
1274 Value *R0 = RHS->getIncomingValue(i: 0);
1275
1276 for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) {
1277 Value *L1 = LHS->getIncomingValue(i: I);
1278 Value *R1 = RHS->getIncomingValue(i: I);
1279
1280 if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))
1281 continue;
1282
1283 return std::nullopt;
1284 }
1285
1286 return std::optional(std::pair(L0, R0));
1287}
1288
1289std::optional<std::pair<Value *, Value *>>
1290InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) {
1291 Instruction *LHSInst = dyn_cast<Instruction>(Val: LHS);
1292 Instruction *RHSInst = dyn_cast<Instruction>(Val: RHS);
1293 if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode())
1294 return std::nullopt;
1295 switch (LHSInst->getOpcode()) {
1296 case Instruction::PHI:
1297 return matchSymmetricPhiNodesPair(LHS: cast<PHINode>(Val: LHS), RHS: cast<PHINode>(Val: RHS));
1298 case Instruction::Select: {
1299 Value *Cond = LHSInst->getOperand(i: 0);
1300 Value *TrueVal = LHSInst->getOperand(i: 1);
1301 Value *FalseVal = LHSInst->getOperand(i: 2);
1302 if (Cond == RHSInst->getOperand(i: 0) && TrueVal == RHSInst->getOperand(i: 2) &&
1303 FalseVal == RHSInst->getOperand(i: 1))
1304 return std::pair(TrueVal, FalseVal);
1305 return std::nullopt;
1306 }
1307 case Instruction::Call: {
1308 // Match min(a, b) and max(a, b)
1309 MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(Val: LHSInst);
1310 MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(Val: RHSInst);
1311 if (LHSMinMax && RHSMinMax &&
1312 LHSMinMax->getPredicate() ==
1313 ICmpInst::getSwappedPredicate(pred: RHSMinMax->getPredicate()) &&
1314 ((LHSMinMax->getLHS() == RHSMinMax->getLHS() &&
1315 LHSMinMax->getRHS() == RHSMinMax->getRHS()) ||
1316 (LHSMinMax->getLHS() == RHSMinMax->getRHS() &&
1317 LHSMinMax->getRHS() == RHSMinMax->getLHS())))
1318 return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS());
1319 return std::nullopt;
1320 }
1321 default:
1322 return std::nullopt;
1323 }
1324}
1325
1326Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
1327 Value *LHS,
1328 Value *RHS) {
1329 Value *A, *B, *C, *D, *E, *F;
1330 bool LHSIsSelect = match(V: LHS, P: m_Select(C: m_Value(V&: A), L: m_Value(V&: B), R: m_Value(V&: C)));
1331 bool RHSIsSelect = match(V: RHS, P: m_Select(C: m_Value(V&: D), L: m_Value(V&: E), R: m_Value(V&: F)));
1332 if (!LHSIsSelect && !RHSIsSelect)
1333 return nullptr;
1334
1335 SelectInst *SI = cast<SelectInst>(Val: LHSIsSelect ? LHS : RHS);
1336
1337 FastMathFlags FMF;
1338 BuilderTy::FastMathFlagGuard Guard(Builder);
1339 if (const auto *FPOp = dyn_cast<FPMathOperator>(Val: &I)) {
1340 FMF = FPOp->getFastMathFlags();
1341 Builder.setFastMathFlags(FMF);
1342 }
1343
1344 Instruction::BinaryOps Opcode = I.getOpcode();
1345 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
1346
1347 Value *Cond, *True = nullptr, *False = nullptr;
1348
1349 // If V is a select whose condition is implied by Cond, resolve it to the
1350 // appropriate arm for this value of Cond.
1351 auto simplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
1352 bool CondIsTrue) -> Value * {
1353 auto *InnerSI = dyn_cast<SelectInst>(Val: V);
1354 if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
1355 return V;
1356
1357 if (std::optional<bool> Implied =
1358 isImpliedCondition(LHS: Cond, RHS: InnerSI->getCondition(), DL, LHSIsTrue: CondIsTrue))
1359 return InnerSI->getOperand(i_nocapture: *Implied ? 1 : 2);
1360 return V;
1361 };
1362
1363 // Special-case for add/negate combination. Replace the zero in the negation
1364 // with the trailing add operand:
1365 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
1366 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
1367 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
1368 // We need an 'add' and exactly 1 arm of the select to have been simplified.
1369 if (Opcode != Instruction::Add || (!True && !False) || (True && False))
1370 return nullptr;
1371 Value *N;
1372 if (True && match(V: FVal, P: m_Neg(V: m_Value(V&: N)))) {
1373 Value *Sub = Builder.CreateSub(LHS: Z, RHS: N);
1374 return Builder.CreateSelect(C: Cond, True, False: Sub, Name: I.getName(), MDFrom: SI);
1375 }
1376 if (False && match(V: TVal, P: m_Neg(V: m_Value(V&: N)))) {
1377 Value *Sub = Builder.CreateSub(LHS: Z, RHS: N);
1378 return Builder.CreateSelect(C: Cond, True: Sub, False, Name: I.getName(), MDFrom: SI);
1379 }
1380 return nullptr;
1381 };
1382
1383 if (LHSIsSelect && RHSIsSelect && A == D) {
1384 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
1385 Cond = A;
1386 True = simplifyBinOp(Opcode, LHS: B, RHS: E, FMF, Q);
1387 False = simplifyBinOp(Opcode, LHS: C, RHS: F, FMF, Q);
1388
1389 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1390 if (False && !True)
1391 True = Builder.CreateBinOp(Opc: Opcode, LHS: B, RHS: E);
1392 else if (True && !False)
1393 False = Builder.CreateBinOp(Opc: Opcode, LHS: C, RHS: F);
1394 }
1395 } else if (LHSIsSelect && LHS->hasOneUse()) {
1396 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
1397 Cond = A;
1398 Value *TrueRHS = simplifySelectWithImpliedCond(RHS, Cond, true);
1399 Value *FalseRHS = simplifySelectWithImpliedCond(RHS, Cond, false);
1400 True = simplifyBinOp(Opcode, LHS: B, RHS: TrueRHS, FMF, Q);
1401 False = simplifyBinOp(Opcode, LHS: C, RHS: FalseRHS, FMF, Q);
1402 if (Value *NewSel = foldAddNegate(B, C, RHS))
1403 return NewSel;
1404 } else if (RHSIsSelect && RHS->hasOneUse()) {
1405 // X op (D ? E : F) -> D ? (X op E) : (X op F)
1406 Cond = D;
1407 Value *TrueLHS = simplifySelectWithImpliedCond(LHS, Cond, true);
1408 Value *FalseLHS = simplifySelectWithImpliedCond(LHS, Cond, false);
1409 True = simplifyBinOp(Opcode, LHS: TrueLHS, RHS: E, FMF, Q);
1410 False = simplifyBinOp(Opcode, LHS: FalseLHS, RHS: F, FMF, Q);
1411 if (Value *NewSel = foldAddNegate(E, F, LHS))
1412 return NewSel;
1413 }
1414
1415 if (!True || !False)
1416 return nullptr;
1417
1418 Value *NewSI = Builder.CreateSelect(C: Cond, True, False, Name: I.getName(), MDFrom: SI);
1419 NewSI->takeName(V: &I);
1420 return NewSI;
1421}
1422
1423/// Freely adapt every user of V as-if V was changed to !V.
1424/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
1425void InstCombinerImpl::freelyInvertAllUsersOf(Value *I, Value *IgnoredUser) {
1426 assert(!isa<Constant>(I) && "Shouldn't invert users of constant");
1427 for (User *U : make_early_inc_range(Range: I->users())) {
1428 if (U == IgnoredUser)
1429 continue; // Don't consider this user.
1430 switch (cast<Instruction>(Val: U)->getOpcode()) {
1431 case Instruction::Select: {
1432 auto *SI = cast<SelectInst>(Val: U);
1433 SI->swapValues();
1434 SI->swapProfMetadata();
1435 break;
1436 }
1437 case Instruction::CondBr: {
1438 CondBrInst *BI = cast<CondBrInst>(Val: U);
1439 BI->swapSuccessors(); // swaps prof metadata too
1440 if (BPI)
1441 BPI->swapSuccEdgesProbabilities(Src: BI->getParent());
1442 break;
1443 }
1444 case Instruction::Xor:
1445 replaceInstUsesWith(I&: cast<Instruction>(Val&: *U), V: I);
1446 // Add to worklist for DCE.
1447 addToWorklist(I: cast<Instruction>(Val: U));
1448 break;
1449 default:
1450 llvm_unreachable("Got unexpected user - out of sync with "
1451 "canFreelyInvertAllUsersOf() ?");
1452 }
1453 }
1454
1455 // Update pre-existing debug value uses.
1456 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1457 llvm::findDbgValues(V: I, DbgVariableRecords);
1458
1459 for (DbgVariableRecord *DbgVal : DbgVariableRecords) {
1460 SmallVector<uint64_t, 1> Ops = {dwarf::DW_OP_not};
1461 for (unsigned Idx = 0, End = DbgVal->getNumVariableLocationOps();
1462 Idx != End; ++Idx)
1463 if (DbgVal->getVariableLocationOp(OpIdx: Idx) == I)
1464 DbgVal->setExpression(
1465 DIExpression::appendOpsToArg(Expr: DbgVal->getExpression(), Ops, ArgNo: Idx));
1466 }
1467}
1468
1469/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
1470/// constant zero (which is the 'negate' form).
1471Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
1472 Value *NegV;
1473 if (match(V, P: m_Neg(V: m_Value(V&: NegV))))
1474 return NegV;
1475
1476 // Constants can be considered to be negated values if they can be folded.
1477 if (ConstantInt *C = dyn_cast<ConstantInt>(Val: V))
1478 return ConstantExpr::getNeg(C);
1479
1480 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(Val: V))
1481 if (C->getType()->getElementType()->isIntegerTy())
1482 return ConstantExpr::getNeg(C);
1483
1484 if (ConstantVector *CV = dyn_cast<ConstantVector>(Val: V)) {
1485 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1486 Constant *Elt = CV->getAggregateElement(Elt: i);
1487 if (!Elt)
1488 return nullptr;
1489
1490 if (isa<UndefValue>(Val: Elt))
1491 continue;
1492
1493 if (!isa<ConstantInt>(Val: Elt))
1494 return nullptr;
1495 }
1496 return ConstantExpr::getNeg(C: CV);
1497 }
1498
1499 // Negate integer vector splats.
1500 if (auto *CV = dyn_cast<Constant>(Val: V))
1501 if (CV->getType()->isVectorTy() &&
1502 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1503 return ConstantExpr::getNeg(C: CV);
1504
1505 return nullptr;
1506}
1507
1508// Try to fold:
1509// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1510// -> ({s|u}itofp (int_binop x, y))
1511// 2) (fp_binop ({s|u}itofp x), FpC)
1512// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1513//
1514// Assuming the sign of the cast for x/y is `OpsFromSigned`.
1515Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(
1516 BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
1517 Constant *Op1FpC, SmallVectorImpl<WithCache<const Value *>> &OpsKnown) {
1518
1519 Type *FPTy = BO.getType();
1520 Type *IntTy = IntOps[0]->getType();
1521
1522 unsigned IntSz = IntTy->getScalarSizeInBits();
1523 // This is the maximum number of inuse bits by the integer where the int -> fp
1524 // casts are exact.
1525 unsigned MaxRepresentableBits =
1526 APFloat::semanticsPrecision(FPTy->getScalarType()->getFltSemantics());
1527
1528 // Preserve known number of leading bits. This can allow us to trivial nsw/nuw
1529 // checks later on.
1530 unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};
1531
1532 // NB: This only comes up if OpsFromSigned is true, so there is no need to
1533 // cache if between calls to `foldFBinOpOfIntCastsFromSign`.
1534 auto IsNonZero = [&](unsigned OpNo) -> bool {
1535 if (OpsKnown[OpNo].hasKnownBits() &&
1536 OpsKnown[OpNo].getKnownBits(Q: SQ).isNonZero())
1537 return true;
1538 return isKnownNonZero(V: IntOps[OpNo], Q: SQ);
1539 };
1540
1541 auto IsNonNeg = [&](unsigned OpNo) -> bool {
1542 // NB: This matches the impl in ValueTracking, we just try to use cached
1543 // knownbits here. If we ever start supporting WithCache for
1544 // `isKnownNonNegative`, change this to an explicit call.
1545 return OpsKnown[OpNo].getKnownBits(Q: SQ).isNonNegative();
1546 };
1547
1548 // Check if we know for certain that ({s|u}itofp op) is exact.
1549 auto IsValidPromotion = [&](unsigned OpNo) -> bool {
1550 // Can we treat this operand as the desired sign?
1551 if (OpsFromSigned != isa<SIToFPInst>(Val: BO.getOperand(i_nocapture: OpNo)) &&
1552 !IsNonNeg(OpNo))
1553 return false;
1554
1555 // If fp precision >= bitwidth(op) then its exact.
1556 // NB: This is slightly conservative for `sitofp`. For signed conversion, we
1557 // can handle `MaxRepresentableBits == IntSz - 1` as the sign bit will be
1558 // handled specially. We can't, however, increase the bound arbitrarily for
1559 // `sitofp` as for larger sizes, it won't sign extend.
1560 if (MaxRepresentableBits < IntSz) {
1561 // Otherwise if its signed cast check that fp precisions >= bitwidth(op) -
1562 // numSignBits(op).
1563 // TODO: If we add support for `WithCache` in `ComputeNumSignBits`, change
1564 // `IntOps[OpNo]` arguments to `KnownOps[OpNo]`.
1565 if (OpsFromSigned)
1566 NumUsedLeadingBits[OpNo] = IntSz - ComputeNumSignBits(Op: IntOps[OpNo]);
1567 // Finally for unsigned check that fp precision >= bitwidth(op) -
1568 // numLeadingZeros(op).
1569 else {
1570 NumUsedLeadingBits[OpNo] =
1571 IntSz - OpsKnown[OpNo].getKnownBits(Q: SQ).countMinLeadingZeros();
1572 }
1573 }
1574 // NB: We could also check if op is known to be a power of 2 or zero (which
1575 // will always be representable). Its unlikely, however, that is we are
1576 // unable to bound op in any way we will be able to pass the overflow checks
1577 // later on.
1578
1579 if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])
1580 return false;
1581 // Signed + Mul also requires that op is non-zero to avoid -0 cases.
1582 return !OpsFromSigned || BO.getOpcode() != Instruction::FMul ||
1583 IsNonZero(OpNo);
1584 };
1585
1586 // If we have a constant rhs, see if we can losslessly convert it to an int.
1587 if (Op1FpC != nullptr) {
1588 // Signed + Mul req non-zero
1589 if (OpsFromSigned && BO.getOpcode() == Instruction::FMul &&
1590 !match(V: Op1FpC, P: m_NonZeroFP()))
1591 return nullptr;
1592
1593 Constant *Op1IntC = ConstantFoldCastOperand(
1594 Opcode: OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, C: Op1FpC,
1595 DestTy: IntTy, DL);
1596 if (Op1IntC == nullptr)
1597 return nullptr;
1598 if (ConstantFoldCastOperand(Opcode: OpsFromSigned ? Instruction::SIToFP
1599 : Instruction::UIToFP,
1600 C: Op1IntC, DestTy: FPTy, DL) != Op1FpC)
1601 return nullptr;
1602
1603 // First try to keep sign of cast the same.
1604 IntOps[1] = Op1IntC;
1605 }
1606
1607 // Ensure lhs/rhs integer types match.
1608 if (IntTy != IntOps[1]->getType())
1609 return nullptr;
1610
1611 if (Op1FpC == nullptr) {
1612 if (!IsValidPromotion(1))
1613 return nullptr;
1614 }
1615 if (!IsValidPromotion(0))
1616 return nullptr;
1617
1618 // Final we check if the integer version of the binop will not overflow.
1619 BinaryOperator::BinaryOps IntOpc;
1620 // Because of the precision check, we can often rule out overflows.
1621 bool NeedsOverflowCheck = true;
1622 // Try to conservatively rule out overflow based on the already done precision
1623 // checks.
1624 unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;
1625 unsigned OverflowMaxCurBits =
1626 std::max(a: NumUsedLeadingBits[0], b: NumUsedLeadingBits[1]);
1627 bool OutputSigned = OpsFromSigned;
1628 switch (BO.getOpcode()) {
1629 case Instruction::FAdd:
1630 IntOpc = Instruction::Add;
1631 OverflowMaxOutputBits += OverflowMaxCurBits;
1632 break;
1633 case Instruction::FSub:
1634 IntOpc = Instruction::Sub;
1635 OverflowMaxOutputBits += OverflowMaxCurBits;
1636 break;
1637 case Instruction::FMul:
1638 IntOpc = Instruction::Mul;
1639 OverflowMaxOutputBits += OverflowMaxCurBits * 2;
1640 break;
1641 default:
1642 llvm_unreachable("Unsupported binop");
1643 }
1644 // The precision check may have already ruled out overflow.
1645 if (OverflowMaxOutputBits < IntSz) {
1646 NeedsOverflowCheck = false;
1647 // We can bound unsigned overflow from sub to in range signed value (this is
1648 // what allows us to avoid the overflow check for sub).
1649 if (IntOpc == Instruction::Sub)
1650 OutputSigned = true;
1651 }
1652
1653 // Precision check did not rule out overflow, so need to check.
1654 // TODO: If we add support for `WithCache` in `willNotOverflow`, change
1655 // `IntOps[...]` arguments to `KnownOps[...]`.
1656 if (NeedsOverflowCheck &&
1657 !willNotOverflow(Opcode: IntOpc, LHS: IntOps[0], RHS: IntOps[1], CtxI: BO, IsSigned: OutputSigned))
1658 return nullptr;
1659
1660 Value *IntBinOp = Builder.CreateBinOp(Opc: IntOpc, LHS: IntOps[0], RHS: IntOps[1]);
1661 if (auto *IntBO = dyn_cast<BinaryOperator>(Val: IntBinOp)) {
1662 IntBO->setHasNoSignedWrap(OutputSigned);
1663 IntBO->setHasNoUnsignedWrap(!OutputSigned);
1664 }
1665 if (OutputSigned)
1666 return new SIToFPInst(IntBinOp, FPTy);
1667 return new UIToFPInst(IntBinOp, FPTy);
1668}
1669
1670// Try to fold:
1671// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1672// -> ({s|u}itofp (int_binop x, y))
1673// 2) (fp_binop ({s|u}itofp x), FpC)
1674// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1675Instruction *InstCombinerImpl::foldFBinOpOfIntCasts(BinaryOperator &BO) {
1676 // Don't perform the fold on vectors, as the integer operation may be much
1677 // more expensive than the float operation in that case.
1678 if (BO.getType()->isVectorTy())
1679 return nullptr;
1680
1681 std::array<Value *, 2> IntOps = {nullptr, nullptr};
1682 Constant *Op1FpC = nullptr;
1683 // Check for:
1684 // 1) (binop ({s|u}itofp x), ({s|u}itofp y))
1685 // 2) (binop ({s|u}itofp x), FpC)
1686 if (!match(V: BO.getOperand(i_nocapture: 0), P: m_IToFP(Op: m_Value(V&: IntOps[0]))))
1687 return nullptr;
1688
1689 if (!match(V: BO.getOperand(i_nocapture: 1), P: m_Constant(C&: Op1FpC)) &&
1690 !match(V: BO.getOperand(i_nocapture: 1), P: m_IToFP(Op: m_Value(V&: IntOps[1]))))
1691 return nullptr;
1692
1693 // Cache KnownBits a bit to potentially save some analysis.
1694 SmallVector<WithCache<const Value *>, 2> OpsKnown = {IntOps[0], IntOps[1]};
1695
1696 // Try treating x/y as coming from both `uitofp` and `sitofp`. There are
1697 // different constraints depending on the sign of the cast.
1698 // NB: `(uitofp nneg X)` == `(sitofp nneg X)`.
1699 if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/false,
1700 IntOps, Op1FpC, OpsKnown))
1701 return R;
1702 return foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/true, IntOps,
1703 Op1FpC, OpsKnown);
1704}
1705
1706/// A binop with a constant operand and a sign-extended boolean operand may be
1707/// converted into a select of constants by applying the binary operation to
1708/// the constant with the two possible values of the extended boolean (0 or -1).
1709Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
1710 // TODO: Handle non-commutative binop (constant is operand 0).
1711 // TODO: Handle zext.
1712 // TODO: Peek through 'not' of cast.
1713 Value *BO0 = BO.getOperand(i_nocapture: 0);
1714 Value *BO1 = BO.getOperand(i_nocapture: 1);
1715 Value *X;
1716 Constant *C;
1717 if (!match(V: BO0, P: m_SExt(Op: m_Value(V&: X))) || !match(V: BO1, P: m_ImmConstant(C)) ||
1718 !X->getType()->isIntOrIntVectorTy(BitWidth: 1))
1719 return nullptr;
1720
1721 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
1722 Constant *Ones = ConstantInt::getAllOnesValue(Ty: BO.getType());
1723 Constant *Zero = ConstantInt::getNullValue(Ty: BO.getType());
1724 Value *TVal = Builder.CreateBinOp(Opc: BO.getOpcode(), LHS: Ones, RHS: C);
1725 Value *FVal = Builder.CreateBinOp(Opc: BO.getOpcode(), LHS: Zero, RHS: C);
1726 return createSelectInstWithUnknownProfile(C: X, S1: TVal, S2: FVal);
1727}
1728
1729static Value *simplifyOperationIntoSelectOperand(Instruction &I, SelectInst *SI,
1730 bool IsTrueArm) {
1731 SmallVector<Value *> Ops;
1732 for (Value *Op : I.operands()) {
1733 Value *V = nullptr;
1734 if (Op == SI) {
1735 V = IsTrueArm ? SI->getTrueValue() : SI->getFalseValue();
1736 } else if (match(V: SI->getCondition(),
1737 P: m_SpecificICmp(MatchPred: IsTrueArm ? ICmpInst::ICMP_EQ
1738 : ICmpInst::ICMP_NE,
1739 L: m_Specific(V: Op), R: m_Value(V))) &&
1740 isGuaranteedNotToBeUndefOrPoison(V)) {
1741 // Pass
1742 } else if (match(V: Op, P: m_ZExt(Op: m_Specific(V: SI->getCondition())))) {
1743 V = IsTrueArm ? ConstantInt::get(Ty: Op->getType(), V: 1)
1744 : ConstantInt::getNullValue(Ty: Op->getType());
1745 } else {
1746 V = Op;
1747 }
1748 Ops.push_back(Elt: V);
1749 }
1750
1751 return simplifyInstructionWithOperands(I: &I, NewOps: Ops, Q: I.getDataLayout());
1752}
1753
1754static Value *foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI,
1755 Value *NewOp, InstCombiner &IC) {
1756 Instruction *Clone = I.clone();
1757 Clone->replaceUsesOfWith(From: SI, To: NewOp);
1758 Clone->dropUBImplyingAttrsAndMetadata();
1759 IC.InsertNewInstBefore(New: Clone, Old: I.getIterator());
1760 return Clone;
1761}
1762
1763Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1764 bool FoldWithMultiUse,
1765 bool SimplifyBothArms) {
1766 // Don't modify shared select instructions unless set FoldWithMultiUse
1767 if (!SI->hasOneUser() && !FoldWithMultiUse)
1768 return nullptr;
1769
1770 Value *TV = SI->getTrueValue();
1771 Value *FV = SI->getFalseValue();
1772
1773 // Bool selects with constant operands can be folded to logical ops.
1774 if (SI->getType()->isIntOrIntVectorTy(BitWidth: 1))
1775 return nullptr;
1776
1777 // Avoid breaking min/max reduction pattern,
1778 // which is necessary for vectorization later.
1779 if (isa<MinMaxIntrinsic>(Val: &Op))
1780 for (Value *IntrinOp : Op.operands())
1781 if (auto *PN = dyn_cast<PHINode>(Val: IntrinOp))
1782 for (Value *PhiOp : PN->operands())
1783 if (PhiOp == &Op)
1784 return nullptr;
1785
1786 // Test if a FCmpInst instruction is used exclusively by a select as
1787 // part of a minimum or maximum operation. If so, refrain from doing
1788 // any other folding. This helps out other analyses which understand
1789 // non-obfuscated minimum and maximum idioms. And in this case, at
1790 // least one of the comparison operands has at least one user besides
1791 // the compare (the select), which would often largely negate the
1792 // benefit of folding anyway.
1793 if (auto *CI = dyn_cast<FCmpInst>(Val: SI->getCondition())) {
1794 if (CI->hasOneUse()) {
1795 Value *Op0 = CI->getOperand(i_nocapture: 0), *Op1 = CI->getOperand(i_nocapture: 1);
1796 if (((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1)) &&
1797 !CI->isCommutative())
1798 return nullptr;
1799 }
1800 }
1801
1802 // Make sure that one of the select arms folds successfully.
1803 Value *NewTV = simplifyOperationIntoSelectOperand(I&: Op, SI, /*IsTrueArm=*/true);
1804 Value *NewFV =
1805 simplifyOperationIntoSelectOperand(I&: Op, SI, /*IsTrueArm=*/false);
1806 if (!NewTV && !NewFV)
1807 return nullptr;
1808
1809 if (SimplifyBothArms && !(NewTV && NewFV))
1810 return nullptr;
1811
1812 // Create an instruction for the arm that did not fold.
1813 if (!NewTV)
1814 NewTV = foldOperationIntoSelectOperand(I&: Op, SI, NewOp: TV, IC&: *this);
1815 if (!NewFV)
1816 NewFV = foldOperationIntoSelectOperand(I&: Op, SI, NewOp: FV, IC&: *this);
1817
1818 SelectInst *NewSel = SelectInst::Create(C: SI->getCondition(), S1: NewTV, S2: NewFV);
1819
1820 // Preserve metadata that remains valid for the transformed select including
1821 // source location information.
1822 NewSel->copyMetadata(SrcInst: *SI,
1823 WL: {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1824 LLVMContext::MD_dbg});
1825
1826 return NewSel;
1827}
1828
1829static Value *simplifyInstructionWithPHI(Instruction &I, PHINode *PN,
1830 Value *InValue, BasicBlock *InBB,
1831 const DataLayout &DL,
1832 const SimplifyQuery SQ) {
1833 // NB: It is a precondition of this transform that the operands be
1834 // phi translatable!
1835 SmallVector<Value *> Ops;
1836 for (Value *Op : I.operands()) {
1837 if (Op == PN)
1838 Ops.push_back(Elt: InValue);
1839 else
1840 Ops.push_back(Elt: Op->DoPHITranslation(CurBB: PN->getParent(), PredBB: InBB));
1841 }
1842
1843 // Don't consider the simplification successful if we get back a constant
1844 // expression. That's just an instruction in hiding.
1845 // Also reject the case where we simplify back to the phi node. We wouldn't
1846 // be able to remove it in that case.
1847 Value *NewVal = simplifyInstructionWithOperands(
1848 I: &I, NewOps: Ops, Q: SQ.getWithInstruction(I: InBB->getTerminator()));
1849 if (NewVal && NewVal != PN && !match(V: NewVal, P: m_ConstantExpr()))
1850 return NewVal;
1851
1852 // Check if incoming PHI value can be replaced with constant
1853 // based on implied condition.
1854 CondBrInst *TerminatorBI = dyn_cast<CondBrInst>(Val: InBB->getTerminator());
1855 const ICmpInst *ICmp = dyn_cast<ICmpInst>(Val: &I);
1856 if (TerminatorBI &&
1857 TerminatorBI->getSuccessor(i: 0) != TerminatorBI->getSuccessor(i: 1) && ICmp) {
1858 bool LHSIsTrue = TerminatorBI->getSuccessor(i: 0) == PN->getParent();
1859 std::optional<bool> ImpliedCond = isImpliedCondition(
1860 LHS: TerminatorBI->getCondition(), RHSPred: ICmp->getCmpPredicate(), RHSOp0: Ops[0], RHSOp1: Ops[1],
1861 DL, LHSIsTrue);
1862 if (ImpliedCond)
1863 return ConstantInt::getBool(Ty: I.getType(), V: ImpliedCond.value());
1864 }
1865
1866 return nullptr;
1867}
1868
1869/// In some cases it is beneficial to fold a select into a binary operator.
1870/// For example:
1871/// %1 = or %in, 4
1872/// %2 = select %cond, %1, %in
1873/// %3 = or %2, 1
1874/// =>
1875/// %1 = select i1 %cond, 5, 1
1876/// %2 = or %1, %in
1877Instruction *InstCombinerImpl::foldBinOpSelectBinOp(BinaryOperator &Op) {
1878 assert(Op.isAssociative() && "The operation must be associative!");
1879
1880 SelectInst *SI = dyn_cast<SelectInst>(Val: Op.getOperand(i_nocapture: 0));
1881
1882 Constant *Const;
1883 if (!SI || !match(V: Op.getOperand(i_nocapture: 1), P: m_ImmConstant(C&: Const)) ||
1884 !Op.hasOneUse() || !SI->hasOneUse())
1885 return nullptr;
1886
1887 Value *TV = SI->getTrueValue();
1888 Value *FV = SI->getFalseValue();
1889 Value *Input, *NewTV, *NewFV;
1890 Constant *Const2;
1891
1892 if (TV->hasOneUse() && match(V: TV, P: m_BinOp(Opcode: Op.getOpcode(), L: m_Specific(V: FV),
1893 R: m_ImmConstant(C&: Const2)))) {
1894 NewTV = ConstantFoldBinaryInstruction(Opcode: Op.getOpcode(), V1: Const, V2: Const2);
1895 NewFV = Const;
1896 Input = FV;
1897 } else if (FV->hasOneUse() &&
1898 match(V: FV, P: m_BinOp(Opcode: Op.getOpcode(), L: m_Specific(V: TV),
1899 R: m_ImmConstant(C&: Const2)))) {
1900 NewTV = Const;
1901 NewFV = ConstantFoldBinaryInstruction(Opcode: Op.getOpcode(), V1: Const, V2: Const2);
1902 Input = TV;
1903 } else
1904 return nullptr;
1905
1906 if (!NewTV || !NewFV)
1907 return nullptr;
1908
1909 Value *NewSI = Builder.CreateSelect(C: SI->getCondition(), True: NewTV, False: NewFV, Name: "", MDFrom: SI);
1910 return BinaryOperator::Create(Op: Op.getOpcode(), S1: NewSI, S2: Input);
1911}
1912
1913Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN,
1914 bool AllowMultipleUses) {
1915 unsigned NumPHIValues = PN->getNumIncomingValues();
1916 if (NumPHIValues == 0)
1917 return nullptr;
1918
1919 // We normally only transform phis with a single use. However, if a PHI has
1920 // multiple uses and they are all the same operation, we can fold *all* of the
1921 // uses into the PHI.
1922 bool OneUse = PN->hasOneUse();
1923 bool IdenticalUsers = false;
1924 if (!AllowMultipleUses && !OneUse) {
1925 // Walk the use list for the instruction, comparing them to I.
1926 for (User *U : PN->users()) {
1927 Instruction *UI = cast<Instruction>(Val: U);
1928 if (UI != &I && !I.isIdenticalTo(I: UI))
1929 return nullptr;
1930 }
1931 // Otherwise, we can replace *all* users with the new PHI we form.
1932 IdenticalUsers = true;
1933 }
1934
1935 // Check that all operands are phi-translatable.
1936 for (Value *Op : I.operands()) {
1937 if (Op == PN)
1938 continue;
1939
1940 // Non-instructions never require phi-translation.
1941 auto *I = dyn_cast<Instruction>(Val: Op);
1942 if (!I)
1943 continue;
1944
1945 // Phi-translate can handle phi nodes in the same block.
1946 if (isa<PHINode>(Val: I))
1947 if (I->getParent() == PN->getParent())
1948 continue;
1949
1950 // Operand dominates the block, no phi-translation necessary.
1951 if (DT.dominates(Def: I, BB: PN->getParent()))
1952 continue;
1953
1954 // Not phi-translatable, bail out.
1955 return nullptr;
1956 }
1957
1958 // Check to see whether the instruction can be folded into each phi operand.
1959 // If there is one operand that does not fold, remember the BB it is in.
1960 SmallVector<Value *> NewPhiValues;
1961 SmallVector<unsigned int> OpsToMoveUseToIncomingBB;
1962 bool SeenNonSimplifiedInVal = false;
1963 for (unsigned i = 0; i != NumPHIValues; ++i) {
1964 Value *InVal = PN->getIncomingValue(i);
1965 BasicBlock *InBB = PN->getIncomingBlock(i);
1966
1967 if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InValue: InVal, InBB, DL, SQ)) {
1968 NewPhiValues.push_back(Elt: NewVal);
1969 continue;
1970 }
1971
1972 // Handle some cases that can't be fully simplified, but where we know that
1973 // the two instructions will fold into one.
1974 auto WillFold = [&]() {
1975 if (!InVal->hasUseList() || !InVal->hasOneUser())
1976 return false;
1977
1978 // icmp of ucmp/scmp with constant will fold to icmp.
1979 const APInt *Ignored;
1980 if (isa<CmpIntrinsic>(Val: InVal) &&
1981 match(V: &I, P: m_ICmp(L: m_Specific(V: PN), R: m_APInt(Res&: Ignored))))
1982 return true;
1983
1984 // icmp eq zext(bool), 0 will fold to !bool.
1985 if (isa<ZExtInst>(Val: InVal) &&
1986 cast<ZExtInst>(Val: InVal)->getSrcTy()->isIntOrIntVectorTy(BitWidth: 1) &&
1987 match(V: &I,
1988 P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: PN), R: m_Zero())))
1989 return true;
1990
1991 return false;
1992 };
1993
1994 if (WillFold()) {
1995 OpsToMoveUseToIncomingBB.push_back(Elt: i);
1996 NewPhiValues.push_back(Elt: nullptr);
1997 continue;
1998 }
1999
2000 if (!OneUse && !IdenticalUsers)
2001 return nullptr;
2002
2003 if (SeenNonSimplifiedInVal)
2004 return nullptr; // More than one non-simplified value.
2005 SeenNonSimplifiedInVal = true;
2006
2007 // If there is exactly one non-simplified value, we can insert a copy of the
2008 // operation in that block. However, if this is a critical edge, we would
2009 // be inserting the computation on some other paths (e.g. inside a loop).
2010 // Only do this if the pred block is unconditionally branching into the phi
2011 // block. Also, make sure that the pred block is not dead code.
2012 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: InBB->getTerminator());
2013 if (!BI || !DT.isReachableFromEntry(A: InBB))
2014 return nullptr;
2015
2016 NewPhiValues.push_back(Elt: nullptr);
2017 OpsToMoveUseToIncomingBB.push_back(Elt: i);
2018
2019 // Do not push the operation across a loop backedge. This could result in
2020 // an infinite combine loop, and is generally non-profitable (especially
2021 // if the operation was originally outside the loop).
2022 if (isBackEdge(From: InBB, To: PN->getParent()))
2023 return nullptr;
2024 }
2025
2026 // Clone the instruction that uses the phi node and move it into the incoming
2027 // BB because we know that the next iteration of InstCombine will simplify it.
2028 SmallDenseMap<BasicBlock *, Instruction *> Clones;
2029 for (auto OpIndex : OpsToMoveUseToIncomingBB) {
2030 Value *Op = PN->getIncomingValue(i: OpIndex);
2031 BasicBlock *OpBB = PN->getIncomingBlock(i: OpIndex);
2032
2033 Instruction *Clone = Clones.lookup(Val: OpBB);
2034 if (!Clone) {
2035 Clone = I.clone();
2036 for (Use &U : Clone->operands()) {
2037 if (U == PN)
2038 U = Op;
2039 else
2040 U = U->DoPHITranslation(CurBB: PN->getParent(), PredBB: OpBB);
2041 }
2042 Clone = InsertNewInstBefore(New: Clone, Old: OpBB->getTerminator()->getIterator());
2043 Clones.insert(KV: {OpBB, Clone});
2044 // We may have speculated the instruction.
2045 Clone->dropUBImplyingAttrsAndMetadata();
2046 }
2047
2048 NewPhiValues[OpIndex] = Clone;
2049 }
2050
2051 // Okay, we can do the transformation: create the new PHI node.
2052 PHINode *NewPN = PHINode::Create(Ty: I.getType(), NumReservedValues: PN->getNumIncomingValues());
2053 InsertNewInstBefore(New: NewPN, Old: PN->getIterator());
2054 NewPN->takeName(V: PN);
2055 NewPN->setDebugLoc(PN->getDebugLoc());
2056
2057 for (unsigned i = 0; i != NumPHIValues; ++i)
2058 NewPN->addIncoming(V: NewPhiValues[i], BB: PN->getIncomingBlock(i));
2059
2060 if (IdenticalUsers) {
2061 // Collect and deduplicate users up-front to avoid iterator invalidation.
2062 SmallSetVector<Instruction *, 4> ToReplace;
2063 for (User *U : PN->users()) {
2064 Instruction *User = cast<Instruction>(Val: U);
2065 if (User == &I)
2066 continue;
2067 ToReplace.insert(X: User);
2068 }
2069 for (Instruction *I : ToReplace) {
2070 replaceInstUsesWith(I&: *I, V: NewPN);
2071 eraseInstFromFunction(I&: *I);
2072 }
2073 OneUse = true;
2074 }
2075
2076 if (OneUse) {
2077 replaceAllDbgUsesWith(From&: *PN, To&: *NewPN, DomPoint&: *PN, DT);
2078 }
2079 return replaceInstUsesWith(I, V: NewPN);
2080}
2081
2082Instruction *InstCombinerImpl::foldBinopWithRecurrence(BinaryOperator &BO) {
2083 if (!BO.isAssociative())
2084 return nullptr;
2085
2086 // Find the interleaved binary ops.
2087 auto Opc = BO.getOpcode();
2088 auto *BO0 = dyn_cast<BinaryOperator>(Val: BO.getOperand(i_nocapture: 0));
2089 auto *BO1 = dyn_cast<BinaryOperator>(Val: BO.getOperand(i_nocapture: 1));
2090 if (!BO0 || !BO1 || !BO0->hasNUses(N: 2) || !BO1->hasNUses(N: 2) ||
2091 BO0->getOpcode() != Opc || BO1->getOpcode() != Opc ||
2092 !BO0->isAssociative() || !BO1->isAssociative() ||
2093 BO0->getParent() != BO1->getParent())
2094 return nullptr;
2095
2096 assert(BO.isCommutative() && BO0->isCommutative() && BO1->isCommutative() &&
2097 "Expected commutative instructions!");
2098
2099 // Find the matching phis, forming the recurrences.
2100 PHINode *PN0, *PN1;
2101 Value *Start0, *Step0, *Start1, *Step1;
2102 if (!matchSimpleRecurrence(I: BO0, P&: PN0, Start&: Start0, Step&: Step0) || !PN0->hasOneUse() ||
2103 !matchSimpleRecurrence(I: BO1, P&: PN1, Start&: Start1, Step&: Step1) || !PN1->hasOneUse() ||
2104 PN0->getParent() != PN1->getParent())
2105 return nullptr;
2106
2107 assert(PN0->getNumIncomingValues() == 2 && PN1->getNumIncomingValues() == 2 &&
2108 "Expected PHIs with two incoming values!");
2109
2110 // Convert the start and step values to constants.
2111 auto *Init0 = dyn_cast<Constant>(Val: Start0);
2112 auto *Init1 = dyn_cast<Constant>(Val: Start1);
2113 auto *C0 = dyn_cast<Constant>(Val: Step0);
2114 auto *C1 = dyn_cast<Constant>(Val: Step1);
2115 if (!Init0 || !Init1 || !C0 || !C1)
2116 return nullptr;
2117
2118 // Fold the recurrence constants.
2119 auto *Init = ConstantFoldBinaryInstruction(Opcode: Opc, V1: Init0, V2: Init1);
2120 auto *C = ConstantFoldBinaryInstruction(Opcode: Opc, V1: C0, V2: C1);
2121 if (!Init || !C)
2122 return nullptr;
2123
2124 // Create the reduced PHI.
2125 auto *NewPN = PHINode::Create(Ty: PN0->getType(), NumReservedValues: PN0->getNumIncomingValues(),
2126 NameStr: "reduced.phi");
2127
2128 // Create the new binary op.
2129 auto *NewBO = BinaryOperator::Create(Op: Opc, S1: NewPN, S2: C);
2130 if (Opc == Instruction::FAdd || Opc == Instruction::FMul) {
2131 // Intersect FMF flags for FADD and FMUL.
2132 FastMathFlags Intersect = BO0->getFastMathFlags() &
2133 BO1->getFastMathFlags() & BO.getFastMathFlags();
2134 NewBO->setFastMathFlags(Intersect);
2135 } else {
2136 OverflowTracking Flags;
2137 Flags.AllKnownNonNegative = false;
2138 Flags.AllKnownNonZero = false;
2139 Flags.mergeFlags(I&: *BO0);
2140 Flags.mergeFlags(I&: *BO1);
2141 Flags.mergeFlags(I&: BO);
2142 Flags.applyFlags(I&: *NewBO);
2143 }
2144 NewBO->takeName(V: &BO);
2145
2146 for (unsigned I = 0, E = PN0->getNumIncomingValues(); I != E; ++I) {
2147 auto *V = PN0->getIncomingValue(i: I);
2148 auto *BB = PN0->getIncomingBlock(i: I);
2149 if (V == Init0) {
2150 assert(((PN1->getIncomingValue(0) == Init1 &&
2151 PN1->getIncomingBlock(0) == BB) ||
2152 (PN1->getIncomingValue(1) == Init1 &&
2153 PN1->getIncomingBlock(1) == BB)) &&
2154 "Invalid incoming block!");
2155 NewPN->addIncoming(V: Init, BB);
2156 } else if (V == BO0) {
2157 assert(((PN1->getIncomingValue(0) == BO1 &&
2158 PN1->getIncomingBlock(0) == BB) ||
2159 (PN1->getIncomingValue(1) == BO1 &&
2160 PN1->getIncomingBlock(1) == BB)) &&
2161 "Invalid incoming block!");
2162 NewPN->addIncoming(V: NewBO, BB);
2163 } else
2164 llvm_unreachable("Unexpected incoming value!");
2165 }
2166
2167 LLVM_DEBUG(dbgs() << " Combined " << *PN0 << "\n " << *BO0
2168 << "\n with " << *PN1 << "\n " << *BO1
2169 << '\n');
2170
2171 // Insert the new recurrence and remove the old (dead) ones.
2172 InsertNewInstWith(New: NewPN, Old: PN0->getIterator());
2173 InsertNewInstWith(New: NewBO, Old: BO0->getIterator());
2174
2175 eraseInstFromFunction(
2176 I&: *replaceInstUsesWith(I&: *BO0, V: PoisonValue::get(T: BO0->getType())));
2177 eraseInstFromFunction(
2178 I&: *replaceInstUsesWith(I&: *BO1, V: PoisonValue::get(T: BO1->getType())));
2179 eraseInstFromFunction(I&: *PN0);
2180 eraseInstFromFunction(I&: *PN1);
2181
2182 return replaceInstUsesWith(I&: BO, V: NewBO);
2183}
2184
2185Instruction *InstCombinerImpl::foldBinopWithPhiOperands(BinaryOperator &BO) {
2186 // Attempt to fold binary operators whose operands are simple recurrences.
2187 if (auto *NewBO = foldBinopWithRecurrence(BO))
2188 return NewBO;
2189
2190 // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
2191 // we are guarding against replicating the binop in >1 predecessor.
2192 // This could miss matching a phi with 2 constant incoming values.
2193 auto *Phi0 = dyn_cast<PHINode>(Val: BO.getOperand(i_nocapture: 0));
2194 auto *Phi1 = dyn_cast<PHINode>(Val: BO.getOperand(i_nocapture: 1));
2195 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
2196 Phi0->getNumOperands() != Phi1->getNumOperands())
2197 return nullptr;
2198
2199 // TODO: Remove the restriction for binop being in the same block as the phis.
2200 if (BO.getParent() != Phi0->getParent() ||
2201 BO.getParent() != Phi1->getParent())
2202 return nullptr;
2203
2204 // Fold if there is at least one specific constant value in phi0 or phi1's
2205 // incoming values that comes from the same block and this specific constant
2206 // value can be used to do optimization for specific binary operator.
2207 // For example:
2208 // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
2209 // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
2210 // %add = add i32 %phi0, %phi1
2211 // ==>
2212 // %add = phi i32 [%j, %bb0], [%i, %bb1]
2213 Constant *C = ConstantExpr::getBinOpIdentity(Opcode: BO.getOpcode(), Ty: BO.getType(),
2214 /*AllowRHSConstant*/ false);
2215 if (C) {
2216 SmallVector<Value *, 4> NewIncomingValues;
2217 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
2218 auto &Phi0Use = std::get<0>(t&: T);
2219 auto &Phi1Use = std::get<1>(t&: T);
2220 if (Phi0->getIncomingBlock(U: Phi0Use) != Phi1->getIncomingBlock(U: Phi1Use))
2221 return false;
2222 Value *Phi0UseV = Phi0Use.get();
2223 Value *Phi1UseV = Phi1Use.get();
2224 if (Phi0UseV == C)
2225 NewIncomingValues.push_back(Elt: Phi1UseV);
2226 else if (Phi1UseV == C)
2227 NewIncomingValues.push_back(Elt: Phi0UseV);
2228 else
2229 return false;
2230 return true;
2231 };
2232
2233 if (all_of(Range: zip(t: Phi0->operands(), u: Phi1->operands()),
2234 P: CanFoldIncomingValuePair)) {
2235 PHINode *NewPhi =
2236 PHINode::Create(Ty: Phi0->getType(), NumReservedValues: Phi0->getNumOperands());
2237 assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
2238 "The number of collected incoming values should equal the number "
2239 "of the original PHINode operands!");
2240 for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
2241 NewPhi->addIncoming(V: NewIncomingValues[I], BB: Phi0->getIncomingBlock(i: I));
2242 return NewPhi;
2243 }
2244 }
2245
2246 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
2247 return nullptr;
2248
2249 // Match a pair of incoming constants for one of the predecessor blocks.
2250 BasicBlock *ConstBB, *OtherBB;
2251 Constant *C0, *C1;
2252 if (match(V: Phi0->getIncomingValue(i: 0), P: m_ImmConstant(C&: C0))) {
2253 ConstBB = Phi0->getIncomingBlock(i: 0);
2254 OtherBB = Phi0->getIncomingBlock(i: 1);
2255 } else if (match(V: Phi0->getIncomingValue(i: 1), P: m_ImmConstant(C&: C0))) {
2256 ConstBB = Phi0->getIncomingBlock(i: 1);
2257 OtherBB = Phi0->getIncomingBlock(i: 0);
2258 } else {
2259 return nullptr;
2260 }
2261 if (!match(V: Phi1->getIncomingValueForBlock(BB: ConstBB), P: m_ImmConstant(C&: C1)))
2262 return nullptr;
2263
2264 // The block that we are hoisting to must reach here unconditionally.
2265 // Otherwise, we could be speculatively executing an expensive or
2266 // non-speculative op.
2267 auto *PredBlockBranch = dyn_cast<UncondBrInst>(Val: OtherBB->getTerminator());
2268 if (!PredBlockBranch || !DT.isReachableFromEntry(A: OtherBB))
2269 return nullptr;
2270
2271 // TODO: This check could be tightened to only apply to binops (div/rem) that
2272 // are not safe to speculatively execute. But that could allow hoisting
2273 // potentially expensive instructions (fdiv for example).
2274 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
2275 if (!isGuaranteedToTransferExecutionToSuccessor(I: &*BBIter))
2276 return nullptr;
2277
2278 // Fold constants for the predecessor block with constant incoming values.
2279 Constant *NewC = ConstantFoldBinaryOpOperands(Opcode: BO.getOpcode(), LHS: C0, RHS: C1, DL);
2280 if (!NewC)
2281 return nullptr;
2282
2283 // Make a new binop in the predecessor block with the non-constant incoming
2284 // values.
2285 Builder.SetInsertPoint(PredBlockBranch);
2286 Value *NewBO = Builder.CreateBinOp(Opc: BO.getOpcode(),
2287 LHS: Phi0->getIncomingValueForBlock(BB: OtherBB),
2288 RHS: Phi1->getIncomingValueForBlock(BB: OtherBB));
2289 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(Val: NewBO))
2290 NotFoldedNewBO->copyIRFlags(V: &BO);
2291
2292 // Replace the binop with a phi of the new values. The old phis are dead.
2293 PHINode *NewPhi = PHINode::Create(Ty: BO.getType(), NumReservedValues: 2);
2294 NewPhi->addIncoming(V: NewBO, BB: OtherBB);
2295 NewPhi->addIncoming(V: NewC, BB: ConstBB);
2296 return NewPhi;
2297}
2298
2299Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
2300 auto TryFoldOperand = [&](unsigned OpIdx,
2301 bool IsOtherParamConst) -> Instruction * {
2302 if (auto *Sel = dyn_cast<SelectInst>(Val: I.getOperand(i_nocapture: OpIdx)))
2303 return FoldOpIntoSelect(Op&: I, SI: Sel, FoldWithMultiUse: false, SimplifyBothArms: !IsOtherParamConst);
2304 if (auto *PN = dyn_cast<PHINode>(Val: I.getOperand(i_nocapture: OpIdx)))
2305 return foldOpIntoPhi(I, PN);
2306 return nullptr;
2307 };
2308
2309 if (Instruction *NewI =
2310 TryFoldOperand(/*OpIdx=*/0, isa<Constant>(Val: I.getOperand(i_nocapture: 1))))
2311 return NewI;
2312 return TryFoldOperand(/*OpIdx=*/1, isa<Constant>(Val: I.getOperand(i_nocapture: 0)));
2313}
2314
2315static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
2316 // If this GEP has only 0 indices, it is the same pointer as
2317 // Src. If Src is not a trivial GEP too, don't combine
2318 // the indices.
2319 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
2320 !Src.hasOneUse())
2321 return false;
2322 return true;
2323}
2324
2325/// Find a constant NewC that has property:
2326/// shuffle(NewC, poison, ShMask) = C
2327/// for lanes that select NewC. Lanes that select the poison operand are not
2328/// constrained.
2329/// Returns nullptr if such a constant does not exist e.g. ShMask=<0,0> C=<1,2>
2330///
2331/// A 1-to-1 mapping is not required. Example:
2332/// ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <poison,5,6,poison>
2333Constant *InstCombinerImpl::unshuffleConstant(ArrayRef<int> ShMask, Constant *C,
2334 VectorType *NewCTy) {
2335 if (isa<ScalableVectorType>(Val: NewCTy)) {
2336 Constant *Splat = C->getSplatValue();
2337 if (!Splat)
2338 return nullptr;
2339 return ConstantVector::getSplat(EC: NewCTy->getElementCount(), Elt: Splat);
2340 }
2341
2342 if (cast<FixedVectorType>(Val: NewCTy)->getNumElements() >
2343 cast<FixedVectorType>(Val: C->getType())->getNumElements())
2344 return nullptr;
2345
2346 unsigned NewCNumElts = cast<FixedVectorType>(Val: NewCTy)->getNumElements();
2347 PoisonValue *PoisonScalar = PoisonValue::get(T: C->getType()->getScalarType());
2348 SmallVector<Constant *, 16> NewVecC(NewCNumElts, PoisonScalar);
2349 unsigned NumElts = cast<FixedVectorType>(Val: C->getType())->getNumElements();
2350 for (unsigned I = 0; I < NumElts; ++I) {
2351 Constant *CElt = C->getAggregateElement(Elt: I);
2352 if (ShMask[I] >= 0) {
2353 int MaskElt = ShMask[I];
2354 if (MaskElt >= (int)NewCNumElts)
2355 continue;
2356
2357 Constant *NewCElt = NewVecC[MaskElt];
2358 // Bail out if:
2359 // 1. The constant vector contains a constant expression.
2360 // 2. The shuffle needs an element of the constant vector that can't
2361 // be mapped to a new constant vector.
2362 // 3. This is a widening shuffle that copies elements of V1 into the
2363 // extended elements (extending with poison is allowed).
2364 if (!CElt || (!isa<PoisonValue>(Val: NewCElt) && NewCElt != CElt) ||
2365 I >= NewCNumElts)
2366 return nullptr;
2367 NewVecC[MaskElt] = CElt;
2368 }
2369 }
2370 return ConstantVector::get(V: NewVecC);
2371}
2372
2373// Get the result of `Vector Op Splat` (or Splat Op Vector if \p SplatLHS).
2374static Constant *constantFoldBinOpWithSplat(unsigned Opcode, Constant *Vector,
2375 Constant *Splat, bool SplatLHS,
2376 const DataLayout &DL) {
2377 ElementCount EC = cast<VectorType>(Val: Vector->getType())->getElementCount();
2378 Constant *LHS = ConstantVector::getSplat(EC, Elt: Splat);
2379 Constant *RHS = Vector;
2380 if (!SplatLHS)
2381 std::swap(a&: LHS, b&: RHS);
2382 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
2383}
2384
2385template <Intrinsic::ID SpliceID>
2386static Instruction *foldSpliceBinOp(BinaryOperator &Inst,
2387 InstCombiner::BuilderTy &Builder) {
2388 Value *LHS = Inst.getOperand(i_nocapture: 0), *RHS = Inst.getOperand(i_nocapture: 1);
2389 auto CreateBinOpSplice = [&](Value *X, Value *Y, Value *Offset) {
2390 Value *V = Builder.CreateBinOp(Opc: Inst.getOpcode(), LHS: X, RHS: Y, Name: Inst.getName());
2391 if (auto *BO = dyn_cast<BinaryOperator>(Val: V))
2392 BO->copyIRFlags(V: &Inst);
2393 Module *M = Inst.getModule();
2394 Function *F = Intrinsic::getOrInsertDeclaration(M, id: SpliceID, OverloadTys: V->getType());
2395 return CallInst::Create(Func: F, Args: {V, PoisonValue::get(T: V->getType()), Offset});
2396 };
2397 Value *V1, *V2, *Offset;
2398 if (match(LHS,
2399 m_Intrinsic<SpliceID>(m_Value(V&: V1), m_Poison(), m_Value(V&: Offset)))) {
2400 // Op(splice(V1, poison, offset), splice(V2, poison, offset))
2401 // -> splice(Op(V1, V2), poison, offset)
2402 if (match(RHS, m_Intrinsic<SpliceID>(m_Value(V&: V2), m_Poison(),
2403 m_Specific(V: Offset))) &&
2404 (LHS->hasOneUse() || RHS->hasOneUse() ||
2405 (LHS == RHS && LHS->hasNUses(N: 2))))
2406 return CreateBinOpSplice(V1, V2, Offset);
2407
2408 // Op(splice(V1, poison, offset), RHSSplat)
2409 // -> splice(Op(V1, RHSSplat), poison, offset)
2410 if (LHS->hasOneUse() && isSplatValue(V: RHS))
2411 return CreateBinOpSplice(V1, RHS, Offset);
2412 }
2413 // Op(LHSSplat, splice(V2, poison, offset))
2414 // -> splice(Op(LHSSplat, V2), poison, offset)
2415 else if (isSplatValue(V: LHS) &&
2416 match(RHS, m_OneUse(m_Intrinsic<SpliceID>(m_Value(V&: V2), m_Poison(),
2417 m_Value(V&: Offset)))))
2418 return CreateBinOpSplice(LHS, V2, Offset);
2419
2420 // TODO: Fold binops of the form
2421 // Op(splice(poison, V1, offset), splice(poison, V2, offset))
2422 // -> splice(poison, Op(V1, V2), offset)
2423
2424 return nullptr;
2425}
2426
2427Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) {
2428 if (!isa<VectorType>(Val: Inst.getType()))
2429 return nullptr;
2430
2431 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
2432 Value *LHS = Inst.getOperand(i_nocapture: 0), *RHS = Inst.getOperand(i_nocapture: 1);
2433 assert(cast<VectorType>(LHS->getType())->getElementCount() ==
2434 cast<VectorType>(Inst.getType())->getElementCount());
2435 assert(cast<VectorType>(RHS->getType())->getElementCount() ==
2436 cast<VectorType>(Inst.getType())->getElementCount());
2437
2438 auto foldConstantsThroughSubVectorInsertSplat =
2439 [&](Value *MaybeSubVector, Value *MaybeSplat,
2440 bool SplatLHS) -> Instruction * {
2441 Value *Idx;
2442 Constant *Splat, *SubVector, *Dest;
2443 if (!match(V: MaybeSplat, P: m_Splat(SubPattern: m_Constant(C&: Splat))) ||
2444 !match(V: MaybeSubVector,
2445 P: m_VectorInsert(Op0: m_Constant(C&: Dest), Op1: m_Constant(C&: SubVector),
2446 Op2: m_Value(V&: Idx))))
2447 return nullptr;
2448 SubVector =
2449 constantFoldBinOpWithSplat(Opcode, Vector: SubVector, Splat, SplatLHS, DL);
2450 Dest = constantFoldBinOpWithSplat(Opcode, Vector: Dest, Splat, SplatLHS, DL);
2451 if (!SubVector || !Dest)
2452 return nullptr;
2453 auto *InsertVector =
2454 Builder.CreateInsertVector(DstType: Dest->getType(), SrcVec: Dest, SubVec: SubVector, Idx);
2455 return replaceInstUsesWith(I&: Inst, V: InsertVector);
2456 };
2457
2458 // If one operand is a constant splat and the other operand is a
2459 // `vector.insert` where both the destination and subvector are constant,
2460 // apply the operation to both the destination and subvector, returning a new
2461 // constant `vector.insert`. This helps constant folding for scalable vectors.
2462 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2463 /*MaybeSubVector=*/LHS, /*MaybeSplat=*/RHS, /*SplatLHS=*/false))
2464 return Folded;
2465 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2466 /*MaybeSubVector=*/RHS, /*MaybeSplat=*/LHS, /*SplatLHS=*/true))
2467 return Folded;
2468
2469 auto createBinOpReverse = [&](Value *X, Value *Y) {
2470 Value *V = Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Y, Name: Inst.getName());
2471 if (auto *BO = dyn_cast<BinaryOperator>(Val: V))
2472 BO->copyIRFlags(V: &Inst);
2473 Module *M = Inst.getModule();
2474 Function *F = Intrinsic::getOrInsertDeclaration(
2475 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
2476 return CallInst::Create(Func: F, Args: V);
2477 };
2478
2479 // NOTE: Reverse shuffles don't require the speculative execution protection
2480 // below because they don't affect which lanes take part in the computation.
2481
2482 Value *V1, *V2;
2483 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
2484 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2485 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
2486 (LHS->hasOneUse() || RHS->hasOneUse() ||
2487 (LHS == RHS && LHS->hasNUses(N: 2))))
2488 return createBinOpReverse(V1, V2);
2489
2490 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2491 if (LHS->hasOneUse() && isSplatValue(V: RHS))
2492 return createBinOpReverse(V1, RHS);
2493 }
2494 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2495 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
2496 return createBinOpReverse(LHS, V2);
2497
2498 auto createBinOpVPReverse = [&](Value *X, Value *Y, Value *EVL) {
2499 Value *V = Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Y, Name: Inst.getName());
2500 if (auto *BO = dyn_cast<BinaryOperator>(Val: V))
2501 BO->copyIRFlags(V: &Inst);
2502
2503 ElementCount EC = cast<VectorType>(Val: V->getType())->getElementCount();
2504 Value *AllTrueMask = Builder.CreateVectorSplat(EC, V: Builder.getTrue());
2505 Module *M = Inst.getModule();
2506 Function *F = Intrinsic::getOrInsertDeclaration(
2507 M, id: Intrinsic::experimental_vp_reverse, OverloadTys: V->getType());
2508 return CallInst::Create(Func: F, Args: {V, AllTrueMask, EVL});
2509 };
2510
2511 Value *EVL;
2512 if (match(V: LHS, P: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
2513 Ops: m_Value(V&: V1), Ops: m_AllOnes(), Ops: m_Value(V&: EVL)))) {
2514 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2515 if (match(V: RHS, P: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
2516 Ops: m_Value(V&: V2), Ops: m_AllOnes(), Ops: m_Specific(V: EVL))) &&
2517 (LHS->hasOneUse() || RHS->hasOneUse() ||
2518 (LHS == RHS && LHS->hasNUses(N: 2))))
2519 return createBinOpVPReverse(V1, V2, EVL);
2520
2521 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2522 if (LHS->hasOneUse() && isSplatValue(V: RHS))
2523 return createBinOpVPReverse(V1, RHS, EVL);
2524 }
2525 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2526 else if (isSplatValue(V: LHS) &&
2527 match(V: RHS, P: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
2528 Ops: m_Value(V&: V2), Ops: m_AllOnes(), Ops: m_Value(V&: EVL))))
2529 return createBinOpVPReverse(LHS, V2, EVL);
2530
2531 if (Instruction *Folded =
2532 foldSpliceBinOp<Intrinsic::vector_splice_left>(Inst, Builder))
2533 return Folded;
2534 if (Instruction *Folded =
2535 foldSpliceBinOp<Intrinsic::vector_splice_right>(Inst, Builder))
2536 return Folded;
2537
2538 // It may not be safe to reorder shuffles and things like div, urem, etc.
2539 // because we may trap when executing those ops on unknown vector elements.
2540 // See PR20059.
2541 if (!isSafeToSpeculativelyExecuteWithVariableReplaced(I: &Inst))
2542 return nullptr;
2543
2544 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
2545 Value *XY = Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Y);
2546 if (auto *BO = dyn_cast<BinaryOperator>(Val: XY))
2547 BO->copyIRFlags(V: &Inst);
2548 return new ShuffleVectorInst(XY, M);
2549 };
2550
2551 // If both arguments of the binary operation are shuffles that use the same
2552 // mask and shuffle within a single vector, move the shuffle after the binop.
2553 ArrayRef<int> Mask;
2554 if (match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Poison(), mask: m_Mask(Mask))) &&
2555 match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Poison(), mask: m_SpecificMask(Mask))) &&
2556 Inst.getType() == V1->getType() && V1->getType() == V2->getType() &&
2557 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
2558 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
2559 return createBinOpShuffle(V1, V2, Mask);
2560 }
2561
2562 // If both arguments of a commutative binop are select-shuffles that use the
2563 // same mask with commuted operands, the shuffles are unnecessary.
2564 if (Inst.isCommutative() &&
2565 match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Value(V&: V2), mask: m_Mask(Mask))) &&
2566 match(V: RHS,
2567 P: m_Shuffle(v1: m_Specific(V: V2), v2: m_Specific(V: V1), mask: m_SpecificMask(Mask)))) {
2568 auto *LShuf = cast<ShuffleVectorInst>(Val: LHS);
2569 auto *RShuf = cast<ShuffleVectorInst>(Val: RHS);
2570 // TODO: Allow shuffles that contain undefs in the mask?
2571 // That is legal, but it reduces undef knowledge.
2572 // TODO: Allow arbitrary shuffles by shuffling after binop?
2573 // That might be legal, but we have to deal with poison.
2574 if (LShuf->isSelect() &&
2575 !is_contained(Range: LShuf->getShuffleMask(), Element: PoisonMaskElem) &&
2576 RShuf->isSelect() &&
2577 !is_contained(Range: RShuf->getShuffleMask(), Element: PoisonMaskElem)) {
2578 // Example:
2579 // LHS = shuffle V1, V2, <0, 5, 6, 3>
2580 // RHS = shuffle V2, V1, <0, 5, 6, 3>
2581 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
2582 Instruction *NewBO = BinaryOperator::Create(Op: Opcode, S1: V1, S2: V2);
2583 NewBO->copyIRFlags(V: &Inst);
2584 return NewBO;
2585 }
2586 }
2587
2588 // If one argument is a shuffle within one vector and the other is a constant,
2589 // try moving the shuffle after the binary operation. This canonicalization
2590 // intends to move shuffles closer to other shuffles and binops closer to
2591 // other binops, so they can be folded. It may also enable demanded elements
2592 // transforms.
2593 Constant *C;
2594 if (match(V: &Inst, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: V1), v2: m_Poison(),
2595 mask: m_Mask(Mask))),
2596 R: m_ImmConstant(C)))) {
2597 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
2598 "Shuffle should not change scalar type");
2599
2600 bool ConstOp1 = isa<Constant>(Val: RHS);
2601 if (Constant *NewC =
2602 unshuffleConstant(ShMask: Mask, C, NewCTy: cast<VectorType>(Val: V1->getType()))) {
2603 // For fixed vectors, lanes of NewC not used by the shuffle will be poison
2604 // which will cause UB for div/rem. Mask them with a safe constant.
2605 if (isa<FixedVectorType>(Val: V1->getType()) && Inst.isIntDivRem())
2606 NewC = getSafeVectorConstantForBinop(Opcode, In: NewC, IsRHSConstant: ConstOp1);
2607
2608 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
2609 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
2610 Value *NewLHS = ConstOp1 ? V1 : NewC;
2611 Value *NewRHS = ConstOp1 ? NewC : V1;
2612 return createBinOpShuffle(NewLHS, NewRHS, Mask);
2613 }
2614 }
2615
2616 // Try to reassociate to sink a splat shuffle after a binary operation.
2617 if (Inst.isAssociative() && Inst.isCommutative()) {
2618 // Canonicalize shuffle operand as LHS.
2619 if (isa<ShuffleVectorInst>(Val: RHS))
2620 std::swap(a&: LHS, b&: RHS);
2621
2622 Value *X;
2623 ArrayRef<int> MaskC;
2624 int SplatIndex;
2625 Value *Y, *OtherOp;
2626 if (!match(V: LHS,
2627 P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: X), v2: m_Undef(), mask: m_Mask(MaskC)))) ||
2628 !match(Mask: MaskC, P: m_SplatOrPoisonMask(SplatIndex)) ||
2629 X->getType() != Inst.getType() ||
2630 !match(V: RHS, P: m_OneUse(SubPattern: m_BinOp(Opcode, L: m_Value(V&: Y), R: m_Value(V&: OtherOp)))))
2631 return nullptr;
2632
2633 // FIXME: This may not be safe if the analysis allows undef elements. By
2634 // moving 'Y' before the splat shuffle, we are implicitly assuming
2635 // that it is not undef/poison at the splat index.
2636 if (isSplatValue(V: OtherOp, Index: SplatIndex)) {
2637 std::swap(a&: Y, b&: OtherOp);
2638 } else if (!isSplatValue(V: Y, Index: SplatIndex)) {
2639 return nullptr;
2640 }
2641
2642 // X and Y are splatted values, so perform the binary operation on those
2643 // values followed by a splat followed by the 2nd binary operation:
2644 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
2645 Value *NewBO = Builder.CreateBinOp(Opc: Opcode, LHS: X, RHS: Y);
2646 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
2647 Value *NewSplat = Builder.CreateShuffleVector(V: NewBO, Mask: NewMask);
2648 Instruction *R = BinaryOperator::Create(Op: Opcode, S1: NewSplat, S2: OtherOp);
2649
2650 // Intersect FMF on both new binops. Other (poison-generating) flags are
2651 // dropped to be safe.
2652 if (isa<FPMathOperator>(Val: R)) {
2653 R->copyFastMathFlags(I: &Inst);
2654 R->andIRFlags(V: RHS);
2655 }
2656 if (auto *NewInstBO = dyn_cast<BinaryOperator>(Val: NewBO))
2657 NewInstBO->copyIRFlags(V: R);
2658 return R;
2659 }
2660
2661 return nullptr;
2662}
2663
2664/// Try to narrow the width of a binop if at least 1 operand is an extend of
2665/// of a value. This requires a potentially expensive known bits check to make
2666/// sure the narrow op does not overflow.
2667Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
2668 // We need at least one extended operand.
2669 Value *Op0 = BO.getOperand(i_nocapture: 0), *Op1 = BO.getOperand(i_nocapture: 1);
2670
2671 // If this is a sub, we swap the operands since we always want an extension
2672 // on the RHS. The LHS can be an extension or a constant.
2673 if (BO.getOpcode() == Instruction::Sub)
2674 std::swap(a&: Op0, b&: Op1);
2675
2676 Value *X;
2677 bool IsSext = match(V: Op0, P: m_SExt(Op: m_Value(V&: X)));
2678 if (!IsSext && !match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))))
2679 return nullptr;
2680
2681 // If both operands are the same extension from the same source type and we
2682 // can eliminate at least one (hasOneUse), this might work.
2683 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
2684 Value *Y;
2685 if (!(match(V: Op1, P: m_ZExtOrSExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType() &&
2686 cast<Operator>(Val: Op1)->getOpcode() == CastOpc &&
2687 (Op0->hasOneUse() || Op1->hasOneUse()))) {
2688 // If that did not match, see if we have a suitable constant operand.
2689 // Truncating and extending must produce the same constant.
2690 Constant *WideC;
2691 if (!Op0->hasOneUse() || !match(V: Op1, P: m_Constant(C&: WideC)))
2692 return nullptr;
2693 Constant *NarrowC = getLosslessInvCast(C: WideC, InvCastTo: X->getType(), CastOp: CastOpc, DL);
2694 if (!NarrowC)
2695 return nullptr;
2696 Y = NarrowC;
2697 }
2698
2699 // Swap back now that we found our operands.
2700 if (BO.getOpcode() == Instruction::Sub)
2701 std::swap(a&: X, b&: Y);
2702
2703 // Both operands have narrow versions. Last step: the math must not overflow
2704 // in the narrow width.
2705 if (!willNotOverflow(Opcode: BO.getOpcode(), LHS: X, RHS: Y, CtxI: BO, IsSigned: IsSext))
2706 return nullptr;
2707
2708 // bo (ext X), (ext Y) --> ext (bo X, Y)
2709 // bo (ext X), C --> ext (bo X, C')
2710 Value *NarrowBO = Builder.CreateBinOp(Opc: BO.getOpcode(), LHS: X, RHS: Y, Name: "narrow");
2711 if (auto *NewBinOp = dyn_cast<BinaryOperator>(Val: NarrowBO)) {
2712 if (IsSext)
2713 NewBinOp->setHasNoSignedWrap();
2714 else
2715 NewBinOp->setHasNoUnsignedWrap();
2716 }
2717 return CastInst::Create(CastOpc, S: NarrowBO, Ty: BO.getType());
2718}
2719
2720/// Determine nowrap flags for (gep (gep p, x), y) to (gep p, (x + y))
2721/// transform.
2722static GEPNoWrapFlags getMergedGEPNoWrapFlags(GEPOperator &GEP1,
2723 GEPOperator &GEP2) {
2724 return GEP1.getNoWrapFlags().intersectForOffsetAdd(Other: GEP2.getNoWrapFlags());
2725}
2726
2727/// Thread a GEP operation with constant indices through the constant true/false
2728/// arms of a select.
2729static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
2730 InstCombiner::BuilderTy &Builder) {
2731 if (!GEP.hasAllConstantIndices())
2732 return nullptr;
2733
2734 Instruction *Sel;
2735 Value *Cond;
2736 Constant *TrueC, *FalseC;
2737 if (!match(V: GEP.getPointerOperand(), P: m_Instruction(I&: Sel)) ||
2738 !match(V: Sel,
2739 P: m_Select(C: m_Value(V&: Cond), L: m_Constant(C&: TrueC), R: m_Constant(C&: FalseC))))
2740 return nullptr;
2741
2742 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
2743 // Propagate 'inbounds' and metadata from existing instructions.
2744 // Note: using IRBuilder to create the constants for efficiency.
2745 SmallVector<Value *, 4> IndexC(GEP.indices());
2746 GEPNoWrapFlags NW = GEP.getNoWrapFlags();
2747 Type *Ty = GEP.getSourceElementType();
2748 Value *NewTrueC = Builder.CreateGEP(Ty, Ptr: TrueC, IdxList: IndexC, Name: "", NW);
2749 Value *NewFalseC = Builder.CreateGEP(Ty, Ptr: FalseC, IdxList: IndexC, Name: "", NW);
2750 return SelectInst::Create(C: Cond, S1: NewTrueC, S2: NewFalseC, NameStr: "", InsertBefore: nullptr, MDFrom: Sel);
2751}
2752
2753// Canonicalization:
2754// gep T, (gep i8, base, C1), (Index + C2) into
2755// gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index
2756static Instruction *canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP,
2757 GEPOperator *Src,
2758 InstCombinerImpl &IC) {
2759 if (GEP.getNumIndices() != 1)
2760 return nullptr;
2761 auto &DL = IC.getDataLayout();
2762 Value *Base;
2763 const APInt *C1;
2764 if (!match(V: Src, P: m_PtrAdd(PointerOp: m_Value(V&: Base), OffsetOp: m_APInt(Res&: C1))))
2765 return nullptr;
2766 Value *VarIndex;
2767 const APInt *C2;
2768 Type *PtrTy = Src->getType()->getScalarType();
2769 unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(Ty: PtrTy);
2770 if (!match(V: GEP.getOperand(i_nocapture: 1), P: m_AddLike(L: m_Value(V&: VarIndex), R: m_APInt(Res&: C2))))
2771 return nullptr;
2772 if (C1->getBitWidth() != IndexSizeInBits ||
2773 C2->getBitWidth() != IndexSizeInBits)
2774 return nullptr;
2775 Type *BaseType = GEP.getSourceElementType();
2776 if (isa<ScalableVectorType>(Val: BaseType))
2777 return nullptr;
2778 APInt TypeSize(IndexSizeInBits, DL.getTypeAllocSize(Ty: BaseType));
2779 APInt NewOffset = TypeSize * *C2 + *C1;
2780 if (NewOffset.isZero() ||
2781 (Src->hasOneUse() && GEP.getOperand(i_nocapture: 1)->hasOneUse())) {
2782 GEPNoWrapFlags Flags = GEPNoWrapFlags::none();
2783 if (GEP.hasNoUnsignedWrap() &&
2784 cast<GEPOperator>(Val: Src)->hasNoUnsignedWrap() &&
2785 match(V: GEP.getOperand(i_nocapture: 1), P: m_NUWAddLike(L: m_Value(), R: m_Value()))) {
2786 Flags |= GEPNoWrapFlags::noUnsignedWrap();
2787 if (GEP.isInBounds() && cast<GEPOperator>(Val: Src)->isInBounds())
2788 Flags |= GEPNoWrapFlags::inBounds();
2789 }
2790
2791 Value *GEPConst =
2792 IC.Builder.CreatePtrAdd(Ptr: Base, Offset: IC.Builder.getInt(AI: NewOffset), Name: "", NW: Flags);
2793 return GetElementPtrInst::Create(PointeeType: BaseType, Ptr: GEPConst, IdxList: VarIndex, NW: Flags);
2794 }
2795
2796 return nullptr;
2797}
2798
2799/// Combine constant offsets separated by variable offsets.
2800/// ptradd (ptradd (ptradd p, C1), x), C2 -> ptradd (ptradd p, x), C1+C2
2801static Instruction *combineConstantOffsets(GetElementPtrInst &GEP,
2802 InstCombinerImpl &IC) {
2803 if (!GEP.hasAllConstantIndices())
2804 return nullptr;
2805
2806 GEPNoWrapFlags NW = GEPNoWrapFlags::all();
2807 SmallVector<GetElementPtrInst *> Skipped;
2808 auto *InnerGEP = dyn_cast<GetElementPtrInst>(Val: GEP.getPointerOperand());
2809 while (true) {
2810 if (!InnerGEP)
2811 return nullptr;
2812
2813 NW = NW.intersectForReassociate(Other: InnerGEP->getNoWrapFlags());
2814 if (InnerGEP->hasAllConstantIndices())
2815 break;
2816
2817 if (!InnerGEP->hasOneUse())
2818 return nullptr;
2819
2820 Skipped.push_back(Elt: InnerGEP);
2821 InnerGEP = dyn_cast<GetElementPtrInst>(Val: InnerGEP->getPointerOperand());
2822 }
2823
2824 // The two constant offset GEPs are directly adjacent: Let normal offset
2825 // merging handle it.
2826 if (Skipped.empty())
2827 return nullptr;
2828
2829 // FIXME: This one-use check is not strictly necessary. Consider relaxing it
2830 // if profitable.
2831 if (!InnerGEP->hasOneUse())
2832 return nullptr;
2833
2834 // Don't bother with vector splats.
2835 Type *Ty = GEP.getType();
2836 if (InnerGEP->getType() != Ty)
2837 return nullptr;
2838
2839 const DataLayout &DL = IC.getDataLayout();
2840 APInt Offset(DL.getIndexTypeSizeInBits(Ty), 0);
2841 if (!GEP.accumulateConstantOffset(DL, Offset) ||
2842 !InnerGEP->accumulateConstantOffset(DL, Offset))
2843 return nullptr;
2844
2845 IC.replaceOperand(I&: *Skipped.back(), OpNum: 0, V: InnerGEP->getPointerOperand());
2846 for (GetElementPtrInst *SkippedGEP : Skipped)
2847 SkippedGEP->setNoWrapFlags(NW);
2848
2849 return IC.replaceInstUsesWith(
2850 I&: GEP,
2851 V: IC.Builder.CreatePtrAdd(Ptr: Skipped.front(), Offset: IC.Builder.getInt(AI: Offset), Name: "",
2852 NW: NW.intersectForOffsetAdd(Other: GEP.getNoWrapFlags())));
2853}
2854
2855Instruction *InstCombinerImpl::visitGEPOfGEP(GetElementPtrInst &GEP,
2856 GEPOperator *Src) {
2857 // Combine Indices - If the source pointer to this getelementptr instruction
2858 // is a getelementptr instruction with matching element type, combine the
2859 // indices of the two getelementptr instructions into a single instruction.
2860 if (!shouldMergeGEPs(GEP&: *cast<GEPOperator>(Val: &GEP), Src&: *Src))
2861 return nullptr;
2862
2863 if (auto *I = canonicalizeGEPOfConstGEPI8(GEP, Src, IC&: *this))
2864 return I;
2865
2866 if (auto *I = combineConstantOffsets(GEP, IC&: *this))
2867 return I;
2868
2869 if (Src->getResultElementType() != GEP.getSourceElementType())
2870 return nullptr;
2871
2872 // Fold chained GEP with constant base into single GEP:
2873 // gep i8, (gep i8, %base, C1), (select Cond, C2, C3)
2874 // -> gep i8, %base, (select Cond, C1+C2, C1+C3)
2875 if (Src->hasOneUse() && GEP.getNumIndices() == 1 &&
2876 Src->getNumIndices() == 1) {
2877 Value *SrcIdx = *Src->idx_begin();
2878 Value *GEPIdx = *GEP.idx_begin();
2879 const APInt *ConstOffset, *TrueVal, *FalseVal;
2880 Value *Cond;
2881
2882 if ((match(V: SrcIdx, P: m_APInt(Res&: ConstOffset)) &&
2883 match(V: GEPIdx,
2884 P: m_Select(C: m_Value(V&: Cond), L: m_APInt(Res&: TrueVal), R: m_APInt(Res&: FalseVal)))) ||
2885 (match(V: GEPIdx, P: m_APInt(Res&: ConstOffset)) &&
2886 match(V: SrcIdx,
2887 P: m_Select(C: m_Value(V&: Cond), L: m_APInt(Res&: TrueVal), R: m_APInt(Res&: FalseVal))))) {
2888 auto *Select = isa<SelectInst>(Val: GEPIdx) ? cast<SelectInst>(Val: GEPIdx)
2889 : cast<SelectInst>(Val: SrcIdx);
2890
2891 // Make sure the select has only one use.
2892 if (!Select->hasOneUse())
2893 return nullptr;
2894
2895 if (TrueVal->getBitWidth() != ConstOffset->getBitWidth() ||
2896 FalseVal->getBitWidth() != ConstOffset->getBitWidth())
2897 return nullptr;
2898
2899 APInt NewTrueVal = *ConstOffset + *TrueVal;
2900 APInt NewFalseVal = *ConstOffset + *FalseVal;
2901 Constant *NewTrue = ConstantInt::get(Ty: Select->getType(), V: NewTrueVal);
2902 Constant *NewFalse = ConstantInt::get(Ty: Select->getType(), V: NewFalseVal);
2903 Value *NewSelect =
2904 Builder.CreateSelect(C: Cond, True: NewTrue, False: NewFalse, /*Name=*/"",
2905 /*MDFrom=*/Select);
2906 GEPNoWrapFlags Flags =
2907 getMergedGEPNoWrapFlags(GEP1&: *Src, GEP2&: *cast<GEPOperator>(Val: &GEP));
2908 return replaceInstUsesWith(I&: GEP,
2909 V: Builder.CreateGEP(Ty: GEP.getResultElementType(),
2910 Ptr: Src->getPointerOperand(),
2911 IdxList: NewSelect, Name: "", NW: Flags));
2912 }
2913 }
2914
2915 // Find out whether the last index in the source GEP is a sequential idx.
2916 bool EndsWithSequential = false;
2917 for (gep_type_iterator I = gep_type_begin(GEP: *Src), E = gep_type_end(GEP: *Src);
2918 I != E; ++I)
2919 EndsWithSequential = I.isSequential();
2920 if (!EndsWithSequential)
2921 return nullptr;
2922
2923 // Replace: gep (gep %P, long B), long A, ...
2924 // With: T = long A+B; gep %P, T, ...
2925 Value *SO1 = Src->getOperand(i_nocapture: Src->getNumOperands() - 1);
2926 Value *GO1 = GEP.getOperand(i_nocapture: 1);
2927
2928 // If they aren't the same type, then the input hasn't been processed
2929 // by the loop above yet (which canonicalizes sequential index types to
2930 // intptr_t). Just avoid transforming this until the input has been
2931 // normalized.
2932 if (SO1->getType() != GO1->getType())
2933 return nullptr;
2934
2935 Value *Sum =
2936 simplifyAddInst(LHS: GO1, RHS: SO1, IsNSW: false, IsNUW: false, Q: SQ.getWithInstruction(I: &GEP));
2937 // Only do the combine when we are sure the cost after the
2938 // merge is never more than that before the merge.
2939 if (Sum == nullptr)
2940 return nullptr;
2941
2942 SmallVector<Value *, 8> Indices;
2943 Indices.append(in_start: Src->op_begin() + 1, in_end: Src->op_end() - 1);
2944 Indices.push_back(Elt: Sum);
2945 Indices.append(in_start: GEP.op_begin() + 2, in_end: GEP.op_end());
2946
2947 // Don't create GEPs with more than one non-zero index.
2948 unsigned NumNonZeroIndices = count_if(Range&: Indices, P: [](Value *Idx) {
2949 auto *C = dyn_cast<Constant>(Val: Idx);
2950 return !C || !C->isNullValue();
2951 });
2952 if (NumNonZeroIndices > 1)
2953 return nullptr;
2954
2955 return replaceInstUsesWith(
2956 I&: GEP, V: Builder.CreateGEP(
2957 Ty: Src->getSourceElementType(), Ptr: Src->getOperand(i_nocapture: 0), IdxList: Indices, Name: "",
2958 NW: getMergedGEPNoWrapFlags(GEP1&: *Src, GEP2&: *cast<GEPOperator>(Val: &GEP))));
2959}
2960
2961Value *InstCombiner::getFreelyInvertedImpl(Value *V, bool WillInvertAllUses,
2962 BuilderTy *Builder,
2963 bool &DoesConsume, unsigned Depth) {
2964 static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));
2965 // ~(~(X)) -> X.
2966 Value *A, *B;
2967 if (match(V, P: m_Not(V: m_Value(V&: A)))) {
2968 DoesConsume = true;
2969 return A;
2970 }
2971
2972 Constant *C;
2973 // Constants can be considered to be not'ed values.
2974 if (match(V, P: m_ImmConstant(C)))
2975 return ConstantExpr::getNot(C);
2976
2977 if (Depth++ >= MaxAnalysisRecursionDepth)
2978 return nullptr;
2979
2980 // The rest of the cases require that we invert all uses so don't bother
2981 // doing the analysis if we know we can't use the result.
2982 if (!WillInvertAllUses)
2983 return nullptr;
2984
2985 // Compares can be inverted if all of their uses are being modified to use
2986 // the ~V.
2987 if (auto *I = dyn_cast<CmpInst>(Val: V)) {
2988 if (Builder != nullptr)
2989 return Builder->CreateCmp(Pred: I->getInversePredicate(), LHS: I->getOperand(i_nocapture: 0),
2990 RHS: I->getOperand(i_nocapture: 1));
2991 return NonNull;
2992 }
2993
2994 // If `V` is of the form `A + B` then `-1 - V` can be folded into
2995 // `(-1 - B) - A` if we are willing to invert all of the uses.
2996 if (match(V, P: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)))) {
2997 if (auto *BV = getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), Builder,
2998 DoesConsume, Depth))
2999 return Builder ? Builder->CreateSub(LHS: BV, RHS: A) : NonNull;
3000 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3001 DoesConsume, Depth))
3002 return Builder ? Builder->CreateSub(LHS: AV, RHS: B) : NonNull;
3003 return nullptr;
3004 }
3005
3006 // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded
3007 // into `A ^ B` if we are willing to invert all of the uses.
3008 if (match(V, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3009 if (auto *BV = getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), Builder,
3010 DoesConsume, Depth))
3011 return Builder ? Builder->CreateXor(LHS: A, RHS: BV) : NonNull;
3012 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3013 DoesConsume, Depth))
3014 return Builder ? Builder->CreateXor(LHS: AV, RHS: B) : NonNull;
3015 return nullptr;
3016 }
3017
3018 // If `V` is of the form `B - A` then `-1 - V` can be folded into
3019 // `A + (-1 - B)` if we are willing to invert all of the uses.
3020 if (match(V, P: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3021 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3022 DoesConsume, Depth))
3023 return Builder ? Builder->CreateAdd(LHS: AV, RHS: B) : NonNull;
3024 return nullptr;
3025 }
3026
3027 // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded
3028 // into `A s>> B` if we are willing to invert all of the uses.
3029 if (match(V, P: m_AShr(L: m_Value(V&: A), R: m_Value(V&: B)))) {
3030 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3031 DoesConsume, Depth))
3032 return Builder ? Builder->CreateAShr(LHS: AV, RHS: B) : NonNull;
3033 return nullptr;
3034 }
3035
3036 Value *Cond;
3037 // LogicOps are special in that we canonicalize them at the cost of an
3038 // instruction.
3039 bool IsSelect = match(V, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
3040 !shouldAvoidAbsorbingNotIntoSelect(SI: *cast<SelectInst>(Val: V));
3041 // Selects/min/max with invertible operands are freely invertible
3042 if (IsSelect || match(V, P: m_MaxOrMin(Op0: m_Value(V&: A), Op1: m_Value(V&: B)))) {
3043 bool LocalDoesConsume = DoesConsume;
3044 if (!getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), /*Builder*/ nullptr,
3045 DoesConsume&: LocalDoesConsume, Depth))
3046 return nullptr;
3047 if (Value *NotA = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3048 DoesConsume&: LocalDoesConsume, Depth)) {
3049 DoesConsume = LocalDoesConsume;
3050 if (Builder != nullptr) {
3051 Value *NotB = getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), Builder,
3052 DoesConsume, Depth);
3053 assert(NotB != nullptr &&
3054 "Unable to build inverted value for known freely invertable op");
3055 if (auto *II = dyn_cast<IntrinsicInst>(Val: V))
3056 return Builder->CreateBinaryIntrinsic(
3057 ID: getInverseMinMaxIntrinsic(MinMaxID: II->getIntrinsicID()), LHS: NotA, RHS: NotB);
3058 return Builder->CreateSelect(C: Cond, True: NotA, False: NotB, Name: "",
3059 MDFrom: cast<Instruction>(Val: V));
3060 }
3061 return NonNull;
3062 }
3063 }
3064
3065 if (PHINode *PN = dyn_cast<PHINode>(Val: V)) {
3066 bool LocalDoesConsume = DoesConsume;
3067 SmallVector<std::pair<Value *, BasicBlock *>, 8> IncomingValues;
3068 for (Use &U : PN->operands()) {
3069 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3070 Value *NewIncomingVal = getFreelyInvertedImpl(
3071 V: U.get(), /*WillInvertAllUses=*/false,
3072 /*Builder=*/nullptr, DoesConsume&: LocalDoesConsume, Depth: MaxAnalysisRecursionDepth - 1);
3073 if (NewIncomingVal == nullptr)
3074 return nullptr;
3075 // Make sure that we can safely erase the original PHI node.
3076 if (NewIncomingVal == V)
3077 return nullptr;
3078 if (Builder != nullptr)
3079 IncomingValues.emplace_back(Args&: NewIncomingVal, Args&: IncomingBlock);
3080 }
3081
3082 DoesConsume = LocalDoesConsume;
3083 if (Builder != nullptr) {
3084 IRBuilderBase::InsertPointGuard Guard(*Builder);
3085 Builder->SetInsertPoint(PN);
3086 PHINode *NewPN =
3087 Builder->CreatePHI(Ty: PN->getType(), NumReservedValues: PN->getNumIncomingValues());
3088 for (auto [Val, Pred] : IncomingValues)
3089 NewPN->addIncoming(V: Val, BB: Pred);
3090 return NewPN;
3091 }
3092 return NonNull;
3093 }
3094
3095 if (match(V, P: m_SExtLike(Op: m_Value(V&: A)))) {
3096 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3097 DoesConsume, Depth))
3098 return Builder ? Builder->CreateSExt(V: AV, DestTy: V->getType()) : NonNull;
3099 return nullptr;
3100 }
3101
3102 if (match(V, P: m_Trunc(Op: m_Value(V&: A)))) {
3103 if (auto *AV = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3104 DoesConsume, Depth))
3105 return Builder ? Builder->CreateTrunc(V: AV, DestTy: V->getType()) : NonNull;
3106 return nullptr;
3107 }
3108
3109 // De Morgan's Laws:
3110 // (~(A | B)) -> (~A & ~B)
3111 // (~(A & B)) -> (~A | ~B)
3112 auto TryInvertAndOrUsingDeMorgan = [&](Instruction::BinaryOps Opcode,
3113 bool IsLogical, Value *A,
3114 Value *B) -> Value * {
3115 bool LocalDoesConsume = DoesConsume;
3116 if (!getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), /*Builder=*/nullptr,
3117 DoesConsume&: LocalDoesConsume, Depth))
3118 return nullptr;
3119 if (auto *NotA = getFreelyInvertedImpl(V: A, WillInvertAllUses: A->hasOneUse(), Builder,
3120 DoesConsume&: LocalDoesConsume, Depth)) {
3121 auto *NotB = getFreelyInvertedImpl(V: B, WillInvertAllUses: B->hasOneUse(), Builder,
3122 DoesConsume&: LocalDoesConsume, Depth);
3123 DoesConsume = LocalDoesConsume;
3124 if (IsLogical)
3125 return Builder ? Builder->CreateLogicalOp(Opc: Opcode, Cond1: NotA, Cond2: NotB) : NonNull;
3126 return Builder ? Builder->CreateBinOp(Opc: Opcode, LHS: NotA, RHS: NotB) : NonNull;
3127 }
3128
3129 return nullptr;
3130 };
3131
3132 if (match(V, P: m_Or(L: m_Value(V&: A), R: m_Value(V&: B))))
3133 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/false, A,
3134 B);
3135
3136 if (match(V, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))))
3137 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/false, A,
3138 B);
3139
3140 if (match(V, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))))
3141 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/true, A,
3142 B);
3143
3144 if (match(V, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))))
3145 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/true, A,
3146 B);
3147
3148 return nullptr;
3149}
3150
3151/// Return true if we should canonicalize the gep to an i8 ptradd.
3152static bool shouldCanonicalizeGEPToPtrAdd(GetElementPtrInst &GEP) {
3153 Value *PtrOp = GEP.getOperand(i_nocapture: 0);
3154 Type *GEPEltType = GEP.getSourceElementType();
3155 if (GEPEltType->isIntegerTy(BitWidth: 8))
3156 return false;
3157
3158 // Canonicalize scalable GEPs to an explicit offset using the llvm.vscale
3159 // intrinsic. This has better support in BasicAA.
3160 if (GEPEltType->isScalableTy())
3161 return true;
3162
3163 // gep i32 p, mul(O, C) -> gep i8, p, mul(O, C*4) to fold the two multiplies
3164 // together.
3165 if (GEP.getNumIndices() == 1 &&
3166 match(V: GEP.getOperand(i_nocapture: 1),
3167 P: m_OneUse(SubPattern: m_CombineOr(Ps: m_Mul(L: m_Value(), R: m_ConstantInt()),
3168 Ps: m_Shl(L: m_Value(), R: m_ConstantInt())))))
3169 return true;
3170
3171 // gep (gep %p, C1), %x, C2 is expanded so the two constants can
3172 // possibly be merged together.
3173 auto PtrOpGep = dyn_cast<GEPOperator>(Val: PtrOp);
3174 return PtrOpGep && PtrOpGep->hasAllConstantIndices() &&
3175 any_of(Range: GEP.indices(), P: [](Value *V) {
3176 const APInt *C;
3177 return match(V, P: m_APInt(Res&: C)) && !C->isZero();
3178 });
3179}
3180
3181static Instruction *foldGEPOfPhi(GetElementPtrInst &GEP, PHINode *PN,
3182 IRBuilderBase &Builder) {
3183 auto *Op1 = dyn_cast<GetElementPtrInst>(Val: PN->getOperand(i_nocapture: 0));
3184 if (!Op1)
3185 return nullptr;
3186
3187 // Don't fold a GEP into itself through a PHI node. This can only happen
3188 // through the back-edge of a loop. Folding a GEP into itself means that
3189 // the value of the previous iteration needs to be stored in the meantime,
3190 // thus requiring an additional register variable to be live, but not
3191 // actually achieving anything (the GEP still needs to be executed once per
3192 // loop iteration).
3193 if (Op1 == &GEP)
3194 return nullptr;
3195 GEPNoWrapFlags NW = Op1->getNoWrapFlags();
3196
3197 int DI = -1;
3198
3199 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
3200 auto *Op2 = dyn_cast<GetElementPtrInst>(Val&: *I);
3201 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
3202 Op1->getSourceElementType() != Op2->getSourceElementType())
3203 return nullptr;
3204
3205 // As for Op1 above, don't try to fold a GEP into itself.
3206 if (Op2 == &GEP)
3207 return nullptr;
3208
3209 // Keep track of the type as we walk the GEP.
3210 Type *CurTy = nullptr;
3211
3212 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
3213 if (Op1->getOperand(i_nocapture: J)->getType() != Op2->getOperand(i_nocapture: J)->getType())
3214 return nullptr;
3215
3216 if (Op1->getOperand(i_nocapture: J) != Op2->getOperand(i_nocapture: J)) {
3217 if (DI == -1) {
3218 // We have not seen any differences yet in the GEPs feeding the
3219 // PHI yet, so we record this one if it is allowed to be a
3220 // variable.
3221
3222 // The first two arguments can vary for any GEP, the rest have to be
3223 // static for struct slots
3224 if (J > 1) {
3225 assert(CurTy && "No current type?");
3226 if (CurTy->isStructTy())
3227 return nullptr;
3228 }
3229
3230 DI = J;
3231 } else {
3232 // The GEP is different by more than one input. While this could be
3233 // extended to support GEPs that vary by more than one variable it
3234 // doesn't make sense since it greatly increases the complexity and
3235 // would result in an R+R+R addressing mode which no backend
3236 // directly supports and would need to be broken into several
3237 // simpler instructions anyway.
3238 return nullptr;
3239 }
3240 }
3241
3242 // Sink down a layer of the type for the next iteration.
3243 if (J > 0) {
3244 if (J == 1) {
3245 CurTy = Op1->getSourceElementType();
3246 } else {
3247 CurTy =
3248 GetElementPtrInst::getTypeAtIndex(Ty: CurTy, Idx: Op1->getOperand(i_nocapture: J));
3249 }
3250 }
3251 }
3252
3253 NW &= Op2->getNoWrapFlags();
3254 }
3255
3256 // If not all GEPs are identical we'll have to create a new PHI node.
3257 // Check that the old PHI node has only one use so that it will get
3258 // removed.
3259 if (DI != -1 && !PN->hasOneUse())
3260 return nullptr;
3261
3262 auto *NewGEP = cast<GetElementPtrInst>(Val: Op1->clone());
3263 NewGEP->setNoWrapFlags(NW);
3264
3265 if (DI == -1) {
3266 // All the GEPs feeding the PHI are identical. Clone one down into our
3267 // BB so that it can be merged with the current GEP.
3268 } else {
3269 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
3270 // into the current block so it can be merged, and create a new PHI to
3271 // set that index.
3272 PHINode *NewPN;
3273 {
3274 IRBuilderBase::InsertPointGuard Guard(Builder);
3275 Builder.SetInsertPoint(PN);
3276 NewPN = Builder.CreatePHI(Ty: Op1->getOperand(i_nocapture: DI)->getType(),
3277 NumReservedValues: PN->getNumOperands());
3278 }
3279
3280 for (auto &I : PN->operands())
3281 NewPN->addIncoming(V: cast<GEPOperator>(Val&: I)->getOperand(i_nocapture: DI),
3282 BB: PN->getIncomingBlock(U: I));
3283
3284 NewGEP->setOperand(i_nocapture: DI, Val_nocapture: NewPN);
3285 }
3286
3287 NewGEP->insertBefore(BB&: *GEP.getParent(), InsertPos: GEP.getParent()->getFirstInsertionPt());
3288 return NewGEP;
3289}
3290
3291Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3292 Value *PtrOp = GEP.getOperand(i_nocapture: 0);
3293 SmallVector<Value *, 8> Indices(GEP.indices());
3294 Type *GEPType = GEP.getType();
3295 Type *GEPEltType = GEP.getSourceElementType();
3296 if (Value *V =
3297 simplifyGEPInst(SrcTy: GEPEltType, Ptr: PtrOp, Indices, NW: GEP.getNoWrapFlags(),
3298 Q: SQ.getWithInstruction(I: &GEP)))
3299 return replaceInstUsesWith(I&: GEP, V);
3300
3301 // For vector geps, use the generic demanded vector support.
3302 // Skip if GEP return type is scalable. The number of elements is unknown at
3303 // compile-time.
3304 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(Val: GEPType)) {
3305 auto VWidth = GEPFVTy->getNumElements();
3306 APInt PoisonElts(VWidth, 0);
3307 APInt AllOnesEltMask(APInt::getAllOnes(numBits: VWidth));
3308 if (Value *V = SimplifyDemandedVectorElts(V: &GEP, DemandedElts: AllOnesEltMask,
3309 PoisonElts)) {
3310 if (V != &GEP)
3311 return replaceInstUsesWith(I&: GEP, V);
3312 return &GEP;
3313 }
3314 }
3315
3316 // Eliminate unneeded casts for indices, and replace indices which displace
3317 // by multiples of a zero size type with zero.
3318 bool MadeChange = false;
3319
3320 // Index width may not be the same width as pointer width.
3321 // Data layout chooses the right type based on supported integer types.
3322 Type *NewScalarIndexTy =
3323 DL.getIndexType(PtrTy: GEP.getPointerOperandType()->getScalarType());
3324
3325 gep_type_iterator GTI = gep_type_begin(GEP);
3326 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
3327 ++I, ++GTI) {
3328 // Skip indices into struct types.
3329 if (GTI.isStruct())
3330 continue;
3331
3332 Type *IndexTy = (*I)->getType();
3333 Type *NewIndexType =
3334 IndexTy->isVectorTy()
3335 ? VectorType::get(ElementType: NewScalarIndexTy,
3336 EC: cast<VectorType>(Val: IndexTy)->getElementCount())
3337 : NewScalarIndexTy;
3338
3339 // If the element type has zero size then any index over it is equivalent
3340 // to an index of zero, so replace it with zero if it is not zero already.
3341 Type *EltTy = GTI.getIndexedType();
3342 if (EltTy->isSized() && DL.getTypeAllocSize(Ty: EltTy).isZero())
3343 if (!isa<Constant>(Val: *I) || !match(V: I->get(), P: m_Zero())) {
3344 *I = Constant::getNullValue(Ty: NewIndexType);
3345 MadeChange = true;
3346 }
3347
3348 if (IndexTy != NewIndexType) {
3349 // If we are using a wider index than needed for this platform, shrink
3350 // it to what we need. If narrower, sign-extend it to what we need.
3351 // This explicit cast can make subsequent optimizations more obvious.
3352 if (IndexTy->getScalarSizeInBits() <
3353 NewIndexType->getScalarSizeInBits()) {
3354 if (GEP.hasNoUnsignedWrap() && GEP.hasNoUnsignedSignedWrap())
3355 *I = Builder.CreateZExt(V: *I, DestTy: NewIndexType, Name: "", /*IsNonNeg=*/true);
3356 else
3357 *I = Builder.CreateSExt(V: *I, DestTy: NewIndexType);
3358 } else {
3359 *I = Builder.CreateTrunc(V: *I, DestTy: NewIndexType, Name: "", IsNUW: GEP.hasNoUnsignedWrap(),
3360 IsNSW: GEP.hasNoUnsignedSignedWrap());
3361 }
3362 MadeChange = true;
3363 }
3364 }
3365 if (MadeChange)
3366 return &GEP;
3367
3368 // Canonicalize constant GEPs to i8 type.
3369 if (!GEPEltType->isIntegerTy(BitWidth: 8) && GEP.hasAllConstantIndices()) {
3370 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPType), 0);
3371 if (GEP.accumulateConstantOffset(DL, Offset))
3372 return replaceInstUsesWith(
3373 I&: GEP, V: Builder.CreatePtrAdd(Ptr: PtrOp, Offset: Builder.getInt(AI: Offset), Name: "",
3374 NW: GEP.getNoWrapFlags()));
3375 }
3376
3377 if (shouldCanonicalizeGEPToPtrAdd(GEP)) {
3378 Value *Offset = EmitGEPOffset(GEP: cast<GEPOperator>(Val: &GEP));
3379 Value *NewGEP =
3380 Builder.CreatePtrAdd(Ptr: PtrOp, Offset, Name: "", NW: GEP.getNoWrapFlags());
3381 return replaceInstUsesWith(I&: GEP, V: NewGEP);
3382 }
3383
3384 // Strip trailing zero indices.
3385 auto *LastIdx = dyn_cast<Constant>(Val: Indices.back());
3386 if (LastIdx && LastIdx->isNullValue() && !LastIdx->getType()->isVectorTy()) {
3387 return replaceInstUsesWith(
3388 I&: GEP, V: Builder.CreateGEP(Ty: GEP.getSourceElementType(), Ptr: PtrOp,
3389 IdxList: drop_end(RangeOrContainer&: Indices), Name: "", NW: GEP.getNoWrapFlags()));
3390 }
3391
3392 // Strip leading zero indices.
3393 auto *FirstIdx = dyn_cast<Constant>(Val: Indices.front());
3394 if (FirstIdx && FirstIdx->isNullValue() &&
3395 !FirstIdx->getType()->isVectorTy()) {
3396 gep_type_iterator GTI = gep_type_begin(GEP);
3397 ++GTI;
3398 if (!GTI.isStruct() && GTI.getSequentialElementStride(DL) ==
3399 DL.getTypeAllocSize(Ty: GTI.getIndexedType()))
3400 return replaceInstUsesWith(I&: GEP, V: Builder.CreateGEP(Ty: GTI.getIndexedType(),
3401 Ptr: GEP.getPointerOperand(),
3402 IdxList: drop_begin(RangeOrContainer&: Indices), Name: "",
3403 NW: GEP.getNoWrapFlags()));
3404 }
3405
3406 // Scalarize vector operands; prefer splat-of-gep.as canonical form.
3407 // Note that this looses information about undef lanes; we run it after
3408 // demanded bits to partially mitigate that loss.
3409 if (GEPType->isVectorTy() && llvm::any_of(Range: GEP.operands(), P: [](Value *Op) {
3410 return Op->getType()->isVectorTy() && getSplatValue(V: Op);
3411 })) {
3412 SmallVector<Value *> NewOps;
3413 for (auto &Op : GEP.operands()) {
3414 if (Op->getType()->isVectorTy())
3415 if (Value *Scalar = getSplatValue(V: Op)) {
3416 NewOps.push_back(Elt: Scalar);
3417 continue;
3418 }
3419 NewOps.push_back(Elt: Op);
3420 }
3421
3422 Value *Res = Builder.CreateGEP(Ty: GEP.getSourceElementType(), Ptr: NewOps[0],
3423 IdxList: ArrayRef(NewOps).drop_front(), Name: GEP.getName(),
3424 NW: GEP.getNoWrapFlags());
3425 if (!Res->getType()->isVectorTy()) {
3426 ElementCount EC = cast<VectorType>(Val: GEPType)->getElementCount();
3427 Res = Builder.CreateVectorSplat(EC, V: Res);
3428 }
3429 return replaceInstUsesWith(I&: GEP, V: Res);
3430 }
3431
3432 bool SeenNonZeroIndex = false;
3433 for (auto [IdxNum, Idx] : enumerate(First&: Indices)) {
3434 // Ignore one leading zero index.
3435 auto *C = dyn_cast<Constant>(Val: Idx);
3436 if (C && C->isNullValue() && IdxNum == 0)
3437 continue;
3438
3439 if (!SeenNonZeroIndex) {
3440 SeenNonZeroIndex = true;
3441 continue;
3442 }
3443
3444 // GEP has multiple non-zero indices: Split it.
3445 ArrayRef<Value *> FrontIndices = ArrayRef(Indices).take_front(N: IdxNum);
3446 Value *FrontGEP =
3447 Builder.CreateGEP(Ty: GEPEltType, Ptr: PtrOp, IdxList: FrontIndices,
3448 Name: GEP.getName() + ".split", NW: GEP.getNoWrapFlags());
3449
3450 SmallVector<Value *> BackIndices;
3451 BackIndices.push_back(Elt: Constant::getNullValue(Ty: NewScalarIndexTy));
3452 append_range(C&: BackIndices, R: drop_begin(RangeOrContainer&: Indices, N: IdxNum));
3453 return GetElementPtrInst::Create(
3454 PointeeType: GetElementPtrInst::getIndexedType(Ty: GEPEltType, IdxList: FrontIndices), Ptr: FrontGEP,
3455 IdxList: BackIndices, NW: GEP.getNoWrapFlags());
3456 }
3457
3458 // Canonicalize gep %T to gep [sizeof(%T) x i8]:
3459 auto IsCanonicalType = [](Type *Ty) {
3460 if (auto *AT = dyn_cast<ArrayType>(Val: Ty))
3461 Ty = AT->getElementType();
3462 return Ty->isIntegerTy(BitWidth: 8);
3463 };
3464 if (Indices.size() == 1 && !IsCanonicalType(GEPEltType)) {
3465 TypeSize Scale = DL.getTypeAllocSize(Ty: GEPEltType);
3466 assert(!Scale.isScalable() && "Should have been handled earlier");
3467 Type *NewElemTy = Builder.getInt8Ty();
3468 if (Scale.getFixedValue() != 1)
3469 NewElemTy = ArrayType::get(ElementType: NewElemTy, NumElements: Scale.getFixedValue());
3470 GEP.setSourceElementType(NewElemTy);
3471 GEP.setResultElementType(NewElemTy);
3472 // Don't bother revisiting the GEP after this change.
3473 MadeIRChange = true;
3474 }
3475
3476 // Check to see if the inputs to the PHI node are getelementptr instructions.
3477 if (auto *PN = dyn_cast<PHINode>(Val: PtrOp)) {
3478 if (Value *NewPtrOp = foldGEPOfPhi(GEP, PN, Builder))
3479 return replaceOperand(I&: GEP, OpNum: 0, V: NewPtrOp);
3480 }
3481
3482 if (auto *Src = dyn_cast<GEPOperator>(Val: PtrOp))
3483 if (Instruction *I = visitGEPOfGEP(GEP, Src))
3484 return I;
3485
3486 if (GEP.getNumIndices() == 1) {
3487 unsigned AS = GEP.getPointerAddressSpace();
3488 if (GEP.getOperand(i_nocapture: 1)->getType()->getScalarSizeInBits() ==
3489 DL.getIndexSizeInBits(AS)) {
3490 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty: GEPEltType).getFixedValue();
3491
3492 if (TyAllocSize == 1) {
3493 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),
3494 // but only if the result pointer is only used as if it were an integer.
3495 // (The case where the underlying object is the same is handled by
3496 // InstSimplify.)
3497 Value *X = GEP.getPointerOperand();
3498 Value *Y;
3499 if (match(V: GEP.getOperand(i_nocapture: 1), P: m_Sub(L: m_PtrToIntOrAddr(Op: m_Value(V&: Y)),
3500 R: m_PtrToIntOrAddr(Op: m_Specific(V: X)))) &&
3501 GEPType == Y->getType()) {
3502 bool HasNonAddressBits =
3503 DL.getAddressSizeInBits(AS) != DL.getPointerSizeInBits(AS);
3504 bool Changed = GEP.replaceUsesWithIf(New: Y, ShouldReplace: [&](Use &U) {
3505 return isa<PtrToAddrInst, ICmpInst>(Val: U.getUser()) ||
3506 (!HasNonAddressBits && isa<PtrToIntInst>(Val: U.getUser()));
3507 });
3508 return Changed ? &GEP : nullptr;
3509 }
3510 } else if (auto *ExactIns =
3511 dyn_cast<PossiblyExactOperator>(Val: GEP.getOperand(i_nocapture: 1))) {
3512 // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)
3513 Value *V;
3514 if (ExactIns->isExact()) {
3515 if ((has_single_bit(Value: TyAllocSize) &&
3516 match(V: GEP.getOperand(i_nocapture: 1),
3517 P: m_Shr(L: m_Value(V),
3518 R: m_SpecificInt(V: countr_zero(Val: TyAllocSize))))) ||
3519 match(V: GEP.getOperand(i_nocapture: 1),
3520 P: m_IDiv(L: m_Value(V), R: m_SpecificInt(V: TyAllocSize)))) {
3521 return GetElementPtrInst::Create(PointeeType: Builder.getInt8Ty(),
3522 Ptr: GEP.getPointerOperand(), IdxList: V,
3523 NW: GEP.getNoWrapFlags());
3524 }
3525 }
3526 if (ExactIns->isExact() && ExactIns->hasOneUse()) {
3527 // Try to canonicalize non-i8 element type to i8 if the index is an
3528 // exact instruction. If the index is an exact instruction (div/shr)
3529 // with a constant RHS, we can fold the non-i8 element scale into the
3530 // div/shr (similiar to the mul case, just inverted).
3531 const APInt *C;
3532 std::optional<APInt> NewC;
3533 if (has_single_bit(Value: TyAllocSize) &&
3534 match(V: ExactIns, P: m_Shr(L: m_Value(V), R: m_APInt(Res&: C))) &&
3535 C->uge(RHS: countr_zero(Val: TyAllocSize)))
3536 NewC = *C - countr_zero(Val: TyAllocSize);
3537 else if (match(V: ExactIns, P: m_UDiv(L: m_Value(V), R: m_APInt(Res&: C)))) {
3538 APInt Quot;
3539 uint64_t Rem;
3540 APInt::udivrem(LHS: *C, RHS: TyAllocSize, Quotient&: Quot, Remainder&: Rem);
3541 if (Rem == 0)
3542 NewC = Quot;
3543 } else if (match(V: ExactIns, P: m_SDiv(L: m_Value(V), R: m_APInt(Res&: C)))) {
3544 APInt Quot;
3545 int64_t Rem;
3546 APInt::sdivrem(LHS: *C, RHS: TyAllocSize, Quotient&: Quot, Remainder&: Rem);
3547 // For sdiv we need to make sure we arent creating INT_MIN / -1.
3548 if (!Quot.isAllOnes() && Rem == 0)
3549 NewC = Quot;
3550 }
3551
3552 if (NewC.has_value()) {
3553 Value *NewOp = Builder.CreateExactBinOp(
3554 Opc: static_cast<Instruction::BinaryOps>(ExactIns->getOpcode()), LHS: V,
3555 RHS: ConstantInt::get(Ty: V->getType(), V: *NewC), /*IsExact=*/true);
3556 return GetElementPtrInst::Create(PointeeType: Builder.getInt8Ty(),
3557 Ptr: GEP.getPointerOperand(), IdxList: NewOp,
3558 NW: GEP.getNoWrapFlags());
3559 }
3560 }
3561 }
3562 }
3563 }
3564 // We do not handle pointer-vector geps here.
3565 if (GEPType->isVectorTy())
3566 return nullptr;
3567
3568 if (!GEP.isInBounds()) {
3569 unsigned IdxWidth =
3570 DL.getIndexSizeInBits(AS: PtrOp->getType()->getPointerAddressSpace());
3571 APInt BasePtrOffset(IdxWidth, 0);
3572 Value *UnderlyingPtrOp =
3573 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, Offset&: BasePtrOffset);
3574 bool CanBeNull;
3575 uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(
3576 DL, CanBeNull, /*CanBeFreed=*/nullptr);
3577 // We can ignore CanBeFreed here, because inbounds is explicitly allowed to
3578 // refer to a deallocated object.
3579 if (!CanBeNull && DerefBytes != 0) {
3580 if (GEP.accumulateConstantOffset(DL, Offset&: BasePtrOffset) &&
3581 BasePtrOffset.isNonNegative()) {
3582 APInt AllocSize(IdxWidth, DerefBytes);
3583 if (BasePtrOffset.ule(RHS: AllocSize)) {
3584 return GetElementPtrInst::CreateInBounds(
3585 PointeeType: GEP.getSourceElementType(), Ptr: PtrOp, IdxList: Indices, NameStr: GEP.getName());
3586 }
3587 }
3588 }
3589 }
3590
3591 // nusw + nneg -> nuw
3592 if (GEP.hasNoUnsignedSignedWrap() && !GEP.hasNoUnsignedWrap() &&
3593 all_of(Range: GEP.indices(), P: [&](Value *Idx) {
3594 return isKnownNonNegative(V: Idx, SQ: SQ.getWithInstruction(I: &GEP));
3595 })) {
3596 GEP.setNoWrapFlags(GEP.getNoWrapFlags() | GEPNoWrapFlags::noUnsignedWrap());
3597 return &GEP;
3598 }
3599
3600 // These rewrites are trying to preserve inbounds/nuw attributes. So we want
3601 // to do this after having tried to derive "nuw" above.
3602 if (GEP.getNumIndices() == 1) {
3603 // Given (gep p, x+y) we want to determine the common nowrap flags for both
3604 // geps if transforming into (gep (gep p, x), y).
3605 auto GetPreservedNoWrapFlags = [&](bool AddIsNUW) {
3606 // We can preserve both "inbounds nuw", "nusw nuw" and "nuw" if we know
3607 // that x + y does not have unsigned wrap.
3608 if (GEP.hasNoUnsignedWrap() && AddIsNUW)
3609 return GEP.getNoWrapFlags();
3610 return GEPNoWrapFlags::none();
3611 };
3612
3613 // Try to replace ADD + GEP with GEP + GEP.
3614 Value *Idx1, *Idx2;
3615 if (match(V: GEP.getOperand(i_nocapture: 1),
3616 P: m_OneUse(SubPattern: m_AddLike(L: m_Value(V&: Idx1), R: m_Value(V&: Idx2))))) {
3617 // %idx = add i64 %idx1, %idx2
3618 // %gep = getelementptr i32, ptr %ptr, i64 %idx
3619 // as:
3620 // %newptr = getelementptr i32, ptr %ptr, i64 %idx1
3621 // %newgep = getelementptr i32, ptr %newptr, i64 %idx2
3622 bool NUW = match(V: GEP.getOperand(i_nocapture: 1), P: m_NUWAddLike(L: m_Value(), R: m_Value()));
3623 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3624 auto *NewPtr =
3625 Builder.CreateGEP(Ty: GEP.getSourceElementType(), Ptr: GEP.getPointerOperand(),
3626 IdxList: Idx1, Name: "", NW: NWFlags);
3627 return replaceInstUsesWith(I&: GEP,
3628 V: Builder.CreateGEP(Ty: GEP.getSourceElementType(),
3629 Ptr: NewPtr, IdxList: Idx2, Name: "", NW: NWFlags));
3630 }
3631 ConstantInt *C;
3632 if (match(V: GEP.getOperand(i_nocapture: 1), P: m_OneUse(SubPattern: m_SExtLike(Op: m_OneUse(SubPattern: m_NSWAddLike(
3633 L: m_Value(V&: Idx1), R: m_ConstantInt(CI&: C))))))) {
3634 // %add = add nsw i32 %idx1, idx2
3635 // %sidx = sext i32 %add to i64
3636 // %gep = getelementptr i32, ptr %ptr, i64 %sidx
3637 // as:
3638 // %newptr = getelementptr i32, ptr %ptr, i32 %idx1
3639 // %newgep = getelementptr i32, ptr %newptr, i32 idx2
3640 bool NUW = match(V: GEP.getOperand(i_nocapture: 1),
3641 P: m_NNegZExt(Op: m_NUWAddLike(L: m_Value(), R: m_Value())));
3642 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3643 auto *NewPtr = Builder.CreateGEP(
3644 Ty: GEP.getSourceElementType(), Ptr: GEP.getPointerOperand(),
3645 IdxList: Builder.CreateSExt(V: Idx1, DestTy: GEP.getOperand(i_nocapture: 1)->getType()), Name: "", NW: NWFlags);
3646 return replaceInstUsesWith(
3647 I&: GEP,
3648 V: Builder.CreateGEP(Ty: GEP.getSourceElementType(), Ptr: NewPtr,
3649 IdxList: Builder.CreateSExt(V: C, DestTy: GEP.getOperand(i_nocapture: 1)->getType()),
3650 Name: "", NW: NWFlags));
3651 }
3652 }
3653
3654 if (Instruction *R = foldSelectGEP(GEP, Builder))
3655 return R;
3656
3657 // srem -> (and/urem) for inbounds+nuw GEP
3658 if (Indices.size() == 1 && GEP.isInBounds() && GEP.hasNoUnsignedWrap()) {
3659 Value *X, *Y;
3660
3661 // Match: idx = srem X, Y -- where Y is a power-of-two value.
3662 if (match(V: Indices[0], P: m_OneUse(SubPattern: m_SRem(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
3663 isKnownToBeAPowerOfTwo(V: Y, /*OrZero=*/true, CtxI: &GEP)) {
3664 // If GEP is inbounds+nuw, the offset cannot be negative
3665 // -> srem by power-of-two can be treated as urem,
3666 // and urem by power-of-two folds to 'and' later.
3667 // OrZero=true is fine here because division by zero is UB.
3668 Instruction *OldIdxI = cast<Instruction>(Val: Indices[0]);
3669 Value *NewIdx = Builder.CreateURem(LHS: X, RHS: Y, Name: OldIdxI->getName());
3670
3671 return GetElementPtrInst::Create(PointeeType: GEPEltType, Ptr: PtrOp, IdxList: {NewIdx},
3672 NW: GEP.getNoWrapFlags());
3673 }
3674 }
3675
3676 return nullptr;
3677}
3678
3679static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo &TLI,
3680 Instruction *AI) {
3681 if (isa<ConstantPointerNull>(Val: V))
3682 return true;
3683 if (auto *LI = dyn_cast<LoadInst>(Val: V))
3684 return isa<GlobalVariable>(Val: LI->getPointerOperand());
3685 // Two distinct allocations will never be equal.
3686 return isAllocLikeFn(V, TLI: &TLI) && V != AI;
3687}
3688
3689/// Given a call CB which uses an address UsedV, return true if we can prove the
3690/// call's only possible effect is storing to V.
3691static bool isRemovableWrite(CallBase &CB, Value *UsedV,
3692 const TargetLibraryInfo &TLI) {
3693 if (!CB.use_empty())
3694 // TODO: add recursion if returned attribute is present
3695 return false;
3696
3697 if (CB.isTerminator())
3698 // TODO: remove implementation restriction
3699 return false;
3700
3701 if (!CB.willReturn() || !CB.doesNotThrow())
3702 return false;
3703
3704 // If the only possible side effect of the call is writing to the alloca,
3705 // and the result isn't used, we can safely remove any reads implied by the
3706 // call including those which might read the alloca itself.
3707 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CI: &CB, TLI);
3708 return Dest && Dest->Ptr == UsedV;
3709}
3710
3711static std::optional<ModRefInfo>
3712isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<Instruction *> &Users,
3713 const TargetLibraryInfo &TLI, bool KnowInit,
3714 unsigned MaxUsers) {
3715 SmallVector<Instruction*, 4> Worklist;
3716 const std::optional<StringRef> Family = getAllocationFamily(I: AI, TLI: &TLI);
3717 Worklist.push_back(Elt: AI);
3718 ModRefInfo Access = KnowInit ? ModRefInfo::NoModRef : ModRefInfo::Mod;
3719
3720 do {
3721 Instruction *PI = Worklist.pop_back_val();
3722 for (User *U : PI->users()) {
3723 Instruction *I = cast<Instruction>(Val: U);
3724 if (Users.size() >= MaxUsers)
3725 return std::nullopt;
3726 switch (I->getOpcode()) {
3727 default:
3728 // Give up the moment we see something we can't handle.
3729 return std::nullopt;
3730
3731 case Instruction::AddrSpaceCast:
3732 case Instruction::BitCast:
3733 case Instruction::GetElementPtr:
3734 Users.emplace_back(Args&: I);
3735 Worklist.push_back(Elt: I);
3736 continue;
3737
3738 case Instruction::ICmp: {
3739 ICmpInst *ICI = cast<ICmpInst>(Val: I);
3740 // We can fold eq/ne comparisons with null to false/true, respectively.
3741 // We also fold comparisons in some conditions provided the alloc has
3742 // not escaped (see isNeverEqualToUnescapedAlloc).
3743 if (!ICI->isEquality())
3744 return std::nullopt;
3745 unsigned OtherIndex = (ICI->getOperand(i_nocapture: 0) == PI) ? 1 : 0;
3746 if (!isNeverEqualToUnescapedAlloc(V: ICI->getOperand(i_nocapture: OtherIndex), TLI, AI))
3747 return std::nullopt;
3748
3749 // Do not fold compares to aligned_alloc calls, as they may have to
3750 // return null in case the required alignment cannot be satisfied,
3751 // unless we can prove that both alignment and size are valid.
3752 auto AlignmentAndSizeKnownValid = [](CallBase *CB) {
3753 // Check if alignment and size of a call to aligned_alloc is valid,
3754 // that is alignment is a power-of-2 and the size is a multiple of the
3755 // alignment.
3756 const APInt *Alignment;
3757 const APInt *Size;
3758 return match(V: CB->getArgOperand(i: 0), P: m_APInt(Res&: Alignment)) &&
3759 match(V: CB->getArgOperand(i: 1), P: m_APInt(Res&: Size)) &&
3760 Alignment->isPowerOf2() && Size->urem(RHS: *Alignment).isZero();
3761 };
3762 auto *CB = dyn_cast<CallBase>(Val: AI);
3763 if (CB &&
3764 TLI.getLibFunc(FDecl: *CB->getCalledFunction()) == LibFunc_aligned_alloc &&
3765 TLI.has(F: LibFunc_aligned_alloc) && !AlignmentAndSizeKnownValid(CB))
3766 return std::nullopt;
3767 Users.emplace_back(Args&: I);
3768 continue;
3769 }
3770
3771 case Instruction::Call:
3772 // Ignore no-op and store intrinsics.
3773 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
3774 switch (II->getIntrinsicID()) {
3775 default:
3776 return std::nullopt;
3777
3778 case Intrinsic::memmove:
3779 case Intrinsic::memcpy:
3780 case Intrinsic::memset: {
3781 MemIntrinsic *MI = cast<MemIntrinsic>(Val: II);
3782 if (MI->isVolatile())
3783 return std::nullopt;
3784 // Note: this could also be ModRef, but we can still interpret that
3785 // as just Mod in that case.
3786 ModRefInfo NewAccess =
3787 MI->getRawDest() == PI ? ModRefInfo::Mod : ModRefInfo::Ref;
3788 if ((Access & ~NewAccess) != ModRefInfo::NoModRef)
3789 return std::nullopt;
3790 Access |= NewAccess;
3791 [[fallthrough]];
3792 }
3793 case Intrinsic::assume:
3794 case Intrinsic::invariant_start:
3795 case Intrinsic::invariant_end:
3796 case Intrinsic::lifetime_start:
3797 case Intrinsic::lifetime_end:
3798 case Intrinsic::objectsize:
3799 Users.emplace_back(Args&: I);
3800 continue;
3801 case Intrinsic::launder_invariant_group:
3802 Users.emplace_back(Args&: I);
3803 Worklist.push_back(Elt: I);
3804 continue;
3805 }
3806 }
3807
3808 if (Family && getFreedOperand(CB: cast<CallBase>(Val: I), TLI: &TLI) == PI &&
3809 getAllocationFamily(I, TLI: &TLI) == Family) {
3810 Users.emplace_back(Args&: I);
3811 continue;
3812 }
3813
3814 if (Family && getReallocatedOperand(CB: cast<CallBase>(Val: I)) == PI &&
3815 getAllocationFamily(I, TLI: &TLI) == Family) {
3816 Users.emplace_back(Args&: I);
3817 Worklist.push_back(Elt: I);
3818 continue;
3819 }
3820
3821 if (!isRefSet(MRI: Access) &&
3822 isRemovableWrite(CB&: *cast<CallBase>(Val: I), UsedV: PI, TLI)) {
3823 Access |= ModRefInfo::Mod;
3824 Users.emplace_back(Args&: I);
3825 continue;
3826 }
3827
3828 return std::nullopt;
3829
3830 case Instruction::Store: {
3831 StoreInst *SI = cast<StoreInst>(Val: I);
3832 if (SI->isVolatile() || SI->getPointerOperand() != PI)
3833 return std::nullopt;
3834 if (isRefSet(MRI: Access))
3835 return std::nullopt;
3836 Access |= ModRefInfo::Mod;
3837 Users.emplace_back(Args&: I);
3838 continue;
3839 }
3840
3841 case Instruction::Load: {
3842 LoadInst *LI = cast<LoadInst>(Val: I);
3843 if (LI->isVolatile() || LI->getPointerOperand() != PI)
3844 return std::nullopt;
3845 if (isModSet(MRI: Access))
3846 return std::nullopt;
3847 Access |= ModRefInfo::Ref;
3848 Users.emplace_back(Args&: I);
3849 continue;
3850 }
3851 }
3852 llvm_unreachable("missing a return?");
3853 }
3854 } while (!Worklist.empty());
3855
3856 assert(Access != ModRefInfo::ModRef);
3857 return Access;
3858}
3859
3860Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) {
3861 assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI));
3862
3863 // If we have a malloc call which is only used in any amount of comparisons to
3864 // null and free calls, delete the calls and replace the comparisons with true
3865 // or false as appropriate.
3866
3867 // This is based on the principle that we can substitute our own allocation
3868 // function (which will never return null) rather than knowledge of the
3869 // specific function being called. In some sense this can change the permitted
3870 // outputs of a program (when we convert a malloc to an alloca, the fact that
3871 // the allocation is now on the stack is potentially visible, for example),
3872 // but we believe in a permissible manner.
3873 //
3874 // Collect into Instruction* first to avoid expensive WeakTrackingVH
3875 // register/unregister overhead; convert to WeakTrackingVH only when the
3876 // site is actually removable.
3877 SmallVector<Instruction *, 64> RawUsers;
3878
3879 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
3880 // before each store.
3881 SmallVector<DbgVariableRecord *, 8> DVRs;
3882 std::unique_ptr<DIBuilder> DIB;
3883 if (isa<AllocaInst>(Val: MI)) {
3884 findDbgUsers(V: &MI, DbgVariableRecords&: DVRs);
3885 DIB.reset(p: new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
3886 }
3887
3888 // Determine what getInitialValueOfAllocation would return without actually
3889 // allocating the result.
3890 bool KnowInitUndef = false;
3891 bool KnowInitZero = false;
3892 Constant *Init =
3893 getInitialValueOfAllocation(V: &MI, TLI: &TLI, Ty: Type::getInt8Ty(C&: MI.getContext()));
3894 if (Init) {
3895 if (isa<UndefValue>(Val: Init))
3896 KnowInitUndef = true;
3897 else if (Init->isNullValue())
3898 KnowInitZero = true;
3899 }
3900 // The various sanitizers don't actually return undef memory, but rather
3901 // memory initialized with special forms of runtime poison
3902 auto &F = *MI.getFunction();
3903 if (F.hasFnAttribute(Kind: Attribute::SanitizeMemory) ||
3904 F.hasFnAttribute(Kind: Attribute::SanitizeAddress))
3905 KnowInitUndef = false;
3906
3907 auto Removable =
3908 isAllocSiteRemovable(AI: &MI, Users&: RawUsers, TLI, KnowInit: KnowInitZero | KnowInitUndef,
3909 MaxUsers: CLOpts.max_allocsite_removable_users);
3910 if (Removable) {
3911 SmallVector<WeakTrackingVH, 64> Users(RawUsers.begin(), RawUsers.end());
3912 for (WeakTrackingVH &User : Users) {
3913 // Lowering all @llvm.objectsize and MTI calls first because they may use
3914 // a bitcast/GEP of the alloca we are removing.
3915 if (!User)
3916 continue;
3917
3918 Instruction *I = cast<Instruction>(Val: &*User);
3919
3920 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
3921 if (II->getIntrinsicID() == Intrinsic::objectsize) {
3922 SmallVector<Instruction *> InsertedInstructions;
3923 Value *Result = lowerObjectSizeCall(
3924 ObjectSize: II, DL, TLI: &TLI, AA, /*MustSucceed=*/true, InsertedInstructions: &InsertedInstructions);
3925 for (Instruction *Inserted : InsertedInstructions)
3926 Worklist.add(I: Inserted);
3927 replaceInstUsesWith(I&: *I, V: Result);
3928 eraseInstFromFunction(I&: *I);
3929 User = nullptr; // Skip examining in the next loop.
3930 continue;
3931 }
3932 if (auto *MTI = dyn_cast<MemTransferInst>(Val: I)) {
3933 if (KnowInitZero && isRefSet(MRI: *Removable)) {
3934 IRBuilderBase::InsertPointGuard Guard(Builder);
3935 Builder.SetInsertPoint(MTI);
3936 auto *M = Builder.CreateMemSet(
3937 Ptr: MTI->getRawDest(),
3938 Val: ConstantInt::get(Ty: Type::getInt8Ty(C&: MI.getContext()), V: 0),
3939 Size: MTI->getLength(), Align: MTI->getDestAlign());
3940 M->copyMetadata(SrcInst: *MTI);
3941 }
3942 }
3943 }
3944 }
3945 for (WeakTrackingVH &User : Users) {
3946 if (!User)
3947 continue;
3948
3949 Instruction *I = cast<Instruction>(Val: &*User);
3950
3951 if (ICmpInst *C = dyn_cast<ICmpInst>(Val: I)) {
3952 replaceInstUsesWith(
3953 I&: *C, V: ConstantInt::get(Ty: C->getType(), V: C->isFalseWhenEqual()));
3954 } else if (auto *SI = dyn_cast<StoreInst>(Val: I)) {
3955 for (auto *DVR : DVRs)
3956 if (DVR->isAddressOfVariable())
3957 ConvertDebugDeclareToDebugValue(DVR, SI, Builder&: *DIB);
3958 } else {
3959 // Casts, GEP, or anything else: we're about to delete this instruction,
3960 // so it can not have any valid uses.
3961 Constant *Replace;
3962 if (isa<LoadInst>(Val: I)) {
3963 assert(KnowInitZero || KnowInitUndef);
3964 Replace = KnowInitUndef ? UndefValue::get(T: I->getType())
3965 : Constant::getNullValue(Ty: I->getType());
3966 } else
3967 Replace = PoisonValue::get(T: I->getType());
3968 replaceInstUsesWith(I&: *I, V: Replace);
3969 }
3970 eraseInstFromFunction(I&: *I);
3971 }
3972
3973 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: &MI)) {
3974 // Replace invoke with a NOP intrinsic to maintain the original CFG
3975 Module *M = II->getModule();
3976 Function *F = Intrinsic::getOrInsertDeclaration(M, id: Intrinsic::donothing);
3977 auto *NewII = InvokeInst::Create(
3978 Func: F, IfNormal: II->getNormalDest(), IfException: II->getUnwindDest(), Args: {}, NameStr: "", InsertBefore: II->getParent());
3979 NewII->setDebugLoc(II->getDebugLoc());
3980 }
3981
3982 // Remove debug intrinsics which describe the value contained within the
3983 // alloca. In addition to removing dbg.{declare,addr} which simply point to
3984 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
3985 //
3986 // ```
3987 // define void @foo(i32 %0) {
3988 // %a = alloca i32 ; Deleted.
3989 // store i32 %0, i32* %a
3990 // dbg.value(i32 %0, "arg0") ; Not deleted.
3991 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
3992 // call void @trivially_inlinable_no_op(i32* %a)
3993 // ret void
3994 // }
3995 // ```
3996 //
3997 // This may not be required if we stop describing the contents of allocas
3998 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
3999 // the LowerDbgDeclare utility.
4000 //
4001 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
4002 // "arg0" dbg.value may be stale after the call. However, failing to remove
4003 // the DW_OP_deref dbg.value causes large gaps in location coverage.
4004 //
4005 // FIXME: the Assignment Tracking project has now likely made this
4006 // redundant (and it's sometimes harmful).
4007 for (auto *DVR : DVRs)
4008 if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())
4009 DVR->eraseFromParent();
4010
4011 return eraseInstFromFunction(I&: MI);
4012 }
4013 return nullptr;
4014}
4015
4016/// Move the call to free before a NULL test.
4017///
4018/// Check if this free is accessed after its argument has been test
4019/// against NULL (property 0).
4020/// If yes, it is legal to move this call in its predecessor block.
4021///
4022/// The move is performed only if the block containing the call to free
4023/// will be removed, i.e.:
4024/// 1. it has only one predecessor P, and P has two successors
4025/// 2. it contains the call, noops, and an unconditional branch
4026/// 3. its successor is the same as its predecessor's successor
4027///
4028/// The profitability is out-of concern here and this function should
4029/// be called only if the caller knows this transformation would be
4030/// profitable (e.g., for code size).
4031static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
4032 const DataLayout &DL) {
4033 Value *Op = FI.getArgOperand(i: 0);
4034 BasicBlock *FreeInstrBB = FI.getParent();
4035 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
4036
4037 // Validate part of constraint #1: Only one predecessor
4038 // FIXME: We can extend the number of predecessor, but in that case, we
4039 // would duplicate the call to free in each predecessor and it may
4040 // not be profitable even for code size.
4041 if (!PredBB)
4042 return nullptr;
4043
4044 // Validate constraint #2: Does this block contains only the call to
4045 // free, noops, and an unconditional branch?
4046 BasicBlock *SuccBB;
4047 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
4048 if (!match(V: FreeInstrBBTerminator, P: m_UnconditionalBr(Succ&: SuccBB)))
4049 return nullptr;
4050
4051 // If there are only 2 instructions in the block, at this point,
4052 // this is the call to free and unconditional.
4053 // If there are more than 2 instructions, check that they are noops
4054 // i.e., they won't hurt the performance of the generated code.
4055 if (FreeInstrBB->size() != 2) {
4056 for (const Instruction &Inst : *FreeInstrBB) {
4057 if (&Inst == &FI || &Inst == FreeInstrBBTerminator ||
4058 isa<PseudoProbeInst>(Val: Inst))
4059 continue;
4060 auto *Cast = dyn_cast<CastInst>(Val: &Inst);
4061 if (!Cast || !Cast->isNoopCast(DL))
4062 return nullptr;
4063 }
4064 }
4065 // Validate the rest of constraint #1 by matching on the pred branch.
4066 Instruction *TI = PredBB->getTerminator();
4067 BasicBlock *TrueBB, *FalseBB;
4068 CmpPredicate Pred;
4069 if (!match(V: TI, P: m_Br(C: m_ICmp(Pred,
4070 L: m_CombineOr(Ps: m_Specific(V: Op),
4071 Ps: m_Specific(V: Op->stripPointerCasts())),
4072 R: m_Zero()),
4073 T&: TrueBB, F&: FalseBB)))
4074 return nullptr;
4075 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
4076 return nullptr;
4077
4078 // Validate constraint #3: Ensure the null case just falls through.
4079 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
4080 return nullptr;
4081 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
4082 "Broken CFG: missing edge from predecessor to successor");
4083
4084 // At this point, we know that everything in FreeInstrBB can be moved
4085 // before TI.
4086 for (Instruction &Instr : llvm::make_early_inc_range(Range&: *FreeInstrBB)) {
4087 if (&Instr == FreeInstrBBTerminator)
4088 break;
4089 Instr.moveBeforePreserving(MovePos: TI->getIterator());
4090 }
4091 assert(FreeInstrBB->size() == 1 &&
4092 "Only the branch instruction should remain");
4093
4094 // Now that we've moved the call to free before the NULL check, we have to
4095 // remove any attributes on its parameter that imply it's non-null, because
4096 // those attributes might have only been valid because of the NULL check, and
4097 // we can get miscompiles if we keep them. This is conservative if non-null is
4098 // also implied by something other than the NULL check, but it's guaranteed to
4099 // be correct, and the conservativeness won't matter in practice, since the
4100 // attributes are irrelevant for the call to free itself and the pointer
4101 // shouldn't be used after the call.
4102 AttributeList Attrs = FI.getAttributes();
4103 Attrs = Attrs.removeParamAttribute(C&: FI.getContext(), ArgNo: 0, Kind: Attribute::NonNull);
4104 Attribute Dereferenceable = Attrs.getParamAttr(ArgNo: 0, Kind: Attribute::Dereferenceable);
4105 if (Dereferenceable.isValid()) {
4106 uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
4107 Attrs = Attrs.removeParamAttribute(C&: FI.getContext(), ArgNo: 0,
4108 Kind: Attribute::Dereferenceable);
4109 Attrs = Attrs.addDereferenceableOrNullParamAttr(C&: FI.getContext(), ArgNo: 0, Bytes);
4110 }
4111 FI.setAttributes(Attrs);
4112
4113 return &FI;
4114}
4115
4116Instruction *InstCombinerImpl::visitFree(CallInst &FI, Value *Op) {
4117 // free undef -> unreachable.
4118 if (isa<UndefValue>(Val: Op)) {
4119 // Leave a marker since we can't modify the CFG here.
4120 CreateNonTerminatorUnreachable(InsertAt: &FI);
4121 return eraseInstFromFunction(I&: FI);
4122 }
4123
4124 // If we have 'free null' delete the instruction. This can happen in stl code
4125 // when lots of inlining happens.
4126 if (isa<ConstantPointerNull>(Val: Op))
4127 return eraseInstFromFunction(I&: FI);
4128
4129 // If we had free(realloc(...)) with no intervening uses, then eliminate the
4130 // realloc() entirely.
4131 CallInst *CI = dyn_cast<CallInst>(Val: Op);
4132 if (CI && CI->hasOneUse())
4133 if (Value *ReallocatedOp = getReallocatedOperand(CB: CI))
4134 return eraseInstFromFunction(I&: *replaceInstUsesWith(I&: *CI, V: ReallocatedOp));
4135
4136 // If we optimize for code size, try to move the call to free before the null
4137 // test so that simplify cfg can remove the empty block and dead code
4138 // elimination the branch. I.e., helps to turn something like:
4139 // if (foo) free(foo);
4140 // into
4141 // free(foo);
4142 //
4143 // Note that we can only do this for 'free' and not for any flavor of
4144 // 'operator delete'; there is no 'operator delete' symbol for which we are
4145 // permitted to invent a call, even if we're passing in a null pointer.
4146 if (MinimizeSize) {
4147 if (TLI.getLibFunc(CB: FI) == LibFunc_free && TLI.has(F: LibFunc_free))
4148 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
4149 return I;
4150 }
4151
4152 return nullptr;
4153}
4154
4155Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) {
4156 Value *RetVal = RI.getReturnValue();
4157 if (!RetVal)
4158 return nullptr;
4159
4160 Function *F = RI.getFunction();
4161 Type *RetTy = RetVal->getType();
4162 if (RetTy->isPointerTy()) {
4163 bool UseProvenance =
4164 F->getAttributes().getRetDereferenceableBytes() > 0 &&
4165 !NullPointerIsDefined(F, AS: RetTy->getPointerAddressSpace());
4166 if (F->hasRetAttribute(Kind: Attribute::NonNull) || UseProvenance) {
4167 if (Value *V = simplifyNonNullOperand(V: RetVal, UseProvenance))
4168 return replaceOperand(I&: RI, OpNum: 0, V);
4169 }
4170 }
4171
4172 if (!AttributeFuncs::isNoFPClassCompatibleType(Ty: RetTy))
4173 return nullptr;
4174
4175 FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();
4176 if (ReturnClass == fcNone)
4177 return nullptr;
4178
4179 KnownFPClass KnownClass;
4180 if (SimplifyDemandedFPClass(I: &RI, Op: 0, DemandedMask: ~ReturnClass, Known&: KnownClass,
4181 Q: SQ.getWithInstruction(I: &RI)))
4182 return &RI;
4183
4184 return nullptr;
4185}
4186
4187// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
4188bool InstCombinerImpl::removeInstructionsBeforeUnreachable(Instruction &I) {
4189 // Try to remove the previous instruction if it must lead to unreachable.
4190 // This includes instructions like stores and "llvm.assume" that may not get
4191 // removed by simple dead code elimination.
4192 bool Changed = false;
4193 while (Instruction *Prev = I.getPrevNode()) {
4194 // While we theoretically can erase EH, that would result in a block that
4195 // used to start with an EH no longer starting with EH, which is invalid.
4196 // To make it valid, we'd need to fixup predecessors to no longer refer to
4197 // this block, but that changes CFG, which is not allowed in InstCombine.
4198 if (Prev->isEHPad())
4199 break; // Can not drop any more instructions. We're done here.
4200
4201 if (!isGuaranteedToTransferExecutionToSuccessor(I: Prev))
4202 break; // Can not drop any more instructions. We're done here.
4203 // Otherwise, this instruction can be freely erased,
4204 // even if it is not side-effect free.
4205
4206 // A value may still have uses before we process it here (for example, in
4207 // another unreachable block), so convert those to poison.
4208 replaceInstUsesWith(I&: *Prev, V: PoisonValue::get(T: Prev->getType()));
4209 eraseInstFromFunction(I&: *Prev);
4210 Changed = true;
4211 }
4212 return Changed;
4213}
4214
4215Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) {
4216 removeInstructionsBeforeUnreachable(I);
4217 return nullptr;
4218}
4219
4220Instruction *InstCombinerImpl::visitUncondBrInst(UncondBrInst &BI) {
4221 // If this store is the second-to-last instruction in the basic block
4222 // (excluding debug info) and if the block ends with
4223 // an unconditional branch, try to move the store to the successor block.
4224
4225 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
4226 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
4227 do {
4228 if (BBI != FirstInstr)
4229 --BBI;
4230 } while (BBI != FirstInstr && BBI->isDebugOrPseudoInst());
4231
4232 return dyn_cast<StoreInst>(Val&: BBI);
4233 };
4234
4235 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
4236 if (mergeStoreIntoSuccessor(SI&: *SI))
4237 return &BI;
4238
4239 return nullptr;
4240}
4241
4242void InstCombinerImpl::addDeadEdge(BasicBlock *From, BasicBlock *To,
4243 SmallVectorImpl<BasicBlock *> &Worklist) {
4244 if (!DeadEdges.insert(V: {From, To}).second)
4245 return;
4246
4247 // Replace phi node operands in successor with poison.
4248 for (PHINode &PN : To->phis())
4249 for (Use &U : PN.incoming_values())
4250 if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(Val: U)) {
4251 replaceUse(U, NewValue: PoisonValue::get(T: PN.getType()));
4252 addToWorklist(I: &PN);
4253 MadeIRChange = true;
4254 }
4255
4256 Worklist.push_back(Elt: To);
4257}
4258
4259// Under the assumption that I is unreachable, remove it and following
4260// instructions. Changes are reported directly to MadeIRChange.
4261void InstCombinerImpl::handleUnreachableFrom(
4262 Instruction *I, SmallVectorImpl<BasicBlock *> &Worklist) {
4263 BasicBlock *BB = I->getParent();
4264 for (Instruction &Inst : make_early_inc_range(
4265 Range: make_range(x: std::next(x: BB->getTerminator()->getReverseIterator()),
4266 y: std::next(x: I->getReverseIterator())))) {
4267 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
4268 replaceInstUsesWith(I&: Inst, V: PoisonValue::get(T: Inst.getType()));
4269 MadeIRChange = true;
4270 }
4271 if (Inst.isEHPad() || Inst.getType()->isTokenTy())
4272 continue;
4273 // RemoveDIs: erase debug-info on this instruction manually.
4274 Inst.dropDbgRecords();
4275 eraseInstFromFunction(I&: Inst);
4276 MadeIRChange = true;
4277 }
4278
4279 SmallVector<Value *> Changed;
4280 if (handleUnreachableTerminator(I: BB->getTerminator(), PoisonedValues&: Changed)) {
4281 MadeIRChange = true;
4282 for (Value *V : Changed)
4283 addToWorklist(I: cast<Instruction>(Val: V));
4284 }
4285
4286 // Handle potentially dead successors.
4287 for (BasicBlock *Succ : successors(BB))
4288 addDeadEdge(From: BB, To: Succ, Worklist);
4289}
4290
4291void InstCombinerImpl::handlePotentiallyDeadBlocks(
4292 SmallVectorImpl<BasicBlock *> &Worklist) {
4293 while (!Worklist.empty()) {
4294 BasicBlock *BB = Worklist.pop_back_val();
4295 if (!all_of(Range: predecessors(BB), P: [&](BasicBlock *Pred) {
4296 return DeadEdges.contains(V: {Pred, BB}) || DT.dominates(A: BB, B: Pred);
4297 }))
4298 continue;
4299
4300 handleUnreachableFrom(I: &BB->front(), Worklist);
4301 }
4302}
4303
4304void InstCombinerImpl::handlePotentiallyDeadSuccessors(BasicBlock *BB,
4305 BasicBlock *LiveSucc) {
4306 SmallVector<BasicBlock *> Worklist;
4307 for (BasicBlock *Succ : successors(BB)) {
4308 // The live successor isn't dead.
4309 if (Succ == LiveSucc)
4310 continue;
4311
4312 addDeadEdge(From: BB, To: Succ, Worklist);
4313 }
4314
4315 handlePotentiallyDeadBlocks(Worklist);
4316}
4317
4318Instruction *InstCombinerImpl::visitCondBrInst(CondBrInst &BI) {
4319 // Change br (not X), label True, label False to: br X, label False, True
4320 Value *Cond = BI.getCondition();
4321 Value *X;
4322 if (match(V: Cond, P: m_Not(V: m_Value(V&: X))) && !isa<Constant>(Val: X)) {
4323 // Swap Destinations and condition...
4324 BI.swapSuccessors();
4325 if (BPI)
4326 BPI->swapSuccEdgesProbabilities(Src: BI.getParent());
4327 return replaceOperand(I&: BI, OpNum: 0, V: X);
4328 }
4329
4330 // Canonicalize logical-and-with-invert as logical-or-with-invert.
4331 // This is done by inverting the condition and swapping successors:
4332 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
4333 Value *Y;
4334 if (isa<SelectInst>(Val: Cond) &&
4335 match(V: Cond,
4336 P: m_OneUse(SubPattern: m_LogicalAnd(L: m_Value(V&: X), R: m_OneUse(SubPattern: m_Not(V: m_Value(V&: Y))))))) {
4337 Value *NotX = Builder.CreateNot(V: X, Name: "not." + X->getName());
4338 Value *Or = Builder.CreateLogicalOr(Cond1: NotX, Cond2: Y);
4339
4340 // Set weights for the new OR select instruction too.
4341 if (auto *OrInst = dyn_cast<Instruction>(Val: Or)) {
4342 if (auto *CondInst = dyn_cast<Instruction>(Val: Cond)) {
4343 SmallVector<uint32_t> Weights;
4344 if (extractBranchWeights(I: *CondInst, Weights)) {
4345 assert(Weights.size() == 2 && "Unexpected number of branch weights!");
4346 std::swap(a&: Weights[0], b&: Weights[1]);
4347 setBranchWeights(I&: *OrInst, Weights, /*IsExpected=*/false);
4348 }
4349 }
4350 }
4351 BI.swapSuccessors();
4352 if (BPI)
4353 BPI->swapSuccEdgesProbabilities(Src: BI.getParent());
4354 return replaceOperand(I&: BI, OpNum: 0, V: Or);
4355 }
4356
4357 // If the condition is irrelevant, remove the use so that other
4358 // transforms on the condition become more effective.
4359 if (!isa<ConstantInt>(Val: Cond) && BI.getSuccessor(i: 0) == BI.getSuccessor(i: 1))
4360 return replaceOperand(I&: BI, OpNum: 0, V: ConstantInt::getFalse(Ty: Cond->getType()));
4361
4362 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
4363 CmpPredicate Pred;
4364 if (match(V: Cond, P: m_OneUse(SubPattern: m_FCmp(Pred, L: m_Value(), R: m_Value()))) &&
4365 !isCanonicalPredicate(Pred)) {
4366 // Swap destinations and condition.
4367 auto *Cmp = cast<CmpInst>(Val: Cond);
4368 Cmp->setPredicate(CmpInst::getInversePredicate(pred: Pred));
4369 BI.swapSuccessors();
4370 if (BPI)
4371 BPI->swapSuccEdgesProbabilities(Src: BI.getParent());
4372 Worklist.push(I: Cmp);
4373 return &BI;
4374 }
4375
4376 if (isa<UndefValue>(Val: Cond)) {
4377 handlePotentiallyDeadSuccessors(BB: BI.getParent(), /*LiveSucc*/ nullptr);
4378 return nullptr;
4379 }
4380 if (auto *CI = dyn_cast<ConstantInt>(Val: Cond)) {
4381 handlePotentiallyDeadSuccessors(BB: BI.getParent(),
4382 LiveSucc: BI.getSuccessor(i: !CI->getZExtValue()));
4383 return nullptr;
4384 }
4385
4386 // Replace all dominated uses of the condition with true/false
4387 // Ignore constant expressions to avoid iterating over uses on other
4388 // functions.
4389 if (!isa<Constant>(Val: Cond) && BI.getSuccessor(i: 0) != BI.getSuccessor(i: 1)) {
4390 for (auto &U : make_early_inc_range(Range: Cond->uses())) {
4391 BasicBlockEdge Edge0(BI.getParent(), BI.getSuccessor(i: 0));
4392 if (DT.dominates(BBE: Edge0, U)) {
4393 replaceUse(U, NewValue: ConstantInt::getTrue(Ty: Cond->getType()));
4394 addToWorklist(I: cast<Instruction>(Val: U.getUser()));
4395 continue;
4396 }
4397 BasicBlockEdge Edge1(BI.getParent(), BI.getSuccessor(i: 1));
4398 if (DT.dominates(BBE: Edge1, U)) {
4399 replaceUse(U, NewValue: ConstantInt::getFalse(Ty: Cond->getType()));
4400 addToWorklist(I: cast<Instruction>(Val: U.getUser()));
4401 }
4402 }
4403 }
4404
4405 DC.registerBranch(BI: &BI);
4406 return nullptr;
4407}
4408
4409// Replaces (switch (select cond, X, C)/(select cond, C, X)) with (switch X) if
4410// we can prove that both (switch C) and (switch X) go to the default when cond
4411// is false/true.
4412static Value *simplifySwitchOnSelectUsingRanges(SwitchInst &SI,
4413 SelectInst *Select,
4414 bool IsTrueArm) {
4415 unsigned CstOpIdx = IsTrueArm ? 1 : 2;
4416 auto *C = dyn_cast<ConstantInt>(Val: Select->getOperand(i_nocapture: CstOpIdx));
4417 if (!C)
4418 return nullptr;
4419
4420 BasicBlock *CstBB = SI.findCaseValue(C)->getCaseSuccessor();
4421 if (CstBB != SI.getDefaultDest())
4422 return nullptr;
4423 Value *X = Select->getOperand(i_nocapture: 3 - CstOpIdx);
4424 CmpPredicate Pred;
4425 const APInt *RHSC;
4426 if (!match(V: Select->getCondition(),
4427 P: m_ICmp(Pred, L: m_Specific(V: X), R: m_APInt(Res&: RHSC))))
4428 return nullptr;
4429 if (IsTrueArm)
4430 Pred = ICmpInst::getInversePredicate(pred: Pred);
4431
4432 // See whether we can replace the select with X
4433 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *RHSC);
4434 for (auto Case : SI.cases())
4435 if (!CR.contains(Val: Case.getCaseValue()->getValue()))
4436 return nullptr;
4437
4438 return X;
4439}
4440
4441Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) {
4442 Value *Cond = SI.getCondition();
4443 Value *Op0;
4444 const APInt *CondOpC;
4445 using InvertFn = std::function<APInt(const APInt &Case, const APInt &C)>;
4446
4447 auto MaybeInvertible = [&](Value *Cond) -> InvertFn {
4448 if (match(V: Cond, P: m_Add(L: m_Value(V&: Op0), R: m_APInt(Res&: CondOpC))))
4449 // Change 'switch (X+C) case Case:' into 'switch (X) case Case-C'.
4450 return [](const APInt &Case, const APInt &C) { return Case - C; };
4451
4452 if (match(V: Cond, P: m_Sub(L: m_APInt(Res&: CondOpC), R: m_Value(V&: Op0))))
4453 // Change 'switch (C-X) case Case:' into 'switch (X) case C-Case'.
4454 return [](const APInt &Case, const APInt &C) { return C - Case; };
4455
4456 if (match(V: Cond, P: m_Xor(L: m_Value(V&: Op0), R: m_APInt(Res&: CondOpC))) &&
4457 !CondOpC->isMinSignedValue() && !CondOpC->isMaxSignedValue())
4458 // Change 'switch (X^C) case Case:' into 'switch (X) case Case^C'.
4459 // Prevent creation of large case values by excluding extremes.
4460 return [](const APInt &Case, const APInt &C) { return Case ^ C; };
4461
4462 return nullptr;
4463 };
4464
4465 // Attempt to invert and simplify the switch condition, as long as the
4466 // condition is not used further, as it may not be profitable otherwise.
4467 if (auto InvertFn = MaybeInvertible(Cond); InvertFn && Cond->hasOneUse()) {
4468 for (auto &Case : SI.cases()) {
4469 const APInt &New = InvertFn(Case.getCaseValue()->getValue(), *CondOpC);
4470 Case.setValue(ConstantInt::get(Context&: SI.getContext(), V: New));
4471 }
4472 return replaceOperand(I&: SI, OpNum: 0, V: Op0);
4473 }
4474
4475 uint64_t ShiftAmt;
4476 if (match(V: Cond, P: m_Shl(L: m_Value(V&: Op0), R: m_ConstantInt(V&: ShiftAmt))) &&
4477 ShiftAmt < Op0->getType()->getScalarSizeInBits() &&
4478 all_of(Range: SI.cases(), P: [&](const auto &Case) {
4479 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
4480 })) {
4481 // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.
4482 OverflowingBinaryOperator *Shl = cast<OverflowingBinaryOperator>(Val: Cond);
4483 if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||
4484 Shl->hasOneUse()) {
4485 Value *NewCond = Op0;
4486 if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {
4487 // If the shift may wrap, we need to mask off the shifted bits.
4488 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
4489 NewCond = Builder.CreateAnd(
4490 LHS: Op0, RHS: APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - ShiftAmt));
4491 }
4492 for (auto Case : SI.cases()) {
4493 const APInt &CaseVal = Case.getCaseValue()->getValue();
4494 APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)
4495 : CaseVal.lshr(shiftAmt: ShiftAmt);
4496 Case.setValue(ConstantInt::get(Context&: SI.getContext(), V: ShiftedCase));
4497 }
4498 return replaceOperand(I&: SI, OpNum: 0, V: NewCond);
4499 }
4500 }
4501
4502 // Fold switch(zext/sext(X)) into switch(X) if possible.
4503 if (match(V: Cond, P: m_ZExtOrSExt(Op: m_Value(V&: Op0)))) {
4504 bool IsZExt = isa<ZExtInst>(Val: Cond);
4505 Type *SrcTy = Op0->getType();
4506 unsigned NewWidth = SrcTy->getScalarSizeInBits();
4507
4508 if (all_of(Range: SI.cases(), P: [&](const auto &Case) {
4509 const APInt &CaseVal = Case.getCaseValue()->getValue();
4510 return IsZExt ? CaseVal.isIntN(N: NewWidth)
4511 : CaseVal.isSignedIntN(N: NewWidth);
4512 })) {
4513 for (auto &Case : SI.cases()) {
4514 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(width: NewWidth);
4515 Case.setValue(ConstantInt::get(Context&: SI.getContext(), V: TruncatedCase));
4516 }
4517 return replaceOperand(I&: SI, OpNum: 0, V: Op0);
4518 }
4519 }
4520
4521 // Fold switch(select cond, X, Y) into switch(X/Y) if possible
4522 if (auto *Select = dyn_cast<SelectInst>(Val: Cond)) {
4523 if (Value *V =
4524 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/true))
4525 return replaceOperand(I&: SI, OpNum: 0, V);
4526 if (Value *V =
4527 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/false))
4528 return replaceOperand(I&: SI, OpNum: 0, V);
4529 }
4530
4531 KnownBits Known = computeKnownBits(V: Cond, CtxI: &SI);
4532 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
4533 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
4534
4535 // Compute the number of leading bits we can ignore.
4536 // TODO: A better way to determine this would use ComputeNumSignBits().
4537 for (const auto &C : SI.cases()) {
4538 LeadingKnownZeros =
4539 std::min(a: LeadingKnownZeros, b: C.getCaseValue()->getValue().countl_zero());
4540 LeadingKnownOnes =
4541 std::min(a: LeadingKnownOnes, b: C.getCaseValue()->getValue().countl_one());
4542 }
4543
4544 unsigned NewWidth = Known.getBitWidth() - std::max(a: LeadingKnownZeros, b: LeadingKnownOnes);
4545
4546 // Shrink the condition operand if the new type is smaller than the old type.
4547 // But do not shrink to a non-standard type, because backend can't generate
4548 // good code for that yet.
4549 // TODO: We can make it aggressive again after fixing PR39569.
4550 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
4551 shouldChangeType(FromWidth: Known.getBitWidth(), ToWidth: NewWidth)) {
4552 IntegerType *Ty = IntegerType::get(C&: SI.getContext(), NumBits: NewWidth);
4553 Builder.SetInsertPoint(&SI);
4554 Value *NewCond = Builder.CreateTrunc(V: Cond, DestTy: Ty, Name: "trunc");
4555
4556 for (auto Case : SI.cases()) {
4557 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(width: NewWidth);
4558 Case.setValue(ConstantInt::get(Context&: SI.getContext(), V: TruncatedCase));
4559 }
4560 return replaceOperand(I&: SI, OpNum: 0, V: NewCond);
4561 }
4562
4563 if (isa<UndefValue>(Val: Cond)) {
4564 handlePotentiallyDeadSuccessors(BB: SI.getParent(), /*LiveSucc*/ nullptr);
4565 return nullptr;
4566 }
4567 if (auto *CI = dyn_cast<ConstantInt>(Val: Cond)) {
4568 handlePotentiallyDeadSuccessors(BB: SI.getParent(),
4569 LiveSucc: SI.findCaseValue(C: CI)->getCaseSuccessor());
4570 return nullptr;
4571 }
4572
4573 return nullptr;
4574}
4575
4576Instruction *
4577InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
4578 auto *WO = dyn_cast<WithOverflowInst>(Val: EV.getAggregateOperand());
4579 if (!WO)
4580 return nullptr;
4581
4582 Intrinsic::ID OvID = WO->getIntrinsicID();
4583 const APInt *C = nullptr;
4584 if (match(V: WO->getRHS(), P: m_APIntAllowPoison(Res&: C))) {
4585 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
4586 OvID == Intrinsic::umul_with_overflow)) {
4587 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
4588 if (C->isAllOnes())
4589 return BinaryOperator::CreateNeg(Op: WO->getLHS());
4590 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
4591 if (C->isPowerOf2()) {
4592 return BinaryOperator::CreateShl(
4593 V1: WO->getLHS(),
4594 V2: ConstantInt::get(Ty: WO->getLHS()->getType(), V: C->logBase2()));
4595 }
4596 }
4597 }
4598
4599 // We're extracting from an overflow intrinsic. See if we're the only user.
4600 // That allows us to simplify multiple result intrinsics to simpler things
4601 // that just get one value.
4602 if (!WO->hasOneUse())
4603 return nullptr;
4604
4605 // Check if we're grabbing only the result of a 'with overflow' intrinsic
4606 // and replace it with a traditional binary instruction.
4607 if (*EV.idx_begin() == 0) {
4608 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4609 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
4610 // Replace the old instruction's uses with poison.
4611 replaceInstUsesWith(I&: *WO, V: PoisonValue::get(T: WO->getType()));
4612 eraseInstFromFunction(I&: *WO);
4613 return BinaryOperator::Create(Op: BinOp, S1: LHS, S2: RHS);
4614 }
4615
4616 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
4617
4618 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
4619 if (OvID == Intrinsic::usub_with_overflow)
4620 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
4621
4622 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
4623 // +1 is not possible because we assume signed values.
4624 if (OvID == Intrinsic::smul_with_overflow &&
4625 WO->getLHS()->getType()->isIntOrIntVectorTy(BitWidth: 1))
4626 return BinaryOperator::CreateAnd(V1: WO->getLHS(), V2: WO->getRHS());
4627
4628 // extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-1
4629 if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
4630 unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
4631 // Only handle even bitwidths for performance reasons.
4632 if (BitWidth % 2 == 0)
4633 return new ICmpInst(
4634 ICmpInst::ICMP_UGT, WO->getLHS(),
4635 ConstantInt::get(Ty: WO->getLHS()->getType(),
4636 V: APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth / 2)));
4637 }
4638
4639 // If only the overflow result is used, and the right hand side is a
4640 // constant (or constant splat), we can remove the intrinsic by directly
4641 // checking for overflow.
4642 if (C) {
4643 // Compute the no-wrap range for LHS given RHS=C, then construct an
4644 // equivalent icmp, potentially using an offset.
4645 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
4646 BinOp: WO->getBinaryOp(), Other: *C, NoWrapKind: WO->getNoWrapKind());
4647
4648 CmpInst::Predicate Pred;
4649 APInt NewRHSC, Offset;
4650 NWR.getEquivalentICmp(Pred, RHS&: NewRHSC, Offset);
4651 auto *OpTy = WO->getRHS()->getType();
4652 auto *NewLHS = WO->getLHS();
4653 if (Offset != 0)
4654 NewLHS = Builder.CreateAdd(LHS: NewLHS, RHS: ConstantInt::get(Ty: OpTy, V: Offset));
4655 return new ICmpInst(ICmpInst::getInversePredicate(pred: Pred), NewLHS,
4656 ConstantInt::get(Ty: OpTy, V: NewRHSC));
4657 }
4658
4659 return nullptr;
4660}
4661
4662static Value *foldFrexpOfSelect(ExtractValueInst &EV, IntrinsicInst *FrexpCall,
4663 SelectInst *SelectInst,
4664 InstCombiner::BuilderTy &Builder) {
4665 // Helper to fold frexp of select to select of frexp.
4666
4667 if (!SelectInst->hasOneUse() || !FrexpCall->hasOneUse())
4668 return nullptr;
4669 Value *Cond = SelectInst->getCondition();
4670 Value *TrueVal = SelectInst->getTrueValue();
4671 Value *FalseVal = SelectInst->getFalseValue();
4672
4673 const APFloat *ConstVal = nullptr;
4674 Value *VarOp = nullptr;
4675 bool ConstIsTrue = false;
4676
4677 if (match(V: TrueVal, P: m_APFloat(Res&: ConstVal))) {
4678 VarOp = FalseVal;
4679 ConstIsTrue = true;
4680 } else if (match(V: FalseVal, P: m_APFloat(Res&: ConstVal))) {
4681 VarOp = TrueVal;
4682 ConstIsTrue = false;
4683 } else {
4684 return nullptr;
4685 }
4686
4687 Builder.SetInsertPoint(&EV);
4688
4689 CallInst *NewFrexp =
4690 Builder.CreateCall(Callee: FrexpCall->getCalledFunction(), Args: {VarOp}, Name: "frexp");
4691 NewFrexp->copyIRFlags(V: FrexpCall);
4692
4693 Value *NewEV = Builder.CreateExtractValue(Agg: NewFrexp, Idxs: 0, Name: "mantissa");
4694
4695 int Exp;
4696 APFloat Mantissa = frexp(X: *ConstVal, Exp, RM: APFloat::rmNearestTiesToEven);
4697
4698 Constant *ConstantMantissa = ConstantFP::get(Ty: TrueVal->getType(), V: Mantissa);
4699
4700 Value *NewSel = Builder.CreateSelectFMF(
4701 C: Cond, True: ConstIsTrue ? ConstantMantissa : NewEV,
4702 False: ConstIsTrue ? NewEV : ConstantMantissa, FMFSource: SelectInst, Name: "select.frexp");
4703 return NewSel;
4704}
4705Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) {
4706 Value *Agg = EV.getAggregateOperand();
4707
4708 if (!EV.hasIndices())
4709 return replaceInstUsesWith(I&: EV, V: Agg);
4710
4711 if (Value *V = simplifyExtractValueInst(Agg, Idxs: EV.getIndices(),
4712 Q: SQ.getWithInstruction(I: &EV)))
4713 return replaceInstUsesWith(I&: EV, V);
4714
4715 Value *Cond, *TrueVal, *FalseVal;
4716 if (match(V: &EV, P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::frexp>(Ops: m_Select(
4717 C: m_Value(V&: Cond), L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal)))))) {
4718 auto *SelInst =
4719 cast<SelectInst>(Val: cast<IntrinsicInst>(Val: Agg)->getArgOperand(i: 0));
4720 if (Value *Result =
4721 foldFrexpOfSelect(EV, FrexpCall: cast<IntrinsicInst>(Val: Agg), SelectInst: SelInst, Builder))
4722 return replaceInstUsesWith(I&: EV, V: Result);
4723 }
4724 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Val: Agg)) {
4725 // We're extracting from an insertvalue instruction, compare the indices
4726 const unsigned *exti, *exte, *insi, *inse;
4727 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
4728 exte = EV.idx_end(), inse = IV->idx_end();
4729 exti != exte && insi != inse;
4730 ++exti, ++insi) {
4731 if (*insi != *exti)
4732 // The insert and extract both reference distinctly different elements.
4733 // This means the extract is not influenced by the insert, and we can
4734 // replace the aggregate operand of the extract with the aggregate
4735 // operand of the insert. i.e., replace
4736 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4737 // %E = extractvalue { i32, { i32 } } %I, 0
4738 // with
4739 // %E = extractvalue { i32, { i32 } } %A, 0
4740 return ExtractValueInst::Create(Agg: IV->getAggregateOperand(),
4741 Idxs: EV.getIndices());
4742 }
4743 if (exti == exte && insi == inse)
4744 // Both iterators are at the end: Index lists are identical. Replace
4745 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4746 // %C = extractvalue { i32, { i32 } } %B, 1, 0
4747 // with "i32 42"
4748 return replaceInstUsesWith(I&: EV, V: IV->getInsertedValueOperand());
4749 if (exti == exte) {
4750 // The extract list is a prefix of the insert list. i.e. replace
4751 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4752 // %E = extractvalue { i32, { i32 } } %I, 1
4753 // with
4754 // %X = extractvalue { i32, { i32 } } %A, 1
4755 // %E = insertvalue { i32 } %X, i32 42, 0
4756 // by switching the order of the insert and extract (though the
4757 // insertvalue should be left in, since it may have other uses).
4758 Value *NewEV = Builder.CreateExtractValue(Agg: IV->getAggregateOperand(),
4759 Idxs: EV.getIndices());
4760 return InsertValueInst::Create(Agg: NewEV, Val: IV->getInsertedValueOperand(),
4761 Idxs: ArrayRef(insi, inse));
4762 }
4763 if (insi == inse)
4764 // The insert list is a prefix of the extract list
4765 // We can simply remove the common indices from the extract and make it
4766 // operate on the inserted value instead of the insertvalue result.
4767 // i.e., replace
4768 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4769 // %E = extractvalue { i32, { i32 } } %I, 1, 0
4770 // with
4771 // %E extractvalue { i32 } { i32 42 }, 0
4772 return ExtractValueInst::Create(Agg: IV->getInsertedValueOperand(),
4773 Idxs: ArrayRef(exti, exte));
4774 }
4775
4776 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
4777 return R;
4778
4779 if (LoadInst *L = dyn_cast<LoadInst>(Val: Agg)) {
4780 // Bail out if the aggregate contains scalable vector type
4781 if (auto *STy = dyn_cast<StructType>(Val: Agg->getType());
4782 STy && STy->isScalableTy())
4783 return nullptr;
4784
4785 // If the (non-volatile) load only has one use, we can rewrite this to a
4786 // load from a GEP. This reduces the size of the load. If a load is used
4787 // only by extractvalue instructions then this either must have been
4788 // optimized before, or it is a struct with padding, in which case we
4789 // don't want to do the transformation as it loses padding knowledge.
4790 if (L->isSimple() && L->hasOneUse()) {
4791 // extractvalue has integer indices, getelementptr has Value*s. Convert.
4792 SmallVector<Value*, 4> Indices;
4793 // Prefix an i32 0 since we need the first element.
4794 Indices.push_back(Elt: Builder.getInt32(C: 0));
4795 for (unsigned Idx : EV.indices())
4796 Indices.push_back(Elt: Builder.getInt32(C: Idx));
4797
4798 // We need to insert these at the location of the old load, not at that of
4799 // the extractvalue.
4800 Builder.SetInsertPoint(L);
4801 Value *GEP = Builder.CreateInBoundsGEP(Ty: L->getType(),
4802 Ptr: L->getPointerOperand(), IdxList: Indices);
4803 Instruction *NL = Builder.CreateLoad(Ty: EV.getType(), Ptr: GEP);
4804 // Whatever aliasing information we had for the orignal load must also
4805 // hold for the smaller load, so propagate the annotations.
4806 NL->setAAMetadata(L->getAAMetadata());
4807 // Returning the load directly will cause the main loop to insert it in
4808 // the wrong spot, so use replaceInstUsesWith().
4809 return replaceInstUsesWith(I&: EV, V: NL);
4810 }
4811 }
4812
4813 if (auto *PN = dyn_cast<PHINode>(Val: Agg))
4814 if (Instruction *Res = foldOpIntoPhi(I&: EV, PN))
4815 return Res;
4816
4817 // Canonicalize extract (select Cond, TV, FV)
4818 // -> select cond, (extract TV), (extract FV)
4819 if (auto *SI = dyn_cast<SelectInst>(Val: Agg))
4820 if (Instruction *R = FoldOpIntoSelect(Op&: EV, SI, /*FoldWithMultiUse=*/true))
4821 return R;
4822
4823 // We could simplify extracts from other values. Note that nested extracts may
4824 // already be simplified implicitly by the above: extract (extract (insert) )
4825 // will be translated into extract ( insert ( extract ) ) first and then just
4826 // the value inserted, if appropriate. Similarly for extracts from single-use
4827 // loads: extract (extract (load)) will be translated to extract (load (gep))
4828 // and if again single-use then via load (gep (gep)) to load (gep).
4829 // However, double extracts from e.g. function arguments or return values
4830 // aren't handled yet.
4831 return nullptr;
4832}
4833
4834/// Return 'true' if the given typeinfo will match anything.
4835static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
4836 switch (Personality) {
4837 case EHPersonality::GNU_C:
4838 case EHPersonality::GNU_C_SjLj:
4839 case EHPersonality::Rust:
4840 // The GCC C EH and Rust personality only exists to support cleanups, so
4841 // it's not clear what the semantics of catch clauses are.
4842 return false;
4843 case EHPersonality::Unknown:
4844 return false;
4845 case EHPersonality::GNU_Ada:
4846 // While __gnat_all_others_value will match any Ada exception, it doesn't
4847 // match foreign exceptions (or didn't, before gcc-4.7).
4848 return false;
4849 case EHPersonality::GNU_CXX:
4850 case EHPersonality::GNU_CXX_SjLj:
4851 case EHPersonality::GNU_ObjC:
4852 case EHPersonality::MSVC_X86SEH:
4853 case EHPersonality::MSVC_TableSEH:
4854 case EHPersonality::MSVC_CXX:
4855 case EHPersonality::CoreCLR:
4856 case EHPersonality::Wasm_CXX:
4857 case EHPersonality::XL_CXX:
4858 case EHPersonality::ZOS_CXX:
4859 case EHPersonality::Wasm_D:
4860 return isa<ConstantPointerNull>(Val: TypeInfo);
4861 }
4862 llvm_unreachable("invalid enum");
4863}
4864
4865static bool shorter_filter(const Value *LHS, const Value *RHS) {
4866 return
4867 cast<ArrayType>(Val: LHS->getType())->getNumElements()
4868 <
4869 cast<ArrayType>(Val: RHS->getType())->getNumElements();
4870}
4871
4872Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {
4873 // The logic here should be correct for any real-world personality function.
4874 // However if that turns out not to be true, the offending logic can always
4875 // be conditioned on the personality function, like the catch-all logic is.
4876 EHPersonality Personality =
4877 classifyEHPersonality(Pers: LI.getParent()->getParent()->getPersonalityFn());
4878
4879 // Simplify the list of clauses, eg by removing repeated catch clauses
4880 // (these are often created by inlining).
4881 bool MakeNewInstruction = false; // If true, recreate using the following:
4882 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
4883 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
4884
4885 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
4886 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
4887 bool isLastClause = i + 1 == e;
4888 if (LI.isCatch(Idx: i)) {
4889 // A catch clause.
4890 Constant *CatchClause = LI.getClause(Idx: i);
4891 Constant *TypeInfo = CatchClause->stripPointerCasts();
4892
4893 // If we already saw this clause, there is no point in having a second
4894 // copy of it.
4895 if (AlreadyCaught.insert(Ptr: TypeInfo).second) {
4896 // This catch clause was not already seen.
4897 NewClauses.push_back(Elt: CatchClause);
4898 } else {
4899 // Repeated catch clause - drop the redundant copy.
4900 MakeNewInstruction = true;
4901 }
4902
4903 // If this is a catch-all then there is no point in keeping any following
4904 // clauses or marking the landingpad as having a cleanup.
4905 if (isCatchAll(Personality, TypeInfo)) {
4906 if (!isLastClause)
4907 MakeNewInstruction = true;
4908 CleanupFlag = false;
4909 break;
4910 }
4911 } else {
4912 // A filter clause. If any of the filter elements were already caught
4913 // then they can be dropped from the filter. It is tempting to try to
4914 // exploit the filter further by saying that any typeinfo that does not
4915 // occur in the filter can't be caught later (and thus can be dropped).
4916 // However this would be wrong, since typeinfos can match without being
4917 // equal (for example if one represents a C++ class, and the other some
4918 // class derived from it).
4919 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
4920 Constant *FilterClause = LI.getClause(Idx: i);
4921 ArrayType *FilterType = cast<ArrayType>(Val: FilterClause->getType());
4922 unsigned NumTypeInfos = FilterType->getNumElements();
4923
4924 // An empty filter catches everything, so there is no point in keeping any
4925 // following clauses or marking the landingpad as having a cleanup. By
4926 // dealing with this case here the following code is made a bit simpler.
4927 if (!NumTypeInfos) {
4928 NewClauses.push_back(Elt: FilterClause);
4929 if (!isLastClause)
4930 MakeNewInstruction = true;
4931 CleanupFlag = false;
4932 break;
4933 }
4934
4935 bool MakeNewFilter = false; // If true, make a new filter.
4936 SmallVector<Constant *, 16> NewFilterElts; // New elements.
4937 if (isa<ConstantAggregateZero>(Val: FilterClause)) {
4938 // Not an empty filter - it contains at least one null typeinfo.
4939 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
4940 Constant *TypeInfo =
4941 Constant::getNullValue(Ty: FilterType->getElementType());
4942 // If this typeinfo is a catch-all then the filter can never match.
4943 if (isCatchAll(Personality, TypeInfo)) {
4944 // Throw the filter away.
4945 MakeNewInstruction = true;
4946 continue;
4947 }
4948
4949 // There is no point in having multiple copies of this typeinfo, so
4950 // discard all but the first copy if there is more than one.
4951 NewFilterElts.push_back(Elt: TypeInfo);
4952 if (NumTypeInfos > 1)
4953 MakeNewFilter = true;
4954 } else {
4955 ConstantArray *Filter = cast<ConstantArray>(Val: FilterClause);
4956 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
4957 NewFilterElts.reserve(N: NumTypeInfos);
4958
4959 // Remove any filter elements that were already caught or that already
4960 // occurred in the filter. While there, see if any of the elements are
4961 // catch-alls. If so, the filter can be discarded.
4962 bool SawCatchAll = false;
4963 for (unsigned j = 0; j != NumTypeInfos; ++j) {
4964 Constant *Elt = Filter->getOperand(i_nocapture: j);
4965 Constant *TypeInfo = Elt->stripPointerCasts();
4966 if (isCatchAll(Personality, TypeInfo)) {
4967 // This element is a catch-all. Bail out, noting this fact.
4968 SawCatchAll = true;
4969 break;
4970 }
4971
4972 // Even if we've seen a type in a catch clause, we don't want to
4973 // remove it from the filter. An unexpected type handler may be
4974 // set up for a call site which throws an exception of the same
4975 // type caught. In order for the exception thrown by the unexpected
4976 // handler to propagate correctly, the filter must be correctly
4977 // described for the call site.
4978 //
4979 // Example:
4980 //
4981 // void unexpected() { throw 1;}
4982 // void foo() throw (int) {
4983 // std::set_unexpected(unexpected);
4984 // try {
4985 // throw 2.0;
4986 // } catch (int i) {}
4987 // }
4988
4989 // There is no point in having multiple copies of the same typeinfo in
4990 // a filter, so only add it if we didn't already.
4991 if (SeenInFilter.insert(Ptr: TypeInfo).second)
4992 NewFilterElts.push_back(Elt: cast<Constant>(Val: Elt));
4993 }
4994 // A filter containing a catch-all cannot match anything by definition.
4995 if (SawCatchAll) {
4996 // Throw the filter away.
4997 MakeNewInstruction = true;
4998 continue;
4999 }
5000
5001 // If we dropped something from the filter, make a new one.
5002 if (NewFilterElts.size() < NumTypeInfos)
5003 MakeNewFilter = true;
5004 }
5005 if (MakeNewFilter) {
5006 FilterType = ArrayType::get(ElementType: FilterType->getElementType(),
5007 NumElements: NewFilterElts.size());
5008 FilterClause = ConstantArray::get(T: FilterType, V: NewFilterElts);
5009 MakeNewInstruction = true;
5010 }
5011
5012 NewClauses.push_back(Elt: FilterClause);
5013
5014 // If the new filter is empty then it will catch everything so there is
5015 // no point in keeping any following clauses or marking the landingpad
5016 // as having a cleanup. The case of the original filter being empty was
5017 // already handled above.
5018 if (MakeNewFilter && !NewFilterElts.size()) {
5019 assert(MakeNewInstruction && "New filter but not a new instruction!");
5020 CleanupFlag = false;
5021 break;
5022 }
5023 }
5024 }
5025
5026 // If several filters occur in a row then reorder them so that the shortest
5027 // filters come first (those with the smallest number of elements). This is
5028 // advantageous because shorter filters are more likely to match, speeding up
5029 // unwinding, but mostly because it increases the effectiveness of the other
5030 // filter optimizations below.
5031 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
5032 unsigned j;
5033 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
5034 for (j = i; j != e; ++j)
5035 if (!isa<ArrayType>(Val: NewClauses[j]->getType()))
5036 break;
5037
5038 // Check whether the filters are already sorted by length. We need to know
5039 // if sorting them is actually going to do anything so that we only make a
5040 // new landingpad instruction if it does.
5041 for (unsigned k = i; k + 1 < j; ++k)
5042 if (shorter_filter(LHS: NewClauses[k+1], RHS: NewClauses[k])) {
5043 // Not sorted, so sort the filters now. Doing an unstable sort would be
5044 // correct too but reordering filters pointlessly might confuse users.
5045 std::stable_sort(first: NewClauses.begin() + i, last: NewClauses.begin() + j,
5046 comp: shorter_filter);
5047 MakeNewInstruction = true;
5048 break;
5049 }
5050
5051 // Look for the next batch of filters.
5052 i = j + 1;
5053 }
5054
5055 // If typeinfos matched if and only if equal, then the elements of a filter L
5056 // that occurs later than a filter F could be replaced by the intersection of
5057 // the elements of F and L. In reality two typeinfos can match without being
5058 // equal (for example if one represents a C++ class, and the other some class
5059 // derived from it) so it would be wrong to perform this transform in general.
5060 // However the transform is correct and useful if F is a subset of L. In that
5061 // case L can be replaced by F, and thus removed altogether since repeating a
5062 // filter is pointless. So here we look at all pairs of filters F and L where
5063 // L follows F in the list of clauses, and remove L if every element of F is
5064 // an element of L. This can occur when inlining C++ functions with exception
5065 // specifications.
5066 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
5067 // Examine each filter in turn.
5068 Value *Filter = NewClauses[i];
5069 ArrayType *FTy = dyn_cast<ArrayType>(Val: Filter->getType());
5070 if (!FTy)
5071 // Not a filter - skip it.
5072 continue;
5073 unsigned FElts = FTy->getNumElements();
5074 // Examine each filter following this one. Doing this backwards means that
5075 // we don't have to worry about filters disappearing under us when removed.
5076 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
5077 Value *LFilter = NewClauses[j];
5078 ArrayType *LTy = dyn_cast<ArrayType>(Val: LFilter->getType());
5079 if (!LTy)
5080 // Not a filter - skip it.
5081 continue;
5082 // If Filter is a subset of LFilter, i.e. every element of Filter is also
5083 // an element of LFilter, then discard LFilter.
5084 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
5085 // If Filter is empty then it is a subset of LFilter.
5086 if (!FElts) {
5087 // Discard LFilter.
5088 NewClauses.erase(CI: J);
5089 MakeNewInstruction = true;
5090 // Move on to the next filter.
5091 continue;
5092 }
5093 unsigned LElts = LTy->getNumElements();
5094 // If Filter is longer than LFilter then it cannot be a subset of it.
5095 if (FElts > LElts)
5096 // Move on to the next filter.
5097 continue;
5098 // At this point we know that LFilter has at least one element.
5099 if (isa<ConstantAggregateZero>(Val: LFilter)) { // LFilter only contains zeros.
5100 // Filter is a subset of LFilter iff Filter contains only zeros (as we
5101 // already know that Filter is not longer than LFilter).
5102 if (isa<ConstantAggregateZero>(Val: Filter)) {
5103 assert(FElts <= LElts && "Should have handled this case earlier!");
5104 // Discard LFilter.
5105 NewClauses.erase(CI: J);
5106 MakeNewInstruction = true;
5107 }
5108 // Move on to the next filter.
5109 continue;
5110 }
5111 ConstantArray *LArray = cast<ConstantArray>(Val: LFilter);
5112 if (isa<ConstantAggregateZero>(Val: Filter)) { // Filter only contains zeros.
5113 // Since Filter is non-empty and contains only zeros, it is a subset of
5114 // LFilter iff LFilter contains a zero.
5115 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
5116 for (unsigned l = 0; l != LElts; ++l)
5117 if (isa<ConstantPointerNull>(Val: LArray->getOperand(i_nocapture: l))) {
5118 // LFilter contains a zero - discard it.
5119 NewClauses.erase(CI: J);
5120 MakeNewInstruction = true;
5121 break;
5122 }
5123 // Move on to the next filter.
5124 continue;
5125 }
5126 // At this point we know that both filters are ConstantArrays. Loop over
5127 // operands to see whether every element of Filter is also an element of
5128 // LFilter. Since filters tend to be short this is probably faster than
5129 // using a method that scales nicely.
5130 ConstantArray *FArray = cast<ConstantArray>(Val: Filter);
5131 bool AllFound = true;
5132 for (unsigned f = 0; f != FElts; ++f) {
5133 Value *FTypeInfo = FArray->getOperand(i_nocapture: f)->stripPointerCasts();
5134 AllFound = false;
5135 for (unsigned l = 0; l != LElts; ++l) {
5136 Value *LTypeInfo = LArray->getOperand(i_nocapture: l)->stripPointerCasts();
5137 if (LTypeInfo == FTypeInfo) {
5138 AllFound = true;
5139 break;
5140 }
5141 }
5142 if (!AllFound)
5143 break;
5144 }
5145 if (AllFound) {
5146 // Discard LFilter.
5147 NewClauses.erase(CI: J);
5148 MakeNewInstruction = true;
5149 }
5150 // Move on to the next filter.
5151 }
5152 }
5153
5154 // If we changed any of the clauses, replace the old landingpad instruction
5155 // with a new one.
5156 if (MakeNewInstruction) {
5157 LandingPadInst *NLI = LandingPadInst::Create(RetTy: LI.getType(),
5158 NumReservedClauses: NewClauses.size());
5159 for (Constant *C : NewClauses)
5160 NLI->addClause(ClauseVal: C);
5161 // A landing pad with no clauses must have the cleanup flag set. It is
5162 // theoretically possible, though highly unlikely, that we eliminated all
5163 // clauses. If so, force the cleanup flag to true.
5164 if (NewClauses.empty())
5165 CleanupFlag = true;
5166 NLI->setCleanup(CleanupFlag);
5167 return NLI;
5168 }
5169
5170 // Even if none of the clauses changed, we may nonetheless have understood
5171 // that the cleanup flag is pointless. Clear it if so.
5172 if (LI.isCleanup() != CleanupFlag) {
5173 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
5174 LI.setCleanup(CleanupFlag);
5175 return &LI;
5176 }
5177
5178 return nullptr;
5179}
5180
5181Value *
5182InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst &OrigFI) {
5183 // Try to push freeze through instructions that propagate but don't produce
5184 // poison as far as possible. If an operand of freeze follows three
5185 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
5186 // guaranteed-non-poison operands then push the freeze through to the one
5187 // operand that is not guaranteed non-poison. The actual transform is as
5188 // follows.
5189 // Op1 = ... ; Op1 can be posion
5190 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
5191 // ; single guaranteed-non-poison operands
5192 // ... = Freeze(Op0)
5193 // =>
5194 // Op1 = ...
5195 // Op1.fr = Freeze(Op1)
5196 // ... = Inst(Op1.fr, NonPoisonOps...)
5197 auto *OrigOp = OrigFI.getOperand(i_nocapture: 0);
5198 auto *OrigOpInst = dyn_cast<Instruction>(Val: OrigOp);
5199
5200 // While we could change the other users of OrigOp to use freeze(OrigOp), that
5201 // potentially reduces their optimization potential, so let's only do this iff
5202 // the OrigOp is only used by the freeze.
5203 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(Val: OrigOp))
5204 return nullptr;
5205
5206 // We can't push the freeze through an instruction which can itself create
5207 // poison. If the only source of new poison is flags, we can simply
5208 // strip them (since we know the only use is the freeze and nothing can
5209 // benefit from them.)
5210 if (canCreateUndefOrPoison(Op: cast<Operator>(Val: OrigOp),
5211 /*ConsiderFlagsAndMetadata*/ false))
5212 return nullptr;
5213
5214 // If operand is guaranteed not to be poison, there is no need to add freeze
5215 // to the operand. So we first find the operand that is not guaranteed to be
5216 // poison.
5217 Value *MaybePoisonOperand = nullptr;
5218 for (Value *V : OrigOpInst->operands()) {
5219 if (isa<MetadataAsValue>(Val: V) || isGuaranteedNotToBeUndefOrPoison(V) ||
5220 // Treat identical operands as a single operand.
5221 (MaybePoisonOperand && MaybePoisonOperand == V))
5222 continue;
5223 if (!MaybePoisonOperand)
5224 MaybePoisonOperand = V;
5225 else
5226 return nullptr;
5227 }
5228
5229 OrigOpInst->dropPoisonGeneratingAnnotations();
5230
5231 // If all operands are guaranteed to be non-poison, we can drop freeze.
5232 if (!MaybePoisonOperand)
5233 return OrigOp;
5234
5235 Builder.SetInsertPoint(OrigOpInst);
5236 Value *FrozenMaybePoisonOperand = Builder.CreateFreeze(
5237 V: MaybePoisonOperand, Name: MaybePoisonOperand->getName() + ".fr");
5238
5239 OrigOpInst->replaceUsesOfWith(From: MaybePoisonOperand, To: FrozenMaybePoisonOperand);
5240 return OrigOp;
5241}
5242
5243Instruction *InstCombinerImpl::foldFreezeIntoRecurrence(FreezeInst &FI,
5244 PHINode *PN) {
5245 // Detect whether this is a recurrence with a start value and some number of
5246 // backedge values. We'll check whether we can push the freeze through the
5247 // backedge values (possibly dropping poison flags along the way) until we
5248 // reach the phi again. In that case, we can move the freeze to the start
5249 // value.
5250 Use *StartU = nullptr;
5251 SmallVector<Value *> Worklist;
5252 for (Use &U : PN->incoming_values()) {
5253 if (DT.dominates(A: PN->getParent(), B: PN->getIncomingBlock(U))) {
5254 // Add backedge value to worklist.
5255 Worklist.push_back(Elt: U.get());
5256 continue;
5257 }
5258
5259 // Don't bother handling multiple start values.
5260 if (StartU)
5261 return nullptr;
5262 StartU = &U;
5263 }
5264
5265 if (!StartU || Worklist.empty())
5266 return nullptr; // Not a recurrence.
5267
5268 Value *StartV = StartU->get();
5269 BasicBlock *StartBB = PN->getIncomingBlock(U: *StartU);
5270 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(V: StartV);
5271 // We can't insert freeze if the start value is the result of the
5272 // terminator (e.g. an invoke).
5273 if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
5274 return nullptr;
5275
5276 SmallPtrSet<Value *, 32> Visited;
5277 SmallVector<Instruction *> DropFlags;
5278 while (!Worklist.empty()) {
5279 Value *V = Worklist.pop_back_val();
5280 if (!Visited.insert(Ptr: V).second)
5281 continue;
5282
5283 if (Visited.size() > 32)
5284 return nullptr; // Limit the total number of values we inspect.
5285
5286 // Assume that PN is non-poison, because it will be after the transform.
5287 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
5288 continue;
5289
5290 Instruction *I = dyn_cast<Instruction>(Val: V);
5291 if (!I || canCreateUndefOrPoison(Op: cast<Operator>(Val: I),
5292 /*ConsiderFlagsAndMetadata*/ false))
5293 return nullptr;
5294
5295 DropFlags.push_back(Elt: I);
5296 append_range(C&: Worklist, R: I->operands());
5297 }
5298
5299 for (Instruction *I : DropFlags)
5300 I->dropPoisonGeneratingAnnotations();
5301
5302 if (StartNeedsFreeze) {
5303 Builder.SetInsertPoint(StartBB->getTerminator());
5304 Value *FrozenStartV = Builder.CreateFreeze(V: StartV,
5305 Name: StartV->getName() + ".fr");
5306 replaceUse(U&: *StartU, NewValue: FrozenStartV);
5307 }
5308 return replaceInstUsesWith(I&: FI, V: PN);
5309}
5310
5311bool InstCombinerImpl::freezeOtherUses(FreezeInst &FI) {
5312 Value *Op = FI.getOperand(i_nocapture: 0);
5313
5314 if (isa<Constant>(Val: Op) || Op->hasOneUse())
5315 return false;
5316
5317 // Move the freeze directly after the definition of its operand, so that
5318 // it dominates the maximum number of uses. Note that it may not dominate
5319 // *all* uses if the operand is an invoke/callbr and the use is in a phi on
5320 // the normal/default destination. This is why the domination check in the
5321 // replacement below is still necessary.
5322 BasicBlock::iterator MoveBefore;
5323 if (isa<Argument>(Val: Op)) {
5324 MoveBefore =
5325 FI.getFunction()->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();
5326 } else {
5327 auto MoveBeforeOpt = cast<Instruction>(Val: Op)->getInsertionPointAfterDef();
5328 if (!MoveBeforeOpt)
5329 return false;
5330 MoveBefore = *MoveBeforeOpt;
5331 }
5332
5333 // Re-point iterator to come after any debug-info records.
5334 MoveBefore.setHeadBit(false);
5335
5336 bool Changed = false;
5337 if (&FI != &*MoveBefore) {
5338 FI.moveBefore(BB&: *MoveBefore->getParent(), I: MoveBefore);
5339 Changed = true;
5340 }
5341
5342 SmallVector<User *> Users;
5343 Changed |= Op->replaceUsesWithIf(New: &FI, ShouldReplace: [&](Use &U) -> bool {
5344 if (!DT.dominates(Def: &FI, U))
5345 return false;
5346
5347 Users.push_back(Elt: U.getUser());
5348 return true;
5349 });
5350
5351 for (auto *U : Users) {
5352 // Re-queue U and its users: freezing U's operand can expose a fold on a
5353 // user of U (e.g. a freeze of U can now be pushed through it) that would
5354 // otherwise only fire on a later iteration, tripping the fixpoint verifier.
5355 auto *UI = cast<Instruction>(Val: U);
5356 Worklist.pushUsersToWorkList(I&: *UI);
5357 Worklist.push(I: UI);
5358 }
5359
5360 return Changed;
5361}
5362
5363// Check if any direct or bitcast user of this value is a shuffle instruction.
5364static bool isUsedWithinShuffleVector(Value *V) {
5365 for (auto *U : V->users()) {
5366 if (isa<ShuffleVectorInst>(Val: U))
5367 return true;
5368 else if (match(V: U, P: m_BitCast(Op: m_Specific(V))) && isUsedWithinShuffleVector(V: U))
5369 return true;
5370 }
5371 return false;
5372}
5373
5374Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {
5375 Value *Op0 = I.getOperand(i_nocapture: 0);
5376
5377 if (Value *V = simplifyFreezeInst(Op: Op0, Q: SQ.getWithInstruction(I: &I)))
5378 return replaceInstUsesWith(I, V);
5379
5380 // freeze (phi const, x) --> phi const, (freeze x)
5381 if (auto *PN = dyn_cast<PHINode>(Val: Op0)) {
5382 if (Instruction *NV = foldOpIntoPhi(I, PN))
5383 return NV;
5384 if (Instruction *NV = foldFreezeIntoRecurrence(FI&: I, PN))
5385 return NV;
5386 }
5387
5388 if (Value *NI = pushFreezeToPreventPoisonFromPropagating(OrigFI&: I))
5389 return replaceInstUsesWith(I, V: NI);
5390
5391 // If I is freeze(undef), check its uses and fold it to a fixed constant.
5392 // - or: pick -1
5393 // - select's condition: if the true value is constant, choose it by making
5394 // the condition true.
5395 // - phi: pick the common constant across operands
5396 // - default: pick 0
5397 //
5398 // Note that this transform is intentionally done here rather than
5399 // via an analysis in InstSimplify or at individual user sites. That is
5400 // because we must produce the same value for all uses of the freeze -
5401 // it's the reason "freeze" exists!
5402 //
5403 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
5404 // duplicating logic for binops at least.
5405 auto getUndefReplacement = [&](Type *Ty) {
5406 auto pickCommonConstantFromPHI = [](PHINode &PN) -> Value * {
5407 // phi(freeze(undef), C, C). Choose C for freeze so the PHI can be
5408 // removed.
5409 Constant *BestValue = nullptr;
5410 for (Value *V : PN.incoming_values()) {
5411 if (match(V, P: m_Freeze(Op: m_Undef())))
5412 continue;
5413
5414 Constant *C = dyn_cast<Constant>(Val: V);
5415 if (!C)
5416 return nullptr;
5417
5418 if (!isGuaranteedNotToBeUndefOrPoison(V: C))
5419 return nullptr;
5420
5421 if (BestValue && BestValue != C)
5422 return nullptr;
5423
5424 BestValue = C;
5425 }
5426 return BestValue;
5427 };
5428
5429 Value *NullValue = Constant::getNullValue(Ty);
5430 Value *BestValue = nullptr;
5431 for (auto *U : I.users()) {
5432 Value *V = NullValue;
5433 if (match(V: U, P: m_Or(L: m_Value(), R: m_Value())))
5434 V = ConstantInt::getAllOnesValue(Ty);
5435 else if (match(V: U, P: m_Select(C: m_Specific(V: &I), L: m_Constant(), R: m_Value())))
5436 V = ConstantInt::getTrue(Ty);
5437 else if (match(V: U, P: m_c_Select(L: m_Specific(V: &I), R: m_Value(V)))) {
5438 if (V == &I || !isGuaranteedNotToBeUndefOrPoison(V, AC: &AC, CtxI: &I, DT: &DT))
5439 V = NullValue;
5440 } else if (auto *PHI = dyn_cast<PHINode>(Val: U)) {
5441 if (Value *MaybeV = pickCommonConstantFromPHI(*PHI))
5442 V = MaybeV;
5443 }
5444
5445 if (!BestValue)
5446 BestValue = V;
5447 else if (BestValue != V)
5448 BestValue = NullValue;
5449 }
5450 assert(BestValue && "Must have at least one use");
5451 assert(BestValue != &I && "Cannot replace with itself");
5452 return BestValue;
5453 };
5454
5455 if (match(V: Op0, P: m_Undef())) {
5456 // Don't fold freeze(undef/poison) if it's used as a vector operand in
5457 // a shuffle. This may improve codegen for shuffles that allow
5458 // unspecified inputs.
5459 if (isUsedWithinShuffleVector(V: &I))
5460 return nullptr;
5461 return replaceInstUsesWith(I, V: getUndefReplacement(I.getType()));
5462 }
5463
5464 auto getFreezeVectorReplacement = [](Constant *C) -> Constant * {
5465 Type *Ty = C->getType();
5466 auto *VTy = dyn_cast<FixedVectorType>(Val: Ty);
5467 if (!VTy)
5468 return nullptr;
5469 Constant *BestValue;
5470 if (!match(V: C, P: m_ContainsMatchingVectorElement(SubPattern: m_CombineAnd(
5471 Ps: m_Unless(P: m_Undef()), Ps: m_Constant(C&: BestValue)))))
5472 BestValue = Constant::getNullValue(Ty: VTy->getScalarType());
5473 return Constant::replaceUndefsWith(C, Replacement: BestValue);
5474 };
5475
5476 Constant *C;
5477 if (match(V: Op0, P: m_Constant(C)) && C->containsUndefOrPoisonElement() &&
5478 !C->containsConstantExpression()) {
5479 if (Constant *Repl = getFreezeVectorReplacement(C))
5480 return replaceInstUsesWith(I, V: Repl);
5481 }
5482
5483 // Replace uses of Op with freeze(Op).
5484 if (freezeOtherUses(FI&: I))
5485 return &I;
5486
5487 return nullptr;
5488}
5489
5490/// Check for case where the call writes to an otherwise dead alloca. This
5491/// shows up for unused out-params in idiomatic C/C++ code. Note that this
5492/// helper *only* analyzes the write; doesn't check any other legality aspect.
5493static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI) {
5494 auto *CB = dyn_cast<CallBase>(Val: I);
5495 if (!CB)
5496 // TODO: handle e.g. store to alloca here - only worth doing if we extend
5497 // to allow reload along used path as described below. Otherwise, this
5498 // is simply a store to a dead allocation which will be removed.
5499 return false;
5500 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CI: CB, TLI);
5501 if (!Dest)
5502 return false;
5503 auto *AI = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Dest->Ptr));
5504 if (!AI)
5505 // TODO: allow malloc?
5506 return false;
5507 // TODO: allow memory access dominated by move point? Note that since AI
5508 // could have a reference to itself captured by the call, we would need to
5509 // account for cycles in doing so.
5510 SmallVector<const User *> AllocaUsers;
5511 SmallPtrSet<const User *, 4> Visited;
5512 auto pushUsers = [&](const Instruction &I) {
5513 for (const User *U : I.users()) {
5514 if (Visited.insert(Ptr: U).second)
5515 AllocaUsers.push_back(Elt: U);
5516 }
5517 };
5518 pushUsers(*AI);
5519 while (!AllocaUsers.empty()) {
5520 auto *UserI = cast<Instruction>(Val: AllocaUsers.pop_back_val());
5521 if (isa<GetElementPtrInst>(Val: UserI) || isa<AddrSpaceCastInst>(Val: UserI)) {
5522 pushUsers(*UserI);
5523 continue;
5524 }
5525 if (UserI == CB)
5526 continue;
5527 // TODO: support lifetime.start/end here
5528 return false;
5529 }
5530 return true;
5531}
5532
5533/// Try to move the specified instruction from its current block into the
5534/// beginning of DestBlock, which can only happen if it's safe to move the
5535/// instruction past all of the instructions between it and the end of its
5536/// block.
5537bool InstCombinerImpl::tryToSinkInstruction(Instruction *I,
5538 BasicBlock *DestBlock) {
5539 BasicBlock *SrcBlock = I->getParent();
5540
5541 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5542 if (isa<PHINode>(Val: I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
5543 I->isTerminator())
5544 return false;
5545
5546 // Do not sink static or dynamic alloca instructions. Static allocas must
5547 // remain in the entry block, and dynamic allocas must not be sunk in between
5548 // a stacksave / stackrestore pair, which would incorrectly shorten its
5549 // lifetime.
5550 if (isa<AllocaInst>(Val: I))
5551 return false;
5552
5553 // Do not sink into catchswitch blocks.
5554 if (isa<CatchSwitchInst>(Val: DestBlock->getTerminator()))
5555 return false;
5556
5557 // Do not sink convergent call instructions.
5558 if (auto *CI = dyn_cast<CallInst>(Val: I)) {
5559 if (CI->isConvergent())
5560 return false;
5561 }
5562
5563 // Unless we can prove that the memory write isn't visibile except on the
5564 // path we're sinking to, we must bail.
5565 if (I->mayWriteToMemory()) {
5566 if (!SoleWriteToDeadLocal(I, TLI))
5567 return false;
5568 }
5569
5570 // We can only sink load instructions if there is nothing between the load and
5571 // the end of block that could change the value.
5572 if (I->mayReadFromMemory() &&
5573 !I->hasMetadata(KindID: LLVMContext::MD_invariant_load)) {
5574 // We don't want to do any sophisticated alias analysis, so we only check
5575 // the instructions after I in I's parent block if we try to sink to its
5576 // successor block.
5577 if (DestBlock->getUniquePredecessor() != I->getParent())
5578 return false;
5579 for (BasicBlock::iterator Scan = std::next(x: I->getIterator()),
5580 E = I->getParent()->end();
5581 Scan != E; ++Scan)
5582 if (Scan->mayWriteToMemory() && !isa<AssumeInst>(Val: Scan))
5583 return false;
5584 }
5585
5586 I->dropDroppableUses(ShouldDrop: [&](const Use *U) {
5587 auto *I = dyn_cast<Instruction>(Val: U->getUser());
5588 if (I && I->getParent() != DestBlock) {
5589 Worklist.add(I);
5590 return true;
5591 }
5592 return false;
5593 });
5594 /// FIXME: We could remove droppable uses that are not dominated by
5595 /// the new position.
5596
5597 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
5598 I->moveBefore(BB&: *DestBlock, I: InsertPos);
5599 ++NumSunkInst;
5600
5601 // Also sink all related debug uses from the source basic block. Otherwise we
5602 // get debug use before the def. Attempt to salvage debug uses first, to
5603 // maximise the range variables have location for. If we cannot salvage, then
5604 // mark the location undef: we know it was supposed to receive a new location
5605 // here, but that computation has been sunk.
5606 SmallVector<DbgVariableRecord *, 2> DbgVariableRecords;
5607 findDbgUsers(V: I, DbgVariableRecords);
5608 if (!DbgVariableRecords.empty())
5609 tryToSinkInstructionDbgVariableRecords(I, InsertPos, SrcBlock, DestBlock,
5610 DPUsers&: DbgVariableRecords);
5611
5612 // PS: there are numerous flaws with this behaviour, not least that right now
5613 // assignments can be re-ordered past other assignments to the same variable
5614 // if they use different Values. Creating more undef assignements can never be
5615 // undone. And salvaging all users outside of this block can un-necessarily
5616 // alter the lifetime of the live-value that the variable refers to.
5617 // Some of these things can be resolved by tolerating debug use-before-defs in
5618 // LLVM-IR, however it depends on the instruction-referencing CodeGen backend
5619 // being used for more architectures.
5620
5621 return true;
5622}
5623
5624void InstCombinerImpl::tryToSinkInstructionDbgVariableRecords(
5625 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
5626 BasicBlock *DestBlock,
5627 SmallVectorImpl<DbgVariableRecord *> &DbgVariableRecords) {
5628 // For all debug values in the destination block, the sunk instruction
5629 // will still be available, so they do not need to be dropped.
5630
5631 // Fetch all DbgVariableRecords not already in the destination.
5632 SmallVector<DbgVariableRecord *, 2> DbgVariableRecordsToSalvage;
5633 for (auto &DVR : DbgVariableRecords)
5634 if (DVR->getParent() != DestBlock)
5635 DbgVariableRecordsToSalvage.push_back(Elt: DVR);
5636
5637 // Fetch a second collection, of DbgVariableRecords in the source block that
5638 // we're going to sink.
5639 SmallVector<DbgVariableRecord *> DbgVariableRecordsToSink;
5640 for (DbgVariableRecord *DVR : DbgVariableRecordsToSalvage)
5641 if (DVR->getParent() == SrcBlock)
5642 DbgVariableRecordsToSink.push_back(Elt: DVR);
5643
5644 // Sort DbgVariableRecords according to their position in the block. This is a
5645 // partial order: DbgVariableRecords attached to different instructions will
5646 // be ordered by the instruction order, but DbgVariableRecords attached to the
5647 // same instruction won't have an order.
5648 auto Order = [](DbgVariableRecord *A, DbgVariableRecord *B) -> bool {
5649 return B->getInstruction()->comesBefore(Other: A->getInstruction());
5650 };
5651 llvm::stable_sort(Range&: DbgVariableRecordsToSink, C: Order);
5652
5653 // If there are two assignments to the same variable attached to the same
5654 // instruction, the ordering between the two assignments is important. Scan
5655 // for this (rare) case and establish which is the last assignment.
5656 using InstVarPair = std::pair<const Instruction *, DebugVariable>;
5657 SmallDenseMap<InstVarPair, DbgVariableRecord *> FilterOutMap;
5658 if (DbgVariableRecordsToSink.size() > 1) {
5659 SmallDenseMap<InstVarPair, unsigned> CountMap;
5660 // Count how many assignments to each variable there is per instruction.
5661 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5662 DebugVariable DbgUserVariable =
5663 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5664 DVR->getDebugLoc()->getInlinedAt());
5665 CountMap[std::make_pair(x: DVR->getInstruction(), y&: DbgUserVariable)] += 1;
5666 }
5667
5668 // If there are any instructions with two assignments, add them to the
5669 // FilterOutMap to record that they need extra filtering.
5670 SmallPtrSet<const Instruction *, 4> DupSet;
5671 for (auto It : CountMap) {
5672 if (It.second > 1) {
5673 FilterOutMap[It.first] = nullptr;
5674 DupSet.insert(Ptr: It.first.first);
5675 }
5676 }
5677
5678 // For all instruction/variable pairs needing extra filtering, find the
5679 // latest assignment.
5680 for (const Instruction *Inst : DupSet) {
5681 for (DbgVariableRecord &DVR :
5682 llvm::reverse(C: filterDbgVars(R: Inst->getDbgRecordRange()))) {
5683 DebugVariable DbgUserVariable =
5684 DebugVariable(DVR.getVariable(), DVR.getExpression(),
5685 DVR.getDebugLoc()->getInlinedAt());
5686 auto FilterIt =
5687 FilterOutMap.find(Val: std::make_pair(x&: Inst, y&: DbgUserVariable));
5688 if (FilterIt == FilterOutMap.end())
5689 continue;
5690 if (FilterIt->second != nullptr)
5691 continue;
5692 FilterIt->second = &DVR;
5693 }
5694 }
5695 }
5696
5697 // Perform cloning of the DbgVariableRecords that we plan on sinking, filter
5698 // out any duplicate assignments identified above.
5699 SmallVector<DbgVariableRecord *, 2> DVRClones;
5700 SmallSet<DebugVariable, 4> SunkVariables;
5701 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5702 if (DVR->Type == DbgVariableRecord::LocationType::Declare)
5703 continue;
5704
5705 DebugVariable DbgUserVariable =
5706 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5707 DVR->getDebugLoc()->getInlinedAt());
5708
5709 // For any variable where there were multiple assignments in the same place,
5710 // ignore all but the last assignment.
5711 if (!FilterOutMap.empty()) {
5712 InstVarPair IVP = std::make_pair(x: DVR->getInstruction(), y&: DbgUserVariable);
5713 auto It = FilterOutMap.find(Val: IVP);
5714
5715 // Filter out.
5716 if (It != FilterOutMap.end() && It->second != DVR)
5717 continue;
5718 }
5719
5720 if (!SunkVariables.insert(V: DbgUserVariable).second)
5721 continue;
5722
5723 if (DVR->isDbgAssign())
5724 continue;
5725
5726 DVRClones.emplace_back(Args: DVR->clone());
5727 LLVM_DEBUG(dbgs() << "CLONE: " << *DVRClones.back() << '\n');
5728 }
5729
5730 // Perform salvaging without the clones, then sink the clones.
5731 if (DVRClones.empty())
5732 return;
5733
5734 salvageDebugInfoForDbgValues(I&: *I, DbgRecords: DbgVariableRecordsToSalvage);
5735
5736 // The clones are in reverse order of original appearance. Assert that the
5737 // head bit is set on the iterator as we _should_ have received it via
5738 // getFirstInsertionPt. Inserting like this will reverse the clone order as
5739 // we'll repeatedly insert at the head, such as:
5740 // DVR-3 (third insertion goes here)
5741 // DVR-2 (second insertion goes here)
5742 // DVR-1 (first insertion goes here)
5743 // Any-Prior-DVRs
5744 // InsertPtInst
5745 assert(InsertPos.getHeadBit());
5746 for (DbgVariableRecord *DVRClone : DVRClones) {
5747 InsertPos->getParent()->insertDbgRecordBefore(DR: DVRClone, Here: InsertPos);
5748 LLVM_DEBUG(dbgs() << "SINK: " << *DVRClone << '\n');
5749 }
5750}
5751
5752bool InstCombinerImpl::run() {
5753 while (!Worklist.isEmpty()) {
5754 // Walk deferred instructions in reverse order, and push them to the
5755 // worklist, which means they'll end up popped from the worklist in-order.
5756 while (Instruction *I = Worklist.popDeferred()) {
5757 // Check to see if we can DCE the instruction. We do this already here to
5758 // reduce the number of uses and thus allow other folds to trigger.
5759 // Note that eraseInstFromFunction() may push additional instructions on
5760 // the deferred worklist, so this will DCE whole instruction chains.
5761 if (isInstructionTriviallyDead(I, TLI: &TLI)) {
5762 eraseInstFromFunction(I&: *I);
5763 ++NumDeadInst;
5764 continue;
5765 }
5766
5767 Worklist.push(I);
5768 }
5769
5770 Instruction *I = Worklist.removeOne();
5771 if (I == nullptr) continue; // skip null values.
5772
5773 // Check to see if we can DCE the instruction.
5774 if (isInstructionTriviallyDead(I, TLI: &TLI)) {
5775 eraseInstFromFunction(I&: *I);
5776 ++NumDeadInst;
5777 continue;
5778 }
5779
5780 if (!DebugCounter::shouldExecute(Counter&: VisitCounter))
5781 continue;
5782
5783 // See if we can trivially sink this instruction to its user if we can
5784 // prove that the successor is not executed more frequently than our block.
5785 // Return the UserBlock if successful.
5786 auto getOptionalSinkBlockForInst =
5787 [this](Instruction *I) -> std::optional<BasicBlock *> {
5788 if (!CLOpts.code_sinking)
5789 return std::nullopt;
5790
5791 BasicBlock *BB = I->getParent();
5792 BasicBlock *UserParent = nullptr;
5793 unsigned NumUsers = 0;
5794
5795 for (Use &U : I->uses()) {
5796 User *User = U.getUser();
5797 if (User->isDroppable()) {
5798 // Do not sink if there are dereferenceable assumes that would be
5799 // removed.
5800 auto II = dyn_cast<IntrinsicInst>(Val: User);
5801 if (II->getIntrinsicID() != Intrinsic::assume ||
5802 !II->getOperandBundle(Name: "dereferenceable"))
5803 continue;
5804 }
5805
5806 if (NumUsers > CLOpts.max_sink_users)
5807 return std::nullopt;
5808
5809 Instruction *UserInst = cast<Instruction>(Val: User);
5810 // Special handling for Phi nodes - get the block the use occurs in.
5811 BasicBlock *UserBB = UserInst->getParent();
5812 if (PHINode *PN = dyn_cast<PHINode>(Val: UserInst))
5813 UserBB = PN->getIncomingBlock(U);
5814 // Bail out if we have uses in different blocks. We don't do any
5815 // sophisticated analysis (i.e finding NearestCommonDominator of these
5816 // use blocks).
5817 if (UserParent && UserParent != UserBB)
5818 return std::nullopt;
5819 UserParent = UserBB;
5820
5821 // Make sure these checks are done only once, naturally we do the checks
5822 // the first time we get the userparent, this will save compile time.
5823 if (NumUsers == 0) {
5824 // Try sinking to another block. If that block is unreachable, then do
5825 // not bother. SimplifyCFG should handle it.
5826 if (UserParent == BB || !DT.isReachableFromEntry(A: UserParent))
5827 return std::nullopt;
5828
5829 auto *Term = UserParent->getTerminator();
5830 // See if the user is one of our successors that has only one
5831 // predecessor, so that we don't have to split the critical edge.
5832 // Another option where we can sink is a block that ends with a
5833 // terminator that does not pass control to other block (such as
5834 // return or unreachable or resume). In this case:
5835 // - I dominates the User (by SSA form);
5836 // - the User will be executed at most once.
5837 // So sinking I down to User is always profitable or neutral.
5838 if (UserParent->getUniquePredecessor() != BB && !succ_empty(I: Term))
5839 return std::nullopt;
5840
5841 assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");
5842 }
5843
5844 NumUsers++;
5845 }
5846
5847 // No user or only has droppable users.
5848 if (!UserParent)
5849 return std::nullopt;
5850
5851 return UserParent;
5852 };
5853
5854 auto OptBB = getOptionalSinkBlockForInst(I);
5855 if (OptBB) {
5856 auto *UserParent = *OptBB;
5857 // Okay, the CFG is simple enough, try to sink this instruction.
5858 if (tryToSinkInstruction(I, DestBlock: UserParent)) {
5859 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
5860 MadeIRChange = true;
5861 // We'll add uses of the sunk instruction below, but since
5862 // sinking can expose opportunities for it's *operands* add
5863 // them to the worklist
5864 for (Use &U : I->operands())
5865 if (Instruction *OpI = dyn_cast<Instruction>(Val: U.get()))
5866 Worklist.push(I: OpI);
5867 }
5868 }
5869
5870 // Now that we have an instruction, try combining it to simplify it.
5871 Builder.SetInsertPoint(I);
5872 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5873 // Used by our IRBuilder inserter to copy annotation metadata.
5874 AnnotationMetadataSource = I;
5875
5876#ifndef NDEBUG
5877 std::string OrigI;
5878#endif
5879 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS););
5880 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
5881
5882 if (Instruction *Result = visit(I&: *I)) {
5883 ++NumCombined;
5884 // Should we replace the old instruction with a new one?
5885 if (Result != I) {
5886 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
5887 << " New = " << *Result << '\n');
5888
5889 // We copy the old instruction's DebugLoc to the new instruction, unless
5890 // InstCombine already assigned a DebugLoc to it, in which case we
5891 // should trust the more specifically selected DebugLoc.
5892 Result->setDebugLoc(Result->getDebugLoc().orElse(Other: I->getDebugLoc()));
5893 // We also copy annotation metadata to the new instruction.
5894 Result->copyMetadata(SrcInst: *I, WL: LLVMContext::MD_annotation);
5895 // Everything uses the new instruction now.
5896 I->replaceAllUsesWith(V: Result);
5897
5898 // Move the name to the new instruction first.
5899 Result->takeName(V: I);
5900
5901 // Insert the new instruction into the basic block...
5902 BasicBlock *InstParent = I->getParent();
5903 BasicBlock::iterator InsertPos = I->getIterator();
5904
5905 // Are we replace a PHI with something that isn't a PHI, or vice versa?
5906 if (isa<PHINode>(Val: Result) != isa<PHINode>(Val: I)) {
5907 // We need to fix up the insertion point.
5908 if (isa<PHINode>(Val: I)) // PHI -> Non-PHI
5909 InsertPos = InstParent->getFirstInsertionPt();
5910 else // Non-PHI -> PHI
5911 InsertPos = InstParent->getFirstNonPHIIt();
5912 }
5913
5914 Result->insertInto(ParentBB: InstParent, It: InsertPos);
5915
5916 // Register newly created assumptions.
5917 if (auto *Assume = dyn_cast<AssumeInst>(Val: Result))
5918 AC.registerAssumption(CI: Assume);
5919
5920 // Push the new instruction and any users onto the worklist.
5921 Worklist.pushUsersToWorkList(I&: *Result);
5922 Worklist.push(I: Result);
5923
5924 eraseInstFromFunction(I&: *I);
5925 } else {
5926 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
5927 << " New = " << *I << '\n');
5928
5929 // If the instruction was modified, it's possible that it is now dead.
5930 // if so, remove it.
5931 if (isInstructionTriviallyDead(I, TLI: &TLI)) {
5932 eraseInstFromFunction(I&: *I);
5933 } else {
5934 Worklist.pushUsersToWorkList(I&: *I);
5935 Worklist.push(I);
5936 }
5937 }
5938 MadeIRChange = true;
5939 }
5940 }
5941
5942 Worklist.zap();
5943 return MadeIRChange;
5944}
5945
5946// Track the scopes used by !alias.scope and !noalias. In a function, a
5947// @llvm.experimental.noalias.scope.decl is only useful if that scope is used
5948// by both sets. If not, the declaration of the scope can be safely omitted.
5949// The MDNode of the scope can be omitted as well for the instructions that are
5950// part of this function. We do not do that at this point, as this might become
5951// too time consuming to do.
5952class AliasScopeTracker {
5953 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
5954 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
5955 // Scopes used by every !alias.scope list that scopes from a disjoint-scope
5956 // domain appears in. This is used to catch scopes that don't actually make
5957 // anything noalias.
5958 SmallDenseMap<const MDNode *, SmallPtrSet<const MDNode *, 4>, 4>
5959 CommonScopesOfDisjointDomain;
5960
5961 // Record, for each disjoint-scope domain \p ScopeList uses, which of its
5962 // scopes are used by \p ScopeList, adding to a running intersection.
5963 void recordDisjointDomainScopes(const MDNode *ScopeList) {
5964 SmallDenseMap<const MDNode *, SmallPtrSet<const MDNode *, 4>, 4> UsedScopes;
5965 for (const MDOperand &MDOperand : ScopeList->operands()) {
5966 const auto *MDScope = cast<MDNode>(Val: MDOperand);
5967 const MDNode *Domain = AliasScopeNode(MDScope).getDomain();
5968 if (AliasScopeDomainNode(Domain).hasDisjointScopes())
5969 UsedScopes[Domain].insert(Ptr: MDScope);
5970 }
5971
5972 for (auto &[Domain, Scopes] : UsedScopes) {
5973 auto [It, Inserted] =
5974 CommonScopesOfDisjointDomain.try_emplace(Key: Domain, Args&: Scopes);
5975 if (!Inserted)
5976 llvm::set_intersect(S1&: It->second, S2: Scopes);
5977 }
5978 }
5979
5980 // Return true if \p Scope is on the implicit !noalias list of one of the
5981 // analysed accesses, that is, if it belongs to a disjoint-scope domain and
5982 // some access uses that domain without using \p Scope.
5983 bool isImplicitlyNoAlias(const MDNode *Scope) const {
5984 auto It =
5985 CommonScopesOfDisjointDomain.find(Val: AliasScopeNode(Scope).getDomain());
5986 return It != CommonScopesOfDisjointDomain.end() &&
5987 !It->second.contains(Ptr: Scope);
5988 }
5989
5990public:
5991 void analyse(Instruction *I) {
5992 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
5993 if (!I->hasMetadataOtherThanDebugLoc())
5994 return;
5995
5996 auto Track = [](Metadata *ScopeList, auto &Container) -> const MDNode * {
5997 const auto *MDScopeList = dyn_cast_or_null<MDNode>(Val: ScopeList);
5998 if (!MDScopeList || !Container.insert(MDScopeList).second)
5999 return nullptr;
6000 for (const auto &MDOperand : MDScopeList->operands())
6001 if (auto *MDScope = dyn_cast<MDNode>(Val: MDOperand))
6002 Container.insert(MDScope);
6003 return MDScopeList;
6004 };
6005
6006 if (const MDNode *AliasScopeList =
6007 Track(I->getMetadata(KindID: LLVMContext::MD_alias_scope),
6008 UsedAliasScopesAndLists))
6009 recordDisjointDomainScopes(ScopeList: AliasScopeList);
6010 Track(I->getMetadata(KindID: LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
6011 }
6012
6013 bool isNoAliasScopeDeclDead(Instruction *Inst) {
6014 NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Val: Inst);
6015 if (!Decl)
6016 return false;
6017
6018 assert(Decl->use_empty() &&
6019 "llvm.experimental.noalias.scope.decl in use ?");
6020 const MDNode *MDSL = Decl->getScopeList();
6021 assert(MDSL->getNumOperands() == 1 &&
6022 "llvm.experimental.noalias.scope should refer to a single scope");
6023 auto &MDOperand = MDSL->getOperand(I: 0);
6024 // A scope is relevant if it appears in an !alias.scope list, and either it
6025 // appears in a !noalias list, or it is on the implicit !noalias list of
6026 // some access using its disjoint-scope domain.
6027 if (auto *MD = dyn_cast<MDNode>(Val: MDOperand))
6028 return !UsedAliasScopesAndLists.contains(Ptr: MD) ||
6029 (!UsedNoAliasScopesAndLists.contains(Ptr: MD) &&
6030 !isImplicitlyNoAlias(Scope: MD));
6031
6032 // Not an MDNode ? throw away.
6033 return true;
6034 }
6035};
6036
6037/// Populate the IC worklist from a function, by walking it in reverse
6038/// post-order and adding all reachable code to the worklist.
6039///
6040/// This has a couple of tricks to make the code faster and more powerful. In
6041/// particular, we constant fold and DCE instructions as we go, to avoid adding
6042/// them to the worklist (this significantly speeds up instcombine on code where
6043/// many instructions are dead or constant). Additionally, if we find a branch
6044/// whose condition is a known constant, we only visit the reachable successors.
6045bool InstCombinerImpl::prepareWorklist(Function &F) {
6046 bool MadeIRChange = false;
6047 SmallPtrSet<BasicBlock *, 32> LiveBlocks;
6048 SmallVector<Instruction *, 128> InstrsForInstructionWorklist;
6049 DenseMap<Constant *, Constant *> FoldedConstants;
6050 AliasScopeTracker SeenAliasScopes;
6051
6052 auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) {
6053 for (BasicBlock *Succ : successors(BB))
6054 if (Succ != LiveSucc && DeadEdges.insert(V: {BB, Succ}).second)
6055 for (PHINode &PN : Succ->phis())
6056 for (Use &U : PN.incoming_values())
6057 if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(Val: U)) {
6058 U.set(PoisonValue::get(T: PN.getType()));
6059 MadeIRChange = true;
6060 }
6061 };
6062
6063 for (BasicBlock *BB : RPOT) {
6064 if (!BB->isEntryBlock() && all_of(Range: predecessors(BB), P: [&](BasicBlock *Pred) {
6065 return DeadEdges.contains(V: {Pred, BB}) || DT.dominates(A: BB, B: Pred);
6066 })) {
6067 HandleOnlyLiveSuccessor(BB, nullptr);
6068 continue;
6069 }
6070 LiveBlocks.insert(Ptr: BB);
6071
6072 for (Instruction &Inst : llvm::make_early_inc_range(Range&: *BB)) {
6073 // ConstantProp instruction if trivially constant.
6074 if (!Inst.use_empty() &&
6075 (Inst.getNumOperands() == 0 || isa<Constant>(Val: Inst.getOperand(i: 0))))
6076 if (Constant *C = ConstantFoldInstruction(I: &Inst, DL, TLI: &TLI)) {
6077 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst
6078 << '\n');
6079 Inst.replaceAllUsesWith(V: C);
6080 ++NumConstProp;
6081 if (isInstructionTriviallyDead(I: &Inst, TLI: &TLI))
6082 Inst.eraseFromParent();
6083 MadeIRChange = true;
6084 continue;
6085 }
6086
6087 // See if we can constant fold its operands.
6088 for (Use &U : Inst.operands()) {
6089 if (!isa<ConstantVector>(Val: U) && !isa<ConstantExpr>(Val: U))
6090 continue;
6091
6092 auto *C = cast<Constant>(Val&: U);
6093 Constant *&FoldRes = FoldedConstants[C];
6094 if (!FoldRes)
6095 FoldRes = ConstantFoldConstant(C, DL, TLI: &TLI);
6096
6097 if (FoldRes != C) {
6098 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst
6099 << "\n Old = " << *C
6100 << "\n New = " << *FoldRes << '\n');
6101 U = FoldRes;
6102 MadeIRChange = true;
6103 }
6104 }
6105
6106 // Skip processing debug and pseudo intrinsics in InstCombine. Processing
6107 // these call instructions consumes non-trivial amount of time and
6108 // provides no value for the optimization.
6109 if (!Inst.isDebugOrPseudoInst()) {
6110 InstrsForInstructionWorklist.push_back(Elt: &Inst);
6111 SeenAliasScopes.analyse(I: &Inst);
6112 }
6113 }
6114
6115 // If this is a branch or switch on a constant, mark only the single
6116 // live successor. Otherwise assume all successors are live.
6117 Instruction *TI = BB->getTerminator();
6118 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: TI)) {
6119 if (isa<UndefValue>(Val: BI->getCondition())) {
6120 // Branch on undef is UB.
6121 HandleOnlyLiveSuccessor(BB, nullptr);
6122 continue;
6123 }
6124 if (auto *Cond = dyn_cast<ConstantInt>(Val: BI->getCondition())) {
6125 bool CondVal = Cond->getZExtValue();
6126 HandleOnlyLiveSuccessor(BB, BI->getSuccessor(i: !CondVal));
6127 continue;
6128 }
6129 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: TI)) {
6130 if (isa<UndefValue>(Val: SI->getCondition())) {
6131 // Switch on undef is UB.
6132 HandleOnlyLiveSuccessor(BB, nullptr);
6133 continue;
6134 }
6135 if (auto *Cond = dyn_cast<ConstantInt>(Val: SI->getCondition())) {
6136 HandleOnlyLiveSuccessor(BB,
6137 SI->findCaseValue(C: Cond)->getCaseSuccessor());
6138 continue;
6139 }
6140 }
6141 }
6142
6143 // Remove instructions inside unreachable blocks. This prevents the
6144 // instcombine code from having to deal with some bad special cases, and
6145 // reduces use counts of instructions.
6146 for (BasicBlock &BB : F) {
6147 if (LiveBlocks.count(Ptr: &BB))
6148 continue;
6149
6150 unsigned NumDeadInstInBB;
6151 NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(BB: &BB);
6152
6153 MadeIRChange |= NumDeadInstInBB != 0;
6154 NumDeadInst += NumDeadInstInBB;
6155 }
6156
6157 // Once we've found all of the instructions to add to instcombine's worklist,
6158 // add them in reverse order. This way instcombine will visit from the top
6159 // of the function down. This jives well with the way that it adds all uses
6160 // of instructions to the worklist after doing a transformation, thus avoiding
6161 // some N^2 behavior in pathological cases.
6162 Worklist.reserve(Size: InstrsForInstructionWorklist.size());
6163 for (Instruction *Inst : reverse(C&: InstrsForInstructionWorklist)) {
6164 // DCE instruction if trivially dead. As we iterate in reverse program
6165 // order here, we will clean up whole chains of dead instructions.
6166 if (isInstructionTriviallyDead(I: Inst, TLI: &TLI) ||
6167 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
6168 ++NumDeadInst;
6169 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
6170 salvageDebugInfo(I&: *Inst);
6171 Inst->eraseFromParent();
6172 MadeIRChange = true;
6173 continue;
6174 }
6175
6176 Worklist.push(I: Inst);
6177 }
6178
6179 return MadeIRChange;
6180}
6181
6182void InstCombiner::computeBackEdges() {
6183 // Collect backedges.
6184 SmallVector<bool> Visited(F.getMaxBlockNumber());
6185 for (BasicBlock *BB : RPOT) {
6186 Visited[BB->getNumber()] = true;
6187 for (BasicBlock *Succ : successors(BB))
6188 if (Visited[Succ->getNumber()])
6189 BackEdges.insert(V: {BB, Succ});
6190 }
6191 ComputedBackEdges = true;
6192}
6193
6194static bool combineInstructionsOverFunction(
6195 Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA,
6196 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
6197 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
6198 BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI,
6199 const InstCombineOptions &Opts) {
6200 auto &DL = F.getDataLayout();
6201 bool VerifyFixpoint = Opts.VerifyFixpoint &&
6202 !F.hasFnAttribute(Kind: "instcombine-no-verify-fixpoint");
6203
6204 ReversePostOrderTraversal<BasicBlock *> RPOT(&F.front());
6205
6206 // Lower dbg.declare intrinsics otherwise their value may be clobbered
6207 // by instcombiner.
6208 const InstCombineCLOptions &CLOpts = InstCombineCLOptions::Global;
6209 bool MadeIRChange = false;
6210 if (CLOpts.lower_dbg_declare)
6211 MadeIRChange = LowerDbgDeclare(F);
6212
6213 // Iterate while there is work to do.
6214 unsigned Iteration = 0;
6215 while (true) {
6216 if (Iteration >= Opts.MaxIterations && !VerifyFixpoint) {
6217 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations
6218 << " on " << F.getName()
6219 << " reached; stopping without verifying fixpoint\n");
6220 break;
6221 }
6222
6223 ++Iteration;
6224 ++NumWorklistIterations;
6225 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
6226 << F.getName() << "\n");
6227
6228 InstCombinerImpl IC(Worklist, F, AA, AC, TLI, TTI, DT, ORE, BFI, BPI, PSI,
6229 DL, RPOT, CLOpts);
6230 bool MadeChangeInThisIteration = IC.prepareWorklist(F);
6231 MadeChangeInThisIteration |= IC.run();
6232 if (!MadeChangeInThisIteration)
6233 break;
6234
6235 MadeIRChange = true;
6236 if (Iteration > Opts.MaxIterations) {
6237 reportFatalUsageError(
6238 reason: "Instruction Combining on " + Twine(F.getName()) +
6239 " did not reach a fixpoint after " + Twine(Opts.MaxIterations) +
6240 " iterations. " +
6241 "Use 'instcombine<no-verify-fixpoint>' or function attribute "
6242 "'instcombine-no-verify-fixpoint' to suppress this error.");
6243 }
6244 }
6245
6246 if (Iteration == 1)
6247 ++NumOneIteration;
6248 else if (Iteration == 2)
6249 ++NumTwoIterations;
6250 else if (Iteration == 3)
6251 ++NumThreeIterations;
6252 else
6253 ++NumFourOrMoreIterations;
6254
6255 return MadeIRChange;
6256}
6257
6258InstCombinePass::InstCombinePass(InstCombineOptions Opts) : Options(Opts) {}
6259
6260void InstCombinePass::printPipeline(
6261 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6262 static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(
6263 OS, MapClassName2PassName);
6264 OS << '<';
6265 OS << "max-iterations=" << Options.MaxIterations << ";";
6266 OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint";
6267 OS << '>';
6268}
6269
6270char InstCombinePass::ID = 0;
6271
6272PreservedAnalyses InstCombinePass::run(Function &F,
6273 FunctionAnalysisManager &AM) {
6274 auto &LRT = AM.getResult<LastRunTrackingAnalysis>(IR&: F);
6275 // No changes since last InstCombine pass, exit early.
6276 if (LRT.shouldSkip(ID: &ID))
6277 return PreservedAnalyses::all();
6278
6279 auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F);
6280 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
6281 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
6282 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(IR&: F);
6283 auto &TTI = AM.getResult<TargetIRAnalysis>(IR&: F);
6284
6285 auto *AA = &AM.getResult<AAManager>(IR&: F);
6286 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(IR&: F);
6287 ProfileSummaryInfo *PSI =
6288 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(IR&: *F.getParent());
6289 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
6290 &AM.getResult<BlockFrequencyAnalysis>(IR&: F) : nullptr;
6291 auto *BPI = AM.getCachedResult<BranchProbabilityAnalysis>(IR&: F);
6292
6293 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6294 BFI, BPI, PSI, Opts: Options)) {
6295 // No changes, all analyses are preserved.
6296 LRT.update(ID: &ID, /*Changed=*/false);
6297 return PreservedAnalyses::all();
6298 }
6299
6300 // Mark all the analyses that instcombine updates as preserved.
6301 PreservedAnalyses PA;
6302 LRT.update(ID: &ID, /*Changed=*/true);
6303 PA.preserve<LastRunTrackingAnalysis>();
6304 PA.preserveSet<CFGAnalyses>();
6305 return PA;
6306}
6307
6308void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
6309 AU.setPreservesCFG();
6310 AU.addRequired<AAResultsWrapperPass>();
6311 AU.addRequired<AssumptionCacheTracker>();
6312 AU.addRequired<TargetLibraryInfoWrapperPass>();
6313 AU.addRequired<TargetTransformInfoWrapperPass>();
6314 AU.addRequired<DominatorTreeWrapperPass>();
6315 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
6316 AU.addPreserved<AAResultsWrapperPass>();
6317 AU.addPreserved<GlobalsAAWrapperPass>();
6318 AU.addRequired<ProfileSummaryInfoWrapperPass>();
6319 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
6320}
6321
6322bool InstructionCombiningPass::runOnFunction(Function &F) {
6323 if (skipFunction(F))
6324 return false;
6325
6326 // Required analyses.
6327 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
6328 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6329 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
6330 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
6331 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6332 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
6333
6334 // Optional analyses.
6335 ProfileSummaryInfo *PSI =
6336 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
6337 BlockFrequencyInfo *BFI =
6338 (PSI && PSI->hasProfileSummary()) ?
6339 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
6340 nullptr;
6341 BranchProbabilityInfo *BPI = nullptr;
6342 if (auto *WrapperPass =
6343 getAnalysisIfAvailable<BranchProbabilityInfoWrapperPass>())
6344 BPI = &WrapperPass->getBPI();
6345
6346 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6347 BFI, BPI, PSI, Opts: InstCombineOptions());
6348}
6349
6350char InstructionCombiningPass::ID = 0;
6351
6352InstructionCombiningPass::InstructionCombiningPass() : FunctionPass(ID) {}
6353
6354INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
6355 "Combine redundant instructions", false, false)
6356INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6357INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
6358INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6359INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6360INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6361INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
6362INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6363INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
6364INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
6365INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
6366 "Combine redundant instructions", false, false)
6367
6368// Initialization Routines.
6369void llvm::initializeInstCombine(PassRegistry &Registry) {
6370 initializeInstructionCombiningPassPass(Registry);
6371}
6372
6373FunctionPass *llvm::createInstructionCombiningPass() {
6374 return new InstructionCombiningPass();
6375}
6376