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