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