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