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