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