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