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 &&
631 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
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
1383 Value *LHS,
1384 Value *RHS) {
1385 Value *A, *B, *C, *D, *E, *F;
1386 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
1387 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
1388 if (!LHSIsSelect && !RHSIsSelect)
1389 return nullptr;
1390
1391 SelectInst *SI = cast<SelectInst>(LHSIsSelect ? LHS : RHS);
1392
1393 FastMathFlags FMF;
1395 if (const auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
1396 FMF = FPOp->getFastMathFlags();
1397 Builder.setFastMathFlags(FMF);
1398 }
1399
1400 Instruction::BinaryOps Opcode = I.getOpcode();
1401 SimplifyQuery Q = SQ.getWithInstruction(&I);
1402
1403 Value *Cond, *True = nullptr, *False = nullptr;
1404
1405 // If V is a select whose condition is implied by Cond, resolve it to the
1406 // appropriate arm for this value of Cond.
1407 auto simplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
1408 bool CondIsTrue) -> Value * {
1409 auto *InnerSI = dyn_cast<SelectInst>(V);
1410 if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
1411 return V;
1412
1413 if (std::optional<bool> Implied =
1414 isImpliedCondition(Cond, InnerSI->getCondition(), DL, CondIsTrue))
1415 return InnerSI->getOperand(*Implied ? 1 : 2);
1416 return V;
1417 };
1418
1419 // Special-case for add/negate combination. Replace the zero in the negation
1420 // with the trailing add operand:
1421 // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
1422 // (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False
1423 auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {
1424 // We need an 'add' and exactly 1 arm of the select to have been simplified.
1425 if (Opcode != Instruction::Add || (!True && !False) || (True && False))
1426 return nullptr;
1427 Value *N;
1428 if (True && match(FVal, m_Neg(m_Value(N)))) {
1429 Value *Sub = Builder.CreateSub(Z, N);
1430 return Builder.CreateSelect(Cond, True, Sub, I.getName(), SI);
1431 }
1432 if (False && match(TVal, m_Neg(m_Value(N)))) {
1433 Value *Sub = Builder.CreateSub(Z, N);
1434 return Builder.CreateSelect(Cond, Sub, False, I.getName(), SI);
1435 }
1436 return nullptr;
1437 };
1438
1439 if (LHSIsSelect && RHSIsSelect && A == D) {
1440 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
1441 Cond = A;
1442 True = simplifyBinOp(Opcode, B, E, FMF, Q);
1443 False = simplifyBinOp(Opcode, C, F, FMF, Q);
1444
1445 if (LHS->hasOneUse() && RHS->hasOneUse()) {
1446 if (False && !True)
1447 True = Builder.CreateBinOp(Opcode, B, E);
1448 else if (True && !False)
1449 False = Builder.CreateBinOp(Opcode, C, F);
1450 }
1451 } else if (LHSIsSelect && LHS->hasOneUse()) {
1452 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
1453 Cond = A;
1454 Value *TrueRHS = simplifySelectWithImpliedCond(RHS, Cond, true);
1455 Value *FalseRHS = simplifySelectWithImpliedCond(RHS, Cond, false);
1456 True = simplifyBinOp(Opcode, B, TrueRHS, FMF, Q);
1457 False = simplifyBinOp(Opcode, C, FalseRHS, FMF, Q);
1458 if (Value *NewSel = foldAddNegate(B, C, RHS))
1459 return NewSel;
1460 } else if (RHSIsSelect && RHS->hasOneUse()) {
1461 // X op (D ? E : F) -> D ? (X op E) : (X op F)
1462 Cond = D;
1463 Value *TrueLHS = simplifySelectWithImpliedCond(LHS, Cond, true);
1464 Value *FalseLHS = simplifySelectWithImpliedCond(LHS, Cond, false);
1465 True = simplifyBinOp(Opcode, TrueLHS, E, FMF, Q);
1466 False = simplifyBinOp(Opcode, FalseLHS, F, FMF, Q);
1467 if (Value *NewSel = foldAddNegate(E, F, LHS))
1468 return NewSel;
1469 }
1470
1471 if (!True || !False)
1472 return nullptr;
1473
1474 Value *NewSI = Builder.CreateSelect(Cond, True, False, I.getName(), SI);
1475 NewSI->takeName(&I);
1476 return NewSI;
1477}
1478
1479/// Freely adapt every user of V as-if V was changed to !V.
1480/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
1482 assert(!isa<Constant>(I) && "Shouldn't invert users of constant");
1483 for (User *U : make_early_inc_range(I->users())) {
1484 if (U == IgnoredUser)
1485 continue; // Don't consider this user.
1486 switch (cast<Instruction>(U)->getOpcode()) {
1487 case Instruction::Select: {
1488 auto *SI = cast<SelectInst>(U);
1489 SI->swapValues();
1490 SI->swapProfMetadata();
1491 break;
1492 }
1493 case Instruction::CondBr: {
1495 BI->swapSuccessors(); // swaps prof metadata too
1496 if (BPI)
1497 BPI->swapSuccEdgesProbabilities(BI->getParent());
1498 break;
1499 }
1500 case Instruction::Xor:
1502 // Add to worklist for DCE.
1504 break;
1505 default:
1506 llvm_unreachable("Got unexpected user - out of sync with "
1507 "canFreelyInvertAllUsersOf() ?");
1508 }
1509 }
1510
1511 // Update pre-existing debug value uses.
1512 SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;
1513 llvm::findDbgValues(I, DbgVariableRecords);
1514
1515 for (DbgVariableRecord *DbgVal : DbgVariableRecords) {
1516 SmallVector<uint64_t, 1> Ops = {dwarf::DW_OP_not};
1517 for (unsigned Idx = 0, End = DbgVal->getNumVariableLocationOps();
1518 Idx != End; ++Idx)
1519 if (DbgVal->getVariableLocationOp(Idx) == I)
1520 DbgVal->setExpression(
1521 DIExpression::appendOpsToArg(DbgVal->getExpression(), Ops, Idx));
1522 }
1523}
1524
1525/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
1526/// constant zero (which is the 'negate' form).
1527Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
1528 Value *NegV;
1529 if (match(V, m_Neg(m_Value(NegV))))
1530 return NegV;
1531
1532 // Constants can be considered to be negated values if they can be folded.
1534 return ConstantExpr::getNeg(C);
1535
1537 if (C->getType()->getElementType()->isIntegerTy())
1538 return ConstantExpr::getNeg(C);
1539
1541 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1542 Constant *Elt = CV->getAggregateElement(i);
1543 if (!Elt)
1544 return nullptr;
1545
1546 if (isa<UndefValue>(Elt))
1547 continue;
1548
1549 if (!isa<ConstantInt>(Elt))
1550 return nullptr;
1551 }
1552 return ConstantExpr::getNeg(CV);
1553 }
1554
1555 // Negate integer vector splats.
1556 if (auto *CV = dyn_cast<Constant>(V))
1557 if (CV->getType()->isVectorTy() &&
1558 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
1559 return ConstantExpr::getNeg(CV);
1560
1561 return nullptr;
1562}
1563
1564// Try to fold:
1565// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1566// -> ({s|u}itofp (int_binop x, y))
1567// 2) (fp_binop ({s|u}itofp x), FpC)
1568// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1569//
1570// Assuming the sign of the cast for x/y is `OpsFromSigned`.
1571Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(
1572 BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,
1574
1575 Type *FPTy = BO.getType();
1576 Type *IntTy = IntOps[0]->getType();
1577
1578 unsigned IntSz = IntTy->getScalarSizeInBits();
1579 // This is the maximum number of inuse bits by the integer where the int -> fp
1580 // casts are exact.
1581 unsigned MaxRepresentableBits =
1583
1584 // Preserve known number of leading bits. This can allow us to trivial nsw/nuw
1585 // checks later on.
1586 unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};
1587
1588 // NB: This only comes up if OpsFromSigned is true, so there is no need to
1589 // cache if between calls to `foldFBinOpOfIntCastsFromSign`.
1590 auto IsNonZero = [&](unsigned OpNo) -> bool {
1591 if (OpsKnown[OpNo].hasKnownBits() &&
1592 OpsKnown[OpNo].getKnownBits(SQ).isNonZero())
1593 return true;
1594 return isKnownNonZero(IntOps[OpNo], SQ);
1595 };
1596
1597 auto IsNonNeg = [&](unsigned OpNo) -> bool {
1598 // NB: This matches the impl in ValueTracking, we just try to use cached
1599 // knownbits here. If we ever start supporting WithCache for
1600 // `isKnownNonNegative`, change this to an explicit call.
1601 return OpsKnown[OpNo].getKnownBits(SQ).isNonNegative();
1602 };
1603
1604 // Check if we know for certain that ({s|u}itofp op) is exact.
1605 auto IsValidPromotion = [&](unsigned OpNo) -> bool {
1606 // Can we treat this operand as the desired sign?
1607 if (OpsFromSigned != isa<SIToFPInst>(BO.getOperand(OpNo)) &&
1608 !IsNonNeg(OpNo))
1609 return false;
1610
1611 // If fp precision >= bitwidth(op) then its exact.
1612 // NB: This is slightly conservative for `sitofp`. For signed conversion, we
1613 // can handle `MaxRepresentableBits == IntSz - 1` as the sign bit will be
1614 // handled specially. We can't, however, increase the bound arbitrarily for
1615 // `sitofp` as for larger sizes, it won't sign extend.
1616 if (MaxRepresentableBits < IntSz) {
1617 // Otherwise if its signed cast check that fp precisions >= bitwidth(op) -
1618 // numSignBits(op).
1619 // TODO: If we add support for `WithCache` in `ComputeNumSignBits`, change
1620 // `IntOps[OpNo]` arguments to `KnownOps[OpNo]`.
1621 if (OpsFromSigned)
1622 NumUsedLeadingBits[OpNo] = IntSz - ComputeNumSignBits(IntOps[OpNo]);
1623 // Finally for unsigned check that fp precision >= bitwidth(op) -
1624 // numLeadingZeros(op).
1625 else {
1626 NumUsedLeadingBits[OpNo] =
1627 IntSz - OpsKnown[OpNo].getKnownBits(SQ).countMinLeadingZeros();
1628 }
1629 }
1630 // NB: We could also check if op is known to be a power of 2 or zero (which
1631 // will always be representable). Its unlikely, however, that is we are
1632 // unable to bound op in any way we will be able to pass the overflow checks
1633 // later on.
1634
1635 if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])
1636 return false;
1637 // Signed + Mul also requires that op is non-zero to avoid -0 cases.
1638 return !OpsFromSigned || BO.getOpcode() != Instruction::FMul ||
1639 IsNonZero(OpNo);
1640 };
1641
1642 // If we have a constant rhs, see if we can losslessly convert it to an int.
1643 if (Op1FpC != nullptr) {
1644 // Signed + Mul req non-zero
1645 if (OpsFromSigned && BO.getOpcode() == Instruction::FMul &&
1646 !match(Op1FpC, m_NonZeroFP()))
1647 return nullptr;
1648
1650 OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, Op1FpC,
1651 IntTy, DL);
1652 if (Op1IntC == nullptr)
1653 return nullptr;
1654 if (ConstantFoldCastOperand(OpsFromSigned ? Instruction::SIToFP
1655 : Instruction::UIToFP,
1656 Op1IntC, FPTy, DL) != Op1FpC)
1657 return nullptr;
1658
1659 // First try to keep sign of cast the same.
1660 IntOps[1] = Op1IntC;
1661 }
1662
1663 // Ensure lhs/rhs integer types match.
1664 if (IntTy != IntOps[1]->getType())
1665 return nullptr;
1666
1667 if (Op1FpC == nullptr) {
1668 if (!IsValidPromotion(1))
1669 return nullptr;
1670 }
1671 if (!IsValidPromotion(0))
1672 return nullptr;
1673
1674 // Final we check if the integer version of the binop will not overflow.
1676 // Because of the precision check, we can often rule out overflows.
1677 bool NeedsOverflowCheck = true;
1678 // Try to conservatively rule out overflow based on the already done precision
1679 // checks.
1680 unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;
1681 unsigned OverflowMaxCurBits =
1682 std::max(NumUsedLeadingBits[0], NumUsedLeadingBits[1]);
1683 bool OutputSigned = OpsFromSigned;
1684 switch (BO.getOpcode()) {
1685 case Instruction::FAdd:
1686 IntOpc = Instruction::Add;
1687 OverflowMaxOutputBits += OverflowMaxCurBits;
1688 break;
1689 case Instruction::FSub:
1690 IntOpc = Instruction::Sub;
1691 OverflowMaxOutputBits += OverflowMaxCurBits;
1692 break;
1693 case Instruction::FMul:
1694 IntOpc = Instruction::Mul;
1695 OverflowMaxOutputBits += OverflowMaxCurBits * 2;
1696 break;
1697 default:
1698 llvm_unreachable("Unsupported binop");
1699 }
1700 // The precision check may have already ruled out overflow.
1701 if (OverflowMaxOutputBits < IntSz) {
1702 NeedsOverflowCheck = false;
1703 // We can bound unsigned overflow from sub to in range signed value (this is
1704 // what allows us to avoid the overflow check for sub).
1705 if (IntOpc == Instruction::Sub)
1706 OutputSigned = true;
1707 }
1708
1709 // Precision check did not rule out overflow, so need to check.
1710 // TODO: If we add support for `WithCache` in `willNotOverflow`, change
1711 // `IntOps[...]` arguments to `KnownOps[...]`.
1712 if (NeedsOverflowCheck &&
1713 !willNotOverflow(IntOpc, IntOps[0], IntOps[1], BO, OutputSigned))
1714 return nullptr;
1715
1716 Value *IntBinOp = Builder.CreateBinOp(IntOpc, IntOps[0], IntOps[1]);
1717 if (auto *IntBO = dyn_cast<BinaryOperator>(IntBinOp)) {
1718 IntBO->setHasNoSignedWrap(OutputSigned);
1719 IntBO->setHasNoUnsignedWrap(!OutputSigned);
1720 }
1721 if (OutputSigned)
1722 return new SIToFPInst(IntBinOp, FPTy);
1723 return new UIToFPInst(IntBinOp, FPTy);
1724}
1725
1726// Try to fold:
1727// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))
1728// -> ({s|u}itofp (int_binop x, y))
1729// 2) (fp_binop ({s|u}itofp x), FpC)
1730// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))
1731Instruction *InstCombinerImpl::foldFBinOpOfIntCasts(BinaryOperator &BO) {
1732 // Don't perform the fold on vectors, as the integer operation may be much
1733 // more expensive than the float operation in that case.
1734 if (BO.getType()->isVectorTy())
1735 return nullptr;
1736
1737 std::array<Value *, 2> IntOps = {nullptr, nullptr};
1738 Constant *Op1FpC = nullptr;
1739 // Check for:
1740 // 1) (binop ({s|u}itofp x), ({s|u}itofp y))
1741 // 2) (binop ({s|u}itofp x), FpC)
1742 if (!match(BO.getOperand(0), m_IToFP(m_Value(IntOps[0]))))
1743 return nullptr;
1744
1745 if (!match(BO.getOperand(1), m_Constant(Op1FpC)) &&
1746 !match(BO.getOperand(1), m_IToFP(m_Value(IntOps[1]))))
1747 return nullptr;
1748
1749 // Cache KnownBits a bit to potentially save some analysis.
1750 SmallVector<WithCache<const Value *>, 2> OpsKnown = {IntOps[0], IntOps[1]};
1751
1752 // Try treating x/y as coming from both `uitofp` and `sitofp`. There are
1753 // different constraints depending on the sign of the cast.
1754 // NB: `(uitofp nneg X)` == `(sitofp nneg X)`.
1755 if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/false,
1756 IntOps, Op1FpC, OpsKnown))
1757 return R;
1758 return foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/true, IntOps,
1759 Op1FpC, OpsKnown);
1760}
1761
1762/// A binop with a constant operand and a sign-extended boolean operand may be
1763/// converted into a select of constants by applying the binary operation to
1764/// the constant with the two possible values of the extended boolean (0 or -1).
1765Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {
1766 // TODO: Handle non-commutative binop (constant is operand 0).
1767 // TODO: Handle zext.
1768 // TODO: Peek through 'not' of cast.
1769 Value *BO0 = BO.getOperand(0);
1770 Value *BO1 = BO.getOperand(1);
1771 Value *X;
1772 Constant *C;
1773 if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||
1774 !X->getType()->isIntOrIntVectorTy(1))
1775 return nullptr;
1776
1777 // bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)
1780 Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);
1781 Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);
1782 return createSelectInstWithUnknownProfile(X, TVal, FVal);
1783}
1784
1786 bool IsTrueArm) {
1788 for (Value *Op : I.operands()) {
1789 Value *V = nullptr;
1790 if (Op == SI) {
1791 V = IsTrueArm ? SI->getTrueValue() : SI->getFalseValue();
1792 } else if (match(SI->getCondition(),
1795 m_Specific(Op), m_Value(V))) &&
1797 // Pass
1798 } else if (match(Op, m_ZExt(m_Specific(SI->getCondition())))) {
1799 V = IsTrueArm ? ConstantInt::get(Op->getType(), 1)
1800 : ConstantInt::getNullValue(Op->getType());
1801 } else {
1802 V = Op;
1803 }
1804 Ops.push_back(V);
1805 }
1806
1807 return simplifyInstructionWithOperands(&I, Ops, I.getDataLayout());
1808}
1809
1811 Value *NewOp, InstCombiner &IC) {
1812 Instruction *Clone = I.clone();
1813 Clone->replaceUsesOfWith(SI, NewOp);
1815 IC.InsertNewInstBefore(Clone, I.getIterator());
1816 return Clone;
1817}
1818
1820 bool FoldWithMultiUse,
1821 bool SimplifyBothArms) {
1822 // Don't modify shared select instructions unless set FoldWithMultiUse
1823 if (!SI->hasOneUser() && !FoldWithMultiUse)
1824 return nullptr;
1825
1826 Value *TV = SI->getTrueValue();
1827 Value *FV = SI->getFalseValue();
1828
1829 // Bool selects with constant operands can be folded to logical ops.
1830 if (SI->getType()->isIntOrIntVectorTy(1))
1831 return nullptr;
1832
1833 // Avoid breaking min/max reduction pattern,
1834 // which is necessary for vectorization later.
1836 for (Value *IntrinOp : Op.operands())
1837 if (auto *PN = dyn_cast<PHINode>(IntrinOp))
1838 for (Value *PhiOp : PN->operands())
1839 if (PhiOp == &Op)
1840 return nullptr;
1841
1842 // Test if a FCmpInst instruction is used exclusively by a select as
1843 // part of a minimum or maximum operation. If so, refrain from doing
1844 // any other folding. This helps out other analyses which understand
1845 // non-obfuscated minimum and maximum idioms. And in this case, at
1846 // least one of the comparison operands has at least one user besides
1847 // the compare (the select), which would often largely negate the
1848 // benefit of folding anyway.
1849 if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) {
1850 if (CI->hasOneUse()) {
1851 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1852 if (((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1)) &&
1853 !CI->isCommutative())
1854 return nullptr;
1855 }
1856 }
1857
1858 // Make sure that one of the select arms folds successfully.
1859 Value *NewTV = simplifyOperationIntoSelectOperand(Op, SI, /*IsTrueArm=*/true);
1860 Value *NewFV =
1861 simplifyOperationIntoSelectOperand(Op, SI, /*IsTrueArm=*/false);
1862 if (!NewTV && !NewFV)
1863 return nullptr;
1864
1865 if (SimplifyBothArms && !(NewTV && NewFV))
1866 return nullptr;
1867
1868 // Create an instruction for the arm that did not fold.
1869 if (!NewTV)
1870 NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);
1871 if (!NewFV)
1872 NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);
1873
1874 SelectInst *NewSel = SelectInst::Create(SI->getCondition(), NewTV, NewFV);
1875
1876 // Preserve metadata that remains valid for the transformed select including
1877 // source location information.
1878 NewSel->copyMetadata(*SI,
1879 {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1880 LLVMContext::MD_dbg});
1881
1882 return NewSel;
1883}
1884
1886 Value *InValue, BasicBlock *InBB,
1887 const DataLayout &DL,
1888 const SimplifyQuery SQ) {
1889 // NB: It is a precondition of this transform that the operands be
1890 // phi translatable!
1892 for (Value *Op : I.operands()) {
1893 if (Op == PN)
1894 Ops.push_back(InValue);
1895 else
1896 Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));
1897 }
1898
1899 // Don't consider the simplification successful if we get back a constant
1900 // expression. That's just an instruction in hiding.
1901 // Also reject the case where we simplify back to the phi node. We wouldn't
1902 // be able to remove it in that case.
1904 &I, Ops, SQ.getWithInstruction(InBB->getTerminator()));
1905 if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr()))
1906 return NewVal;
1907
1908 // Check if incoming PHI value can be replaced with constant
1909 // based on implied condition.
1910 CondBrInst *TerminatorBI = dyn_cast<CondBrInst>(InBB->getTerminator());
1911 const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I);
1912 if (TerminatorBI &&
1913 TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) {
1914 bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent();
1915 std::optional<bool> ImpliedCond = isImpliedCondition(
1916 TerminatorBI->getCondition(), ICmp->getCmpPredicate(), Ops[0], Ops[1],
1917 DL, LHSIsTrue);
1918 if (ImpliedCond)
1919 return ConstantInt::getBool(I.getType(), ImpliedCond.value());
1920 }
1921
1922 return nullptr;
1923}
1924
1925/// In some cases it is beneficial to fold a select into a binary operator.
1926/// For example:
1927/// %1 = or %in, 4
1928/// %2 = select %cond, %1, %in
1929/// %3 = or %2, 1
1930/// =>
1931/// %1 = select i1 %cond, 5, 1
1932/// %2 = or %1, %in
1934 assert(Op.isAssociative() && "The operation must be associative!");
1935
1936 SelectInst *SI = dyn_cast<SelectInst>(Op.getOperand(0));
1937
1938 Constant *Const;
1939 if (!SI || !match(Op.getOperand(1), m_ImmConstant(Const)) ||
1940 !Op.hasOneUse() || !SI->hasOneUse())
1941 return nullptr;
1942
1943 Value *TV = SI->getTrueValue();
1944 Value *FV = SI->getFalseValue();
1945 Value *Input, *NewTV, *NewFV;
1946 Constant *Const2;
1947
1948 if (TV->hasOneUse() && match(TV, m_BinOp(Op.getOpcode(), m_Specific(FV),
1949 m_ImmConstant(Const2)))) {
1950 NewTV = ConstantFoldBinaryInstruction(Op.getOpcode(), Const, Const2);
1951 NewFV = Const;
1952 Input = FV;
1953 } else if (FV->hasOneUse() &&
1954 match(FV, m_BinOp(Op.getOpcode(), m_Specific(TV),
1955 m_ImmConstant(Const2)))) {
1956 NewTV = Const;
1957 NewFV = ConstantFoldBinaryInstruction(Op.getOpcode(), Const, Const2);
1958 Input = TV;
1959 } else
1960 return nullptr;
1961
1962 if (!NewTV || !NewFV)
1963 return nullptr;
1964
1965 Value *NewSI = Builder.CreateSelect(SI->getCondition(), NewTV, NewFV, "", SI);
1966 return BinaryOperator::Create(Op.getOpcode(), NewSI, Input);
1967}
1968
1970 bool AllowMultipleUses) {
1971 unsigned NumPHIValues = PN->getNumIncomingValues();
1972 if (NumPHIValues == 0)
1973 return nullptr;
1974
1975 // We normally only transform phis with a single use. However, if a PHI has
1976 // multiple uses and they are all the same operation, we can fold *all* of the
1977 // uses into the PHI.
1978 bool OneUse = PN->hasOneUse();
1979 bool IdenticalUsers = false;
1980 if (!AllowMultipleUses && !OneUse) {
1981 // Walk the use list for the instruction, comparing them to I.
1982 for (User *U : PN->users()) {
1984 if (UI != &I && !I.isIdenticalTo(UI))
1985 return nullptr;
1986 }
1987 // Otherwise, we can replace *all* users with the new PHI we form.
1988 IdenticalUsers = true;
1989 }
1990
1991 // Check that all operands are phi-translatable.
1992 for (Value *Op : I.operands()) {
1993 if (Op == PN)
1994 continue;
1995
1996 // Non-instructions never require phi-translation.
1997 auto *I = dyn_cast<Instruction>(Op);
1998 if (!I)
1999 continue;
2000
2001 // Phi-translate can handle phi nodes in the same block.
2002 if (isa<PHINode>(I))
2003 if (I->getParent() == PN->getParent())
2004 continue;
2005
2006 // Operand dominates the block, no phi-translation necessary.
2007 if (DT.dominates(I, PN->getParent()))
2008 continue;
2009
2010 // Not phi-translatable, bail out.
2011 return nullptr;
2012 }
2013
2014 // Check to see whether the instruction can be folded into each phi operand.
2015 // If there is one operand that does not fold, remember the BB it is in.
2016 SmallVector<Value *> NewPhiValues;
2017 SmallVector<unsigned int> OpsToMoveUseToIncomingBB;
2018 bool SeenNonSimplifiedInVal = false;
2019 for (unsigned i = 0; i != NumPHIValues; ++i) {
2020 Value *InVal = PN->getIncomingValue(i);
2021 BasicBlock *InBB = PN->getIncomingBlock(i);
2022
2023 if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) {
2024 NewPhiValues.push_back(NewVal);
2025 continue;
2026 }
2027
2028 // Handle some cases that can't be fully simplified, but where we know that
2029 // the two instructions will fold into one.
2030 auto WillFold = [&]() {
2031 if (!InVal->hasUseList() || !InVal->hasOneUser())
2032 return false;
2033
2034 // icmp of ucmp/scmp with constant will fold to icmp.
2035 const APInt *Ignored;
2036 if (isa<CmpIntrinsic>(InVal) &&
2037 match(&I, m_ICmp(m_Specific(PN), m_APInt(Ignored))))
2038 return true;
2039
2040 // icmp eq zext(bool), 0 will fold to !bool.
2041 if (isa<ZExtInst>(InVal) &&
2042 cast<ZExtInst>(InVal)->getSrcTy()->isIntOrIntVectorTy(1) &&
2043 match(&I,
2045 return true;
2046
2047 return false;
2048 };
2049
2050 if (WillFold()) {
2051 OpsToMoveUseToIncomingBB.push_back(i);
2052 NewPhiValues.push_back(nullptr);
2053 continue;
2054 }
2055
2056 if (!OneUse && !IdenticalUsers)
2057 return nullptr;
2058
2059 if (SeenNonSimplifiedInVal)
2060 return nullptr; // More than one non-simplified value.
2061 SeenNonSimplifiedInVal = true;
2062
2063 // If there is exactly one non-simplified value, we can insert a copy of the
2064 // operation in that block. However, if this is a critical edge, we would
2065 // be inserting the computation on some other paths (e.g. inside a loop).
2066 // Only do this if the pred block is unconditionally branching into the phi
2067 // block. Also, make sure that the pred block is not dead code.
2069 if (!BI || !DT.isReachableFromEntry(InBB))
2070 return nullptr;
2071
2072 NewPhiValues.push_back(nullptr);
2073 OpsToMoveUseToIncomingBB.push_back(i);
2074
2075 // Do not push the operation across a loop backedge. This could result in
2076 // an infinite combine loop, and is generally non-profitable (especially
2077 // if the operation was originally outside the loop).
2078 if (isBackEdge(InBB, PN->getParent()))
2079 return nullptr;
2080 }
2081
2082 // Clone the instruction that uses the phi node and move it into the incoming
2083 // BB because we know that the next iteration of InstCombine will simplify it.
2085 for (auto OpIndex : OpsToMoveUseToIncomingBB) {
2086 Value *Op = PN->getIncomingValue(OpIndex);
2087 BasicBlock *OpBB = PN->getIncomingBlock(OpIndex);
2088
2089 Instruction *Clone = Clones.lookup(OpBB);
2090 if (!Clone) {
2091 Clone = I.clone();
2092 for (Use &U : Clone->operands()) {
2093 if (U == PN)
2094 U = Op;
2095 else
2096 U = U->DoPHITranslation(PN->getParent(), OpBB);
2097 }
2098 Clone = InsertNewInstBefore(Clone, OpBB->getTerminator()->getIterator());
2099 Clones.insert({OpBB, Clone});
2100 // We may have speculated the instruction.
2102 }
2103
2104 NewPhiValues[OpIndex] = Clone;
2105 }
2106
2107 // Okay, we can do the transformation: create the new PHI node.
2108 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
2109 InsertNewInstBefore(NewPN, PN->getIterator());
2110 NewPN->takeName(PN);
2111 NewPN->setDebugLoc(PN->getDebugLoc());
2112
2113 for (unsigned i = 0; i != NumPHIValues; ++i)
2114 NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));
2115
2116 if (IdenticalUsers) {
2117 // Collect and deduplicate users up-front to avoid iterator invalidation.
2119 for (User *U : PN->users()) {
2121 if (User == &I)
2122 continue;
2123 ToReplace.insert(User);
2124 }
2125 for (Instruction *I : ToReplace) {
2126 replaceInstUsesWith(*I, NewPN);
2128 }
2129 OneUse = true;
2130 }
2131
2132 if (OneUse) {
2133 replaceAllDbgUsesWith(*PN, *NewPN, *PN, DT);
2134 }
2135 return replaceInstUsesWith(I, NewPN);
2136}
2137
2139 if (!BO.isAssociative())
2140 return nullptr;
2141
2142 // Find the interleaved binary ops.
2143 auto Opc = BO.getOpcode();
2144 auto *BO0 = dyn_cast<BinaryOperator>(BO.getOperand(0));
2145 auto *BO1 = dyn_cast<BinaryOperator>(BO.getOperand(1));
2146 if (!BO0 || !BO1 || !BO0->hasNUses(2) || !BO1->hasNUses(2) ||
2147 BO0->getOpcode() != Opc || BO1->getOpcode() != Opc ||
2148 !BO0->isAssociative() || !BO1->isAssociative() ||
2149 BO0->getParent() != BO1->getParent())
2150 return nullptr;
2151
2152 assert(BO.isCommutative() && BO0->isCommutative() && BO1->isCommutative() &&
2153 "Expected commutative instructions!");
2154
2155 // Find the matching phis, forming the recurrences.
2156 PHINode *PN0, *PN1;
2157 Value *Start0, *Step0, *Start1, *Step1;
2158 if (!matchSimpleRecurrence(BO0, PN0, Start0, Step0) || !PN0->hasOneUse() ||
2159 !matchSimpleRecurrence(BO1, PN1, Start1, Step1) || !PN1->hasOneUse() ||
2160 PN0->getParent() != PN1->getParent())
2161 return nullptr;
2162
2163 assert(PN0->getNumIncomingValues() == 2 && PN1->getNumIncomingValues() == 2 &&
2164 "Expected PHIs with two incoming values!");
2165
2166 // Convert the start and step values to constants.
2167 auto *Init0 = dyn_cast<Constant>(Start0);
2168 auto *Init1 = dyn_cast<Constant>(Start1);
2169 auto *C0 = dyn_cast<Constant>(Step0);
2170 auto *C1 = dyn_cast<Constant>(Step1);
2171 if (!Init0 || !Init1 || !C0 || !C1)
2172 return nullptr;
2173
2174 // Fold the recurrence constants.
2175 auto *Init = ConstantFoldBinaryInstruction(Opc, Init0, Init1);
2176 auto *C = ConstantFoldBinaryInstruction(Opc, C0, C1);
2177 if (!Init || !C)
2178 return nullptr;
2179
2180 // Create the reduced PHI.
2181 auto *NewPN = PHINode::Create(PN0->getType(), PN0->getNumIncomingValues(),
2182 "reduced.phi");
2183
2184 // Create the new binary op.
2185 auto *NewBO = BinaryOperator::Create(Opc, NewPN, C);
2186 if (Opc == Instruction::FAdd || Opc == Instruction::FMul) {
2187 // Intersect FMF flags for FADD and FMUL.
2188 FastMathFlags Intersect = BO0->getFastMathFlags() &
2189 BO1->getFastMathFlags() & BO.getFastMathFlags();
2190 NewBO->setFastMathFlags(Intersect);
2191 } else {
2192 OverflowTracking Flags;
2193 Flags.AllKnownNonNegative = false;
2194 Flags.AllKnownNonZero = false;
2195 Flags.mergeFlags(*BO0);
2196 Flags.mergeFlags(*BO1);
2197 Flags.mergeFlags(BO);
2198 Flags.applyFlags(*NewBO);
2199 }
2200 NewBO->takeName(&BO);
2201
2202 for (unsigned I = 0, E = PN0->getNumIncomingValues(); I != E; ++I) {
2203 auto *V = PN0->getIncomingValue(I);
2204 auto *BB = PN0->getIncomingBlock(I);
2205 if (V == Init0) {
2206 assert(((PN1->getIncomingValue(0) == Init1 &&
2207 PN1->getIncomingBlock(0) == BB) ||
2208 (PN1->getIncomingValue(1) == Init1 &&
2209 PN1->getIncomingBlock(1) == BB)) &&
2210 "Invalid incoming block!");
2211 NewPN->addIncoming(Init, BB);
2212 } else if (V == BO0) {
2213 assert(((PN1->getIncomingValue(0) == BO1 &&
2214 PN1->getIncomingBlock(0) == BB) ||
2215 (PN1->getIncomingValue(1) == BO1 &&
2216 PN1->getIncomingBlock(1) == BB)) &&
2217 "Invalid incoming block!");
2218 NewPN->addIncoming(NewBO, BB);
2219 } else
2220 llvm_unreachable("Unexpected incoming value!");
2221 }
2222
2223 LLVM_DEBUG(dbgs() << " Combined " << *PN0 << "\n " << *BO0
2224 << "\n with " << *PN1 << "\n " << *BO1
2225 << '\n');
2226
2227 // Insert the new recurrence and remove the old (dead) ones.
2228 InsertNewInstWith(NewPN, PN0->getIterator());
2229 InsertNewInstWith(NewBO, BO0->getIterator());
2230
2237
2238 return replaceInstUsesWith(BO, NewBO);
2239}
2240
2242 // Attempt to fold binary operators whose operands are simple recurrences.
2243 if (auto *NewBO = foldBinopWithRecurrence(BO))
2244 return NewBO;
2245
2246 // TODO: This should be similar to the incoming values check in foldOpIntoPhi:
2247 // we are guarding against replicating the binop in >1 predecessor.
2248 // This could miss matching a phi with 2 constant incoming values.
2249 auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));
2250 auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));
2251 if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||
2252 Phi0->getNumOperands() != Phi1->getNumOperands())
2253 return nullptr;
2254
2255 // TODO: Remove the restriction for binop being in the same block as the phis.
2256 if (BO.getParent() != Phi0->getParent() ||
2257 BO.getParent() != Phi1->getParent())
2258 return nullptr;
2259
2260 // Fold if there is at least one specific constant value in phi0 or phi1's
2261 // incoming values that comes from the same block and this specific constant
2262 // value can be used to do optimization for specific binary operator.
2263 // For example:
2264 // %phi0 = phi i32 [0, %bb0], [%i, %bb1]
2265 // %phi1 = phi i32 [%j, %bb0], [0, %bb1]
2266 // %add = add i32 %phi0, %phi1
2267 // ==>
2268 // %add = phi i32 [%j, %bb0], [%i, %bb1]
2270 /*AllowRHSConstant*/ false);
2271 if (C) {
2272 SmallVector<Value *, 4> NewIncomingValues;
2273 auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {
2274 auto &Phi0Use = std::get<0>(T);
2275 auto &Phi1Use = std::get<1>(T);
2276 if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))
2277 return false;
2278 Value *Phi0UseV = Phi0Use.get();
2279 Value *Phi1UseV = Phi1Use.get();
2280 if (Phi0UseV == C)
2281 NewIncomingValues.push_back(Phi1UseV);
2282 else if (Phi1UseV == C)
2283 NewIncomingValues.push_back(Phi0UseV);
2284 else
2285 return false;
2286 return true;
2287 };
2288
2289 if (all_of(zip(Phi0->operands(), Phi1->operands()),
2290 CanFoldIncomingValuePair)) {
2291 PHINode *NewPhi =
2292 PHINode::Create(Phi0->getType(), Phi0->getNumOperands());
2293 assert(NewIncomingValues.size() == Phi0->getNumOperands() &&
2294 "The number of collected incoming values should equal the number "
2295 "of the original PHINode operands!");
2296 for (unsigned I = 0; I < Phi0->getNumOperands(); I++)
2297 NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));
2298 return NewPhi;
2299 }
2300 }
2301
2302 if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)
2303 return nullptr;
2304
2305 // Match a pair of incoming constants for one of the predecessor blocks.
2306 BasicBlock *ConstBB, *OtherBB;
2307 Constant *C0, *C1;
2308 if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {
2309 ConstBB = Phi0->getIncomingBlock(0);
2310 OtherBB = Phi0->getIncomingBlock(1);
2311 } else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {
2312 ConstBB = Phi0->getIncomingBlock(1);
2313 OtherBB = Phi0->getIncomingBlock(0);
2314 } else {
2315 return nullptr;
2316 }
2317 if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))
2318 return nullptr;
2319
2320 // The block that we are hoisting to must reach here unconditionally.
2321 // Otherwise, we could be speculatively executing an expensive or
2322 // non-speculative op.
2323 auto *PredBlockBranch = dyn_cast<UncondBrInst>(OtherBB->getTerminator());
2324 if (!PredBlockBranch || !DT.isReachableFromEntry(OtherBB))
2325 return nullptr;
2326
2327 // TODO: This check could be tightened to only apply to binops (div/rem) that
2328 // are not safe to speculatively execute. But that could allow hoisting
2329 // potentially expensive instructions (fdiv for example).
2330 for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)
2332 return nullptr;
2333
2334 // Fold constants for the predecessor block with constant incoming values.
2335 Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL);
2336 if (!NewC)
2337 return nullptr;
2338
2339 // Make a new binop in the predecessor block with the non-constant incoming
2340 // values.
2341 Builder.SetInsertPoint(PredBlockBranch);
2342 Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),
2343 Phi0->getIncomingValueForBlock(OtherBB),
2344 Phi1->getIncomingValueForBlock(OtherBB));
2345 if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))
2346 NotFoldedNewBO->copyIRFlags(&BO);
2347
2348 // Replace the binop with a phi of the new values. The old phis are dead.
2349 PHINode *NewPhi = PHINode::Create(BO.getType(), 2);
2350 NewPhi->addIncoming(NewBO, OtherBB);
2351 NewPhi->addIncoming(NewC, ConstBB);
2352 return NewPhi;
2353}
2354
2356 auto TryFoldOperand = [&](unsigned OpIdx,
2357 bool IsOtherParamConst) -> Instruction * {
2358 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(OpIdx)))
2359 return FoldOpIntoSelect(I, Sel, false, !IsOtherParamConst);
2360 if (auto *PN = dyn_cast<PHINode>(I.getOperand(OpIdx)))
2361 return foldOpIntoPhi(I, PN);
2362 return nullptr;
2363 };
2364
2365 if (Instruction *NewI =
2366 TryFoldOperand(/*OpIdx=*/0, isa<Constant>(I.getOperand(1))))
2367 return NewI;
2368 return TryFoldOperand(/*OpIdx=*/1, isa<Constant>(I.getOperand(0)));
2369}
2370
2372 // If this GEP has only 0 indices, it is the same pointer as
2373 // Src. If Src is not a trivial GEP too, don't combine
2374 // the indices.
2375 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
2376 !Src.hasOneUse())
2377 return false;
2378 return true;
2379}
2380
2381/// Find a constant NewC that has property:
2382/// shuffle(NewC, poison, ShMask) = C
2383/// for lanes that select NewC. Lanes that select the poison operand are not
2384/// constrained.
2385/// Returns nullptr if such a constant does not exist e.g. ShMask=<0,0> C=<1,2>
2386///
2387/// A 1-to-1 mapping is not required. Example:
2388/// ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <poison,5,6,poison>
2390 VectorType *NewCTy) {
2391 if (isa<ScalableVectorType>(NewCTy)) {
2392 Constant *Splat = C->getSplatValue();
2393 if (!Splat)
2394 return nullptr;
2396 }
2397
2398 if (cast<FixedVectorType>(NewCTy)->getNumElements() >
2399 cast<FixedVectorType>(C->getType())->getNumElements())
2400 return nullptr;
2401
2402 unsigned NewCNumElts = cast<FixedVectorType>(NewCTy)->getNumElements();
2403 PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType());
2404 SmallVector<Constant *, 16> NewVecC(NewCNumElts, PoisonScalar);
2405 unsigned NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
2406 for (unsigned I = 0; I < NumElts; ++I) {
2407 Constant *CElt = C->getAggregateElement(I);
2408 if (ShMask[I] >= 0) {
2409 int MaskElt = ShMask[I];
2410 if (MaskElt >= (int)NewCNumElts)
2411 continue;
2412
2413 Constant *NewCElt = NewVecC[MaskElt];
2414 // Bail out if:
2415 // 1. The constant vector contains a constant expression.
2416 // 2. The shuffle needs an element of the constant vector that can't
2417 // be mapped to a new constant vector.
2418 // 3. This is a widening shuffle that copies elements of V1 into the
2419 // extended elements (extending with poison is allowed).
2420 if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) ||
2421 I >= NewCNumElts)
2422 return nullptr;
2423 NewVecC[MaskElt] = CElt;
2424 }
2425 }
2426 return ConstantVector::get(NewVecC);
2427}
2428
2429// Get the result of `Vector Op Splat` (or Splat Op Vector if \p SplatLHS).
2431 Constant *Splat, bool SplatLHS,
2432 const DataLayout &DL) {
2433 ElementCount EC = cast<VectorType>(Vector->getType())->getElementCount();
2435 Constant *RHS = Vector;
2436 if (!SplatLHS)
2437 std::swap(LHS, RHS);
2438 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
2439}
2440
2441template <Intrinsic::ID SpliceID>
2443 InstCombiner::BuilderTy &Builder) {
2444 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
2445 auto CreateBinOpSplice = [&](Value *X, Value *Y, Value *Offset) {
2446 Value *V = Builder.CreateBinOp(Inst.getOpcode(), X, Y, Inst.getName());
2447 if (auto *BO = dyn_cast<BinaryOperator>(V))
2448 BO->copyIRFlags(&Inst);
2449 Module *M = Inst.getModule();
2450 Function *F = Intrinsic::getOrInsertDeclaration(M, SpliceID, V->getType());
2451 return CallInst::Create(F, {V, PoisonValue::get(V->getType()), Offset});
2452 };
2453 Value *V1, *V2, *Offset;
2454 if (match(LHS,
2456 // Op(splice(V1, poison, offset), splice(V2, poison, offset))
2457 // -> splice(Op(V1, V2), poison, offset)
2459 m_Specific(Offset))) &&
2460 (LHS->hasOneUse() || RHS->hasOneUse() ||
2461 (LHS == RHS && LHS->hasNUses(2))))
2462 return CreateBinOpSplice(V1, V2, Offset);
2463
2464 // Op(splice(V1, poison, offset), RHSSplat)
2465 // -> splice(Op(V1, RHSSplat), poison, offset)
2466 if (LHS->hasOneUse() && isSplatValue(RHS))
2467 return CreateBinOpSplice(V1, RHS, Offset);
2468 }
2469 // Op(LHSSplat, splice(V2, poison, offset))
2470 // -> splice(Op(LHSSplat, V2), poison, offset)
2471 else if (isSplatValue(LHS) &&
2473 m_Value(Offset)))))
2474 return CreateBinOpSplice(LHS, V2, Offset);
2475
2476 // TODO: Fold binops of the form
2477 // Op(splice(poison, V1, offset), splice(poison, V2, offset))
2478 // -> splice(poison, Op(V1, V2), offset)
2479
2480 return nullptr;
2481}
2482
2484 if (!isa<VectorType>(Inst.getType()))
2485 return nullptr;
2486
2487 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
2488 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
2489 assert(cast<VectorType>(LHS->getType())->getElementCount() ==
2490 cast<VectorType>(Inst.getType())->getElementCount());
2491 assert(cast<VectorType>(RHS->getType())->getElementCount() ==
2492 cast<VectorType>(Inst.getType())->getElementCount());
2493
2494 auto foldConstantsThroughSubVectorInsertSplat =
2495 [&](Value *MaybeSubVector, Value *MaybeSplat,
2496 bool SplatLHS) -> Instruction * {
2497 Value *Idx;
2498 Constant *Splat, *SubVector, *Dest;
2499 if (!match(MaybeSplat, m_Splat(m_Constant(Splat))) ||
2500 !match(MaybeSubVector,
2501 m_VectorInsert(m_Constant(Dest), m_Constant(SubVector),
2502 m_Value(Idx))))
2503 return nullptr;
2504 SubVector =
2505 constantFoldBinOpWithSplat(Opcode, SubVector, Splat, SplatLHS, DL);
2506 Dest = constantFoldBinOpWithSplat(Opcode, Dest, Splat, SplatLHS, DL);
2507 if (!SubVector || !Dest)
2508 return nullptr;
2509 auto *InsertVector =
2510 Builder.CreateInsertVector(Dest->getType(), Dest, SubVector, Idx);
2511 return replaceInstUsesWith(Inst, InsertVector);
2512 };
2513
2514 // If one operand is a constant splat and the other operand is a
2515 // `vector.insert` where both the destination and subvector are constant,
2516 // apply the operation to both the destination and subvector, returning a new
2517 // constant `vector.insert`. This helps constant folding for scalable vectors.
2518 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2519 /*MaybeSubVector=*/LHS, /*MaybeSplat=*/RHS, /*SplatLHS=*/false))
2520 return Folded;
2521 if (Instruction *Folded = foldConstantsThroughSubVectorInsertSplat(
2522 /*MaybeSubVector=*/RHS, /*MaybeSplat=*/LHS, /*SplatLHS=*/true))
2523 return Folded;
2524
2525 auto createBinOpReverse = [&](Value *X, Value *Y) {
2526 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
2527 if (auto *BO = dyn_cast<BinaryOperator>(V))
2528 BO->copyIRFlags(&Inst);
2529 Module *M = Inst.getModule();
2531 M, Intrinsic::vector_reverse, V->getType());
2532 return CallInst::Create(F, V);
2533 };
2534
2535 // NOTE: Reverse shuffles don't require the speculative execution protection
2536 // below because they don't affect which lanes take part in the computation.
2537
2538 Value *V1, *V2;
2539 if (match(LHS, m_VecReverse(m_Value(V1)))) {
2540 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2541 if (match(RHS, m_VecReverse(m_Value(V2))) &&
2542 (LHS->hasOneUse() || RHS->hasOneUse() ||
2543 (LHS == RHS && LHS->hasNUses(2))))
2544 return createBinOpReverse(V1, V2);
2545
2546 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2547 if (LHS->hasOneUse() && isSplatValue(RHS))
2548 return createBinOpReverse(V1, RHS);
2549 }
2550 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2551 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
2552 return createBinOpReverse(LHS, V2);
2553
2554 auto createBinOpVPReverse = [&](Value *X, Value *Y, Value *EVL) {
2555 Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());
2556 if (auto *BO = dyn_cast<BinaryOperator>(V))
2557 BO->copyIRFlags(&Inst);
2558
2559 ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
2560 Value *AllTrueMask = Builder.CreateVectorSplat(EC, Builder.getTrue());
2561 Module *M = Inst.getModule();
2563 M, Intrinsic::experimental_vp_reverse, V->getType());
2564 return CallInst::Create(F, {V, AllTrueMask, EVL});
2565 };
2566
2567 Value *EVL;
2569 m_Value(V1), m_AllOnes(), m_Value(EVL)))) {
2570 // Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))
2572 m_Value(V2), m_AllOnes(), m_Specific(EVL))) &&
2573 (LHS->hasOneUse() || RHS->hasOneUse() ||
2574 (LHS == RHS && LHS->hasNUses(2))))
2575 return createBinOpVPReverse(V1, V2, EVL);
2576
2577 // Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))
2578 if (LHS->hasOneUse() && isSplatValue(RHS))
2579 return createBinOpVPReverse(V1, RHS, EVL);
2580 }
2581 // Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))
2582 else if (isSplatValue(LHS) &&
2584 m_Value(V2), m_AllOnes(), m_Value(EVL))))
2585 return createBinOpVPReverse(LHS, V2, EVL);
2586
2587 if (Instruction *Folded =
2589 return Folded;
2590 if (Instruction *Folded =
2592 return Folded;
2593
2594 // It may not be safe to reorder shuffles and things like div, urem, etc.
2595 // because we may trap when executing those ops on unknown vector elements.
2596 // See PR20059.
2598 return nullptr;
2599
2600 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
2601 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
2602 if (auto *BO = dyn_cast<BinaryOperator>(XY))
2603 BO->copyIRFlags(&Inst);
2604 return new ShuffleVectorInst(XY, M);
2605 };
2606
2607 // If both arguments of the binary operation are shuffles that use the same
2608 // mask and shuffle within a single vector, move the shuffle after the binop.
2609 ArrayRef<int> Mask;
2610 if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) &&
2611 match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) &&
2612 Inst.getType() == V1->getType() && V1->getType() == V2->getType() &&
2613 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
2614 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
2615 return createBinOpShuffle(V1, V2, Mask);
2616 }
2617
2618 // If both arguments of a commutative binop are select-shuffles that use the
2619 // same mask with commuted operands, the shuffles are unnecessary.
2620 if (Inst.isCommutative() &&
2621 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
2622 match(RHS,
2624 auto *LShuf = cast<ShuffleVectorInst>(LHS);
2625 auto *RShuf = cast<ShuffleVectorInst>(RHS);
2626 // TODO: Allow shuffles that contain undefs in the mask?
2627 // That is legal, but it reduces undef knowledge.
2628 // TODO: Allow arbitrary shuffles by shuffling after binop?
2629 // That might be legal, but we have to deal with poison.
2630 if (LShuf->isSelect() &&
2631 !is_contained(LShuf->getShuffleMask(), PoisonMaskElem) &&
2632 RShuf->isSelect() &&
2633 !is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) {
2634 // Example:
2635 // LHS = shuffle V1, V2, <0, 5, 6, 3>
2636 // RHS = shuffle V2, V1, <0, 5, 6, 3>
2637 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
2638 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
2639 NewBO->copyIRFlags(&Inst);
2640 return NewBO;
2641 }
2642 }
2643
2644 // If one argument is a shuffle within one vector and the other is a constant,
2645 // try moving the shuffle after the binary operation. This canonicalization
2646 // intends to move shuffles closer to other shuffles and binops closer to
2647 // other binops, so they can be folded. It may also enable demanded elements
2648 // transforms.
2649 Constant *C;
2651 m_Mask(Mask))),
2652 m_ImmConstant(C)))) {
2653 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() &&
2654 "Shuffle should not change scalar type");
2655
2656 bool ConstOp1 = isa<Constant>(RHS);
2657 if (Constant *NewC =
2658 unshuffleConstant(Mask, C, cast<VectorType>(V1->getType()))) {
2659 // For fixed vectors, lanes of NewC not used by the shuffle will be poison
2660 // which will cause UB for div/rem. Mask them with a safe constant.
2661 if (isa<FixedVectorType>(V1->getType()) && Inst.isIntDivRem())
2662 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
2663
2664 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
2665 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
2666 Value *NewLHS = ConstOp1 ? V1 : NewC;
2667 Value *NewRHS = ConstOp1 ? NewC : V1;
2668 return createBinOpShuffle(NewLHS, NewRHS, Mask);
2669 }
2670 }
2671
2672 // Try to reassociate to sink a splat shuffle after a binary operation.
2673 if (Inst.isAssociative() && Inst.isCommutative()) {
2674 // Canonicalize shuffle operand as LHS.
2675 if (isa<ShuffleVectorInst>(RHS))
2676 std::swap(LHS, RHS);
2677
2678 Value *X;
2679 ArrayRef<int> MaskC;
2680 int SplatIndex;
2681 Value *Y, *OtherOp;
2682 if (!match(LHS,
2683 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
2684 !match(MaskC, m_SplatOrPoisonMask(SplatIndex)) ||
2685 X->getType() != Inst.getType() ||
2686 !match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))
2687 return nullptr;
2688
2689 // FIXME: This may not be safe if the analysis allows undef elements. By
2690 // moving 'Y' before the splat shuffle, we are implicitly assuming
2691 // that it is not undef/poison at the splat index.
2692 if (isSplatValue(OtherOp, SplatIndex)) {
2693 std::swap(Y, OtherOp);
2694 } else if (!isSplatValue(Y, SplatIndex)) {
2695 return nullptr;
2696 }
2697
2698 // X and Y are splatted values, so perform the binary operation on those
2699 // values followed by a splat followed by the 2nd binary operation:
2700 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
2701 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
2702 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
2703 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
2704 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
2705
2706 // Intersect FMF on both new binops. Other (poison-generating) flags are
2707 // dropped to be safe.
2708 if (isa<FPMathOperator>(R)) {
2709 R->copyFastMathFlags(&Inst);
2710 R->andIRFlags(RHS);
2711 }
2712 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
2713 NewInstBO->copyIRFlags(R);
2714 return R;
2715 }
2716
2717 return nullptr;
2718}
2719
2720/// Try to narrow the width of a binop if at least 1 operand is an extend of
2721/// of a value. This requires a potentially expensive known bits check to make
2722/// sure the narrow op does not overflow.
2723Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
2724 // We need at least one extended operand.
2725 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
2726
2727 // If this is a sub, we swap the operands since we always want an extension
2728 // on the RHS. The LHS can be an extension or a constant.
2729 if (BO.getOpcode() == Instruction::Sub)
2730 std::swap(Op0, Op1);
2731
2732 Value *X;
2733 bool IsSext = match(Op0, m_SExt(m_Value(X)));
2734 if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
2735 return nullptr;
2736
2737 // If both operands are the same extension from the same source type and we
2738 // can eliminate at least one (hasOneUse), this might work.
2739 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
2740 Value *Y;
2741 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
2742 cast<Operator>(Op1)->getOpcode() == CastOpc &&
2743 (Op0->hasOneUse() || Op1->hasOneUse()))) {
2744 // If that did not match, see if we have a suitable constant operand.
2745 // Truncating and extending must produce the same constant.
2746 Constant *WideC;
2747 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
2748 return nullptr;
2749 Constant *NarrowC = getLosslessInvCast(WideC, X->getType(), CastOpc, DL);
2750 if (!NarrowC)
2751 return nullptr;
2752 Y = NarrowC;
2753 }
2754
2755 // Swap back now that we found our operands.
2756 if (BO.getOpcode() == Instruction::Sub)
2757 std::swap(X, Y);
2758
2759 // Both operands have narrow versions. Last step: the math must not overflow
2760 // in the narrow width.
2761 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
2762 return nullptr;
2763
2764 // bo (ext X), (ext Y) --> ext (bo X, Y)
2765 // bo (ext X), C --> ext (bo X, C')
2766 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
2767 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
2768 if (IsSext)
2769 NewBinOp->setHasNoSignedWrap();
2770 else
2771 NewBinOp->setHasNoUnsignedWrap();
2772 }
2773 return CastInst::Create(CastOpc, NarrowBO, BO.getType());
2774}
2775
2776/// Determine nowrap flags for (gep (gep p, x), y) to (gep p, (x + y))
2777/// transform.
2782
2783/// Thread a GEP operation with constant indices through the constant true/false
2784/// arms of a select.
2786 InstCombiner::BuilderTy &Builder) {
2787 if (!GEP.hasAllConstantIndices())
2788 return nullptr;
2789
2790 Instruction *Sel;
2791 Value *Cond;
2792 Constant *TrueC, *FalseC;
2793 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
2794 !match(Sel,
2795 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
2796 return nullptr;
2797
2798 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
2799 // Propagate 'inbounds' and metadata from existing instructions.
2800 // Note: using IRBuilder to create the constants for efficiency.
2801 SmallVector<Value *, 4> IndexC(GEP.indices());
2802 GEPNoWrapFlags NW = GEP.getNoWrapFlags();
2803 Type *Ty = GEP.getSourceElementType();
2804 Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", NW);
2805 Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", NW);
2806 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
2807}
2808
2809// Canonicalization:
2810// gep T, (gep i8, base, C1), (Index + C2) into
2811// gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index
2813 GEPOperator *Src,
2814 InstCombinerImpl &IC) {
2815 if (GEP.getNumIndices() != 1)
2816 return nullptr;
2817 auto &DL = IC.getDataLayout();
2818 Value *Base;
2819 const APInt *C1;
2820 if (!match(Src, m_PtrAdd(m_Value(Base), m_APInt(C1))))
2821 return nullptr;
2822 Value *VarIndex;
2823 const APInt *C2;
2824 Type *PtrTy = Src->getType()->getScalarType();
2825 unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(PtrTy);
2826 if (!match(GEP.getOperand(1), m_AddLike(m_Value(VarIndex), m_APInt(C2))))
2827 return nullptr;
2828 if (C1->getBitWidth() != IndexSizeInBits ||
2829 C2->getBitWidth() != IndexSizeInBits)
2830 return nullptr;
2831 Type *BaseType = GEP.getSourceElementType();
2833 return nullptr;
2834 APInt TypeSize(IndexSizeInBits, DL.getTypeAllocSize(BaseType));
2835 APInt NewOffset = TypeSize * *C2 + *C1;
2836 if (NewOffset.isZero() ||
2837 (Src->hasOneUse() && GEP.getOperand(1)->hasOneUse())) {
2839 if (GEP.hasNoUnsignedWrap() &&
2840 cast<GEPOperator>(Src)->hasNoUnsignedWrap() &&
2841 match(GEP.getOperand(1), m_NUWAddLike(m_Value(), m_Value()))) {
2843 if (GEP.isInBounds() && cast<GEPOperator>(Src)->isInBounds())
2844 Flags |= GEPNoWrapFlags::inBounds();
2845 }
2846
2847 Value *GEPConst =
2848 IC.Builder.CreatePtrAdd(Base, IC.Builder.getInt(NewOffset), "", Flags);
2849 return GetElementPtrInst::Create(BaseType, GEPConst, VarIndex, Flags);
2850 }
2851
2852 return nullptr;
2853}
2854
2855/// Combine constant offsets separated by variable offsets.
2856/// ptradd (ptradd (ptradd p, C1), x), C2 -> ptradd (ptradd p, x), C1+C2
2858 InstCombinerImpl &IC) {
2859 if (!GEP.hasAllConstantIndices())
2860 return nullptr;
2861
2864 auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand());
2865 while (true) {
2866 if (!InnerGEP)
2867 return nullptr;
2868
2869 NW = NW.intersectForReassociate(InnerGEP->getNoWrapFlags());
2870 if (InnerGEP->hasAllConstantIndices())
2871 break;
2872
2873 if (!InnerGEP->hasOneUse())
2874 return nullptr;
2875
2876 Skipped.push_back(InnerGEP);
2877 InnerGEP = dyn_cast<GetElementPtrInst>(InnerGEP->getPointerOperand());
2878 }
2879
2880 // The two constant offset GEPs are directly adjacent: Let normal offset
2881 // merging handle it.
2882 if (Skipped.empty())
2883 return nullptr;
2884
2885 // FIXME: This one-use check is not strictly necessary. Consider relaxing it
2886 // if profitable.
2887 if (!InnerGEP->hasOneUse())
2888 return nullptr;
2889
2890 // Don't bother with vector splats.
2891 Type *Ty = GEP.getType();
2892 if (InnerGEP->getType() != Ty)
2893 return nullptr;
2894
2895 const DataLayout &DL = IC.getDataLayout();
2896 APInt Offset(DL.getIndexTypeSizeInBits(Ty), 0);
2897 if (!GEP.accumulateConstantOffset(DL, Offset) ||
2898 !InnerGEP->accumulateConstantOffset(DL, Offset))
2899 return nullptr;
2900
2901 IC.replaceOperand(*Skipped.back(), 0, InnerGEP->getPointerOperand());
2902 for (GetElementPtrInst *SkippedGEP : Skipped)
2903 SkippedGEP->setNoWrapFlags(NW);
2904
2905 return IC.replaceInstUsesWith(
2906 GEP,
2907 IC.Builder.CreatePtrAdd(Skipped.front(), IC.Builder.getInt(Offset), "",
2908 NW.intersectForOffsetAdd(GEP.getNoWrapFlags())));
2909}
2910
2912 GEPOperator *Src) {
2913 // Combine Indices - If the source pointer to this getelementptr instruction
2914 // is a getelementptr instruction with matching element type, combine the
2915 // indices of the two getelementptr instructions into a single instruction.
2916 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2917 return nullptr;
2918
2919 if (auto *I = canonicalizeGEPOfConstGEPI8(GEP, Src, *this))
2920 return I;
2921
2922 if (auto *I = combineConstantOffsets(GEP, *this))
2923 return I;
2924
2925 if (Src->getResultElementType() != GEP.getSourceElementType())
2926 return nullptr;
2927
2928 // Fold chained GEP with constant base into single GEP:
2929 // gep i8, (gep i8, %base, C1), (select Cond, C2, C3)
2930 // -> gep i8, %base, (select Cond, C1+C2, C1+C3)
2931 if (Src->hasOneUse() && GEP.getNumIndices() == 1 &&
2932 Src->getNumIndices() == 1) {
2933 Value *SrcIdx = *Src->idx_begin();
2934 Value *GEPIdx = *GEP.idx_begin();
2935 const APInt *ConstOffset, *TrueVal, *FalseVal;
2936 Value *Cond;
2937
2938 if ((match(SrcIdx, m_APInt(ConstOffset)) &&
2939 match(GEPIdx,
2940 m_Select(m_Value(Cond), m_APInt(TrueVal), m_APInt(FalseVal)))) ||
2941 (match(GEPIdx, m_APInt(ConstOffset)) &&
2942 match(SrcIdx,
2943 m_Select(m_Value(Cond), m_APInt(TrueVal), m_APInt(FalseVal))))) {
2944 auto *Select = isa<SelectInst>(GEPIdx) ? cast<SelectInst>(GEPIdx)
2945 : cast<SelectInst>(SrcIdx);
2946
2947 // Make sure the select has only one use.
2948 if (!Select->hasOneUse())
2949 return nullptr;
2950
2951 if (TrueVal->getBitWidth() != ConstOffset->getBitWidth() ||
2952 FalseVal->getBitWidth() != ConstOffset->getBitWidth())
2953 return nullptr;
2954
2955 APInt NewTrueVal = *ConstOffset + *TrueVal;
2956 APInt NewFalseVal = *ConstOffset + *FalseVal;
2957 Constant *NewTrue = ConstantInt::get(Select->getType(), NewTrueVal);
2958 Constant *NewFalse = ConstantInt::get(Select->getType(), NewFalseVal);
2959 Value *NewSelect =
2960 Builder.CreateSelect(Cond, NewTrue, NewFalse, /*Name=*/"",
2961 /*MDFrom=*/Select);
2962 GEPNoWrapFlags Flags =
2964 return replaceInstUsesWith(GEP,
2965 Builder.CreateGEP(GEP.getResultElementType(),
2966 Src->getPointerOperand(),
2967 NewSelect, "", Flags));
2968 }
2969 }
2970
2971 // Find out whether the last index in the source GEP is a sequential idx.
2972 bool EndsWithSequential = false;
2973 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2974 I != E; ++I)
2975 EndsWithSequential = I.isSequential();
2976 if (!EndsWithSequential)
2977 return nullptr;
2978
2979 // Replace: gep (gep %P, long B), long A, ...
2980 // With: T = long A+B; gep %P, T, ...
2981 Value *SO1 = Src->getOperand(Src->getNumOperands() - 1);
2982 Value *GO1 = GEP.getOperand(1);
2983
2984 // If they aren't the same type, then the input hasn't been processed
2985 // by the loop above yet (which canonicalizes sequential index types to
2986 // intptr_t). Just avoid transforming this until the input has been
2987 // normalized.
2988 if (SO1->getType() != GO1->getType())
2989 return nullptr;
2990
2991 Value *Sum =
2992 simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2993 // Only do the combine when we are sure the cost after the
2994 // merge is never more than that before the merge.
2995 if (Sum == nullptr)
2996 return nullptr;
2997
2999 Indices.append(Src->op_begin() + 1, Src->op_end() - 1);
3000 Indices.push_back(Sum);
3001 Indices.append(GEP.op_begin() + 2, GEP.op_end());
3002
3003 // Don't create GEPs with more than one non-zero index.
3004 unsigned NumNonZeroIndices = count_if(Indices, [](Value *Idx) {
3005 auto *C = dyn_cast<Constant>(Idx);
3006 return !C || !C->isNullValue();
3007 });
3008 if (NumNonZeroIndices > 1)
3009 return nullptr;
3010
3011 return replaceInstUsesWith(
3012 GEP, Builder.CreateGEP(
3013 Src->getSourceElementType(), Src->getOperand(0), Indices, "",
3015}
3016
3019 bool &DoesConsume, unsigned Depth) {
3020 static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));
3021 // ~(~(X)) -> X.
3022 Value *A, *B;
3023 if (match(V, m_Not(m_Value(A)))) {
3024 DoesConsume = true;
3025 return A;
3026 }
3027
3028 Constant *C;
3029 // Constants can be considered to be not'ed values.
3030 if (match(V, m_ImmConstant(C)))
3031 return ConstantExpr::getNot(C);
3032
3034 return nullptr;
3035
3036 // The rest of the cases require that we invert all uses so don't bother
3037 // doing the analysis if we know we can't use the result.
3038 if (!WillInvertAllUses)
3039 return nullptr;
3040
3041 // Compares can be inverted if all of their uses are being modified to use
3042 // the ~V.
3043 if (auto *I = dyn_cast<CmpInst>(V)) {
3044 if (Builder != nullptr)
3045 return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0),
3046 I->getOperand(1));
3047 return NonNull;
3048 }
3049
3050 // If `V` is of the form `A + B` then `-1 - V` can be folded into
3051 // `(-1 - B) - A` if we are willing to invert all of the uses.
3052 if (match(V, m_Add(m_Value(A), m_Value(B)))) {
3053 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3054 DoesConsume, Depth))
3055 return Builder ? Builder->CreateSub(BV, A) : NonNull;
3056 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3057 DoesConsume, Depth))
3058 return Builder ? Builder->CreateSub(AV, B) : NonNull;
3059 return nullptr;
3060 }
3061
3062 // If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded
3063 // into `A ^ B` if we are willing to invert all of the uses.
3064 if (match(V, m_Xor(m_Value(A), m_Value(B)))) {
3065 if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3066 DoesConsume, Depth))
3067 return Builder ? Builder->CreateXor(A, BV) : NonNull;
3068 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3069 DoesConsume, Depth))
3070 return Builder ? Builder->CreateXor(AV, B) : NonNull;
3071 return nullptr;
3072 }
3073
3074 // If `V` is of the form `B - A` then `-1 - V` can be folded into
3075 // `A + (-1 - B)` if we are willing to invert all of the uses.
3076 if (match(V, m_Sub(m_Value(A), m_Value(B)))) {
3077 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3078 DoesConsume, Depth))
3079 return Builder ? Builder->CreateAdd(AV, B) : NonNull;
3080 return nullptr;
3081 }
3082
3083 // If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded
3084 // into `A s>> B` if we are willing to invert all of the uses.
3085 if (match(V, m_AShr(m_Value(A), m_Value(B)))) {
3086 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3087 DoesConsume, Depth))
3088 return Builder ? Builder->CreateAShr(AV, B) : NonNull;
3089 return nullptr;
3090 }
3091
3092 Value *Cond;
3093 // LogicOps are special in that we canonicalize them at the cost of an
3094 // instruction.
3095 bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
3097 // Selects/min/max with invertible operands are freely invertible
3098 if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) {
3099 bool LocalDoesConsume = DoesConsume;
3100 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr,
3101 LocalDoesConsume, Depth))
3102 return nullptr;
3103 if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3104 LocalDoesConsume, Depth)) {
3105 DoesConsume = LocalDoesConsume;
3106 if (Builder != nullptr) {
3107 Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3108 DoesConsume, Depth);
3109 assert(NotB != nullptr &&
3110 "Unable to build inverted value for known freely invertable op");
3111 if (auto *II = dyn_cast<IntrinsicInst>(V))
3112 return Builder->CreateBinaryIntrinsic(
3113 getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB);
3114 return Builder->CreateSelect(Cond, NotA, NotB, "",
3116 }
3117 return NonNull;
3118 }
3119 }
3120
3121 if (PHINode *PN = dyn_cast<PHINode>(V)) {
3122 bool LocalDoesConsume = DoesConsume;
3124 for (Use &U : PN->operands()) {
3125 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3126 Value *NewIncomingVal = getFreelyInvertedImpl(
3127 U.get(), /*WillInvertAllUses=*/false,
3128 /*Builder=*/nullptr, LocalDoesConsume, MaxAnalysisRecursionDepth - 1);
3129 if (NewIncomingVal == nullptr)
3130 return nullptr;
3131 // Make sure that we can safely erase the original PHI node.
3132 if (NewIncomingVal == V)
3133 return nullptr;
3134 if (Builder != nullptr)
3135 IncomingValues.emplace_back(NewIncomingVal, IncomingBlock);
3136 }
3137
3138 DoesConsume = LocalDoesConsume;
3139 if (Builder != nullptr) {
3141 Builder->SetInsertPoint(PN);
3142 PHINode *NewPN =
3143 Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());
3144 for (auto [Val, Pred] : IncomingValues)
3145 NewPN->addIncoming(Val, Pred);
3146 return NewPN;
3147 }
3148 return NonNull;
3149 }
3150
3151 if (match(V, m_SExtLike(m_Value(A)))) {
3152 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3153 DoesConsume, Depth))
3154 return Builder ? Builder->CreateSExt(AV, V->getType()) : NonNull;
3155 return nullptr;
3156 }
3157
3158 if (match(V, m_Trunc(m_Value(A)))) {
3159 if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3160 DoesConsume, Depth))
3161 return Builder ? Builder->CreateTrunc(AV, V->getType()) : NonNull;
3162 return nullptr;
3163 }
3164
3165 // De Morgan's Laws:
3166 // (~(A | B)) -> (~A & ~B)
3167 // (~(A & B)) -> (~A | ~B)
3168 auto TryInvertAndOrUsingDeMorgan = [&](Instruction::BinaryOps Opcode,
3169 bool IsLogical, Value *A,
3170 Value *B) -> Value * {
3171 bool LocalDoesConsume = DoesConsume;
3172 if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder=*/nullptr,
3173 LocalDoesConsume, Depth))
3174 return nullptr;
3175 if (auto *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,
3176 LocalDoesConsume, Depth)) {
3177 auto *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,
3178 LocalDoesConsume, Depth);
3179 DoesConsume = LocalDoesConsume;
3180 if (!Builder)
3181 return NonNull;
3182 if (IsLogical) {
3183 Value *InvertedLogicalOp = Builder->CreateLogicalOp(
3184 Opcode, NotA, NotB, "",
3186 if (auto *SI = dyn_cast<SelectInst>(InvertedLogicalOp))
3187 SI->swapProfMetadata();
3188 return InvertedLogicalOp;
3189 }
3190 return Builder->CreateBinOp(Opcode, NotA, NotB);
3191 }
3192
3193 return nullptr;
3194 };
3195
3196 if (match(V, m_Or(m_Value(A), m_Value(B))))
3197 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/false, A,
3198 B);
3199
3200 if (match(V, m_And(m_Value(A), m_Value(B))))
3201 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/false, A,
3202 B);
3203
3204 if (match(V, m_LogicalOr(m_Value(A), m_Value(B))))
3205 return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/true, A,
3206 B);
3207
3208 if (match(V, m_LogicalAnd(m_Value(A), m_Value(B))))
3209 return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/true, A,
3210 B);
3211
3212 return nullptr;
3213}
3214
3215/// Return true if we should canonicalize the gep to an i8 ptradd.
3217 Value *PtrOp = GEP.getOperand(0);
3218 Type *GEPEltType = GEP.getSourceElementType();
3219 if (GEPEltType->isIntegerTy(8))
3220 return false;
3221
3222 // Canonicalize scalable GEPs to an explicit offset using the llvm.vscale
3223 // intrinsic. This has better support in BasicAA.
3224 if (GEPEltType->isScalableTy())
3225 return true;
3226
3227 // gep i32 p, mul(O, C) -> gep i8, p, mul(O, C*4) to fold the two multiplies
3228 // together.
3229 if (GEP.getNumIndices() == 1 &&
3230 match(GEP.getOperand(1),
3232 m_Shl(m_Value(), m_ConstantInt())))))
3233 return true;
3234
3235 // gep (gep %p, C1), %x, C2 is expanded so the two constants can
3236 // possibly be merged together.
3237 auto PtrOpGep = dyn_cast<GEPOperator>(PtrOp);
3238 return PtrOpGep && PtrOpGep->hasAllConstantIndices() &&
3239 any_of(GEP.indices(), [](Value *V) {
3240 const APInt *C;
3241 return match(V, m_APInt(C)) && !C->isZero();
3242 });
3243}
3244
3246 IRBuilderBase &Builder) {
3247 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
3248 if (!Op1)
3249 return nullptr;
3250
3251 // Don't fold a GEP into itself through a PHI node. This can only happen
3252 // through the back-edge of a loop. Folding a GEP into itself means that
3253 // the value of the previous iteration needs to be stored in the meantime,
3254 // thus requiring an additional register variable to be live, but not
3255 // actually achieving anything (the GEP still needs to be executed once per
3256 // loop iteration).
3257 if (Op1 == &GEP)
3258 return nullptr;
3259 GEPNoWrapFlags NW = Op1->getNoWrapFlags();
3260
3261 int DI = -1;
3262
3263 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
3264 auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
3265 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||
3266 Op1->getSourceElementType() != Op2->getSourceElementType())
3267 return nullptr;
3268
3269 // As for Op1 above, don't try to fold a GEP into itself.
3270 if (Op2 == &GEP)
3271 return nullptr;
3272
3273 // Keep track of the type as we walk the GEP.
3274 Type *CurTy = nullptr;
3275
3276 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
3277 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
3278 return nullptr;
3279
3280 if (Op1->getOperand(J) != Op2->getOperand(J)) {
3281 if (DI == -1) {
3282 // We have not seen any differences yet in the GEPs feeding the
3283 // PHI yet, so we record this one if it is allowed to be a
3284 // variable.
3285
3286 // The first two arguments can vary for any GEP, the rest have to be
3287 // static for struct slots
3288 if (J > 1) {
3289 assert(CurTy && "No current type?");
3290 if (CurTy->isStructTy())
3291 return nullptr;
3292 }
3293
3294 DI = J;
3295 } else {
3296 // The GEP is different by more than one input. While this could be
3297 // extended to support GEPs that vary by more than one variable it
3298 // doesn't make sense since it greatly increases the complexity and
3299 // would result in an R+R+R addressing mode which no backend
3300 // directly supports and would need to be broken into several
3301 // simpler instructions anyway.
3302 return nullptr;
3303 }
3304 }
3305
3306 // Sink down a layer of the type for the next iteration.
3307 if (J > 0) {
3308 if (J == 1) {
3309 CurTy = Op1->getSourceElementType();
3310 } else {
3311 CurTy =
3312 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
3313 }
3314 }
3315 }
3316
3317 NW &= Op2->getNoWrapFlags();
3318 }
3319
3320 // If not all GEPs are identical we'll have to create a new PHI node.
3321 // Check that the old PHI node has only one use so that it will get
3322 // removed.
3323 if (DI != -1 && !PN->hasOneUse())
3324 return nullptr;
3325
3326 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
3327 NewGEP->setNoWrapFlags(NW);
3328
3329 if (DI == -1) {
3330 // All the GEPs feeding the PHI are identical. Clone one down into our
3331 // BB so that it can be merged with the current GEP.
3332 } else {
3333 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
3334 // into the current block so it can be merged, and create a new PHI to
3335 // set that index.
3336 PHINode *NewPN;
3337 {
3338 IRBuilderBase::InsertPointGuard Guard(Builder);
3339 Builder.SetInsertPoint(PN);
3340 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
3341 PN->getNumOperands());
3342 }
3343
3344 for (auto &I : PN->operands())
3345 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
3346 PN->getIncomingBlock(I));
3347
3348 NewGEP->setOperand(DI, NewPN);
3349 }
3350
3351 NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt());
3352 return NewGEP;
3353}
3354
3356 Value *PtrOp = GEP.getOperand(0);
3357 SmallVector<Value *, 8> Indices(GEP.indices());
3358 Type *GEPType = GEP.getType();
3359 Type *GEPEltType = GEP.getSourceElementType();
3360 if (Value *V =
3361 simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.getNoWrapFlags(),
3362 SQ.getWithInstruction(&GEP)))
3363 return replaceInstUsesWith(GEP, V);
3364
3365 // For vector geps, use the generic demanded vector support.
3366 // Skip if GEP return type is scalable. The number of elements is unknown at
3367 // compile-time.
3368 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
3369 auto VWidth = GEPFVTy->getNumElements();
3370 APInt PoisonElts(VWidth, 0);
3371 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
3372 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
3373 PoisonElts)) {
3374 if (V != &GEP)
3375 return replaceInstUsesWith(GEP, V);
3376 return &GEP;
3377 }
3378 }
3379
3380 // Eliminate unneeded casts for indices, and replace indices which displace
3381 // by multiples of a zero size type with zero.
3382 bool MadeChange = false;
3383
3384 // Index width may not be the same width as pointer width.
3385 // Data layout chooses the right type based on supported integer types.
3386 Type *NewScalarIndexTy =
3387 DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
3388
3390 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
3391 ++I, ++GTI) {
3392 // Skip indices into struct types.
3393 if (GTI.isStruct())
3394 continue;
3395
3396 Type *IndexTy = (*I)->getType();
3397 Type *NewIndexType =
3398 IndexTy->isVectorTy()
3399 ? VectorType::get(NewScalarIndexTy,
3400 cast<VectorType>(IndexTy)->getElementCount())
3401 : NewScalarIndexTy;
3402
3403 // If the element type has zero size then any index over it is equivalent
3404 // to an index of zero, so replace it with zero if it is not zero already.
3405 Type *EltTy = GTI.getIndexedType();
3406 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
3407 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
3408 *I = Constant::getNullValue(NewIndexType);
3409 MadeChange = true;
3410 }
3411
3412 if (IndexTy != NewIndexType) {
3413 // If we are using a wider index than needed for this platform, shrink
3414 // it to what we need. If narrower, sign-extend it to what we need.
3415 // This explicit cast can make subsequent optimizations more obvious.
3416 if (IndexTy->getScalarSizeInBits() <
3417 NewIndexType->getScalarSizeInBits()) {
3418 if (GEP.hasNoUnsignedWrap() && GEP.hasNoUnsignedSignedWrap())
3419 *I = Builder.CreateZExt(*I, NewIndexType, "", /*IsNonNeg=*/true);
3420 else
3421 *I = Builder.CreateSExt(*I, NewIndexType);
3422 } else {
3423 *I = Builder.CreateTrunc(*I, NewIndexType, "", GEP.hasNoUnsignedWrap(),
3424 GEP.hasNoUnsignedSignedWrap());
3425 }
3426 MadeChange = true;
3427 }
3428 }
3429 if (MadeChange)
3430 return &GEP;
3431
3432 // Canonicalize constant GEPs to i8 type.
3433 if (!GEPEltType->isIntegerTy(8) && GEP.hasAllConstantIndices()) {
3434 APInt Offset(DL.getIndexTypeSizeInBits(GEPType), 0);
3435 if (GEP.accumulateConstantOffset(DL, Offset))
3436 return replaceInstUsesWith(
3437 GEP, Builder.CreatePtrAdd(PtrOp, Builder.getInt(Offset), "",
3438 GEP.getNoWrapFlags()));
3439 }
3440
3442 Value *Offset = EmitGEPOffset(cast<GEPOperator>(&GEP));
3443 Value *NewGEP =
3444 Builder.CreatePtrAdd(PtrOp, Offset, "", GEP.getNoWrapFlags());
3445 return replaceInstUsesWith(GEP, NewGEP);
3446 }
3447
3448 // Strip trailing zero indices.
3449 auto *LastIdx = dyn_cast<Constant>(Indices.back());
3450 if (LastIdx && LastIdx->isNullValue() && !LastIdx->getType()->isVectorTy()) {
3451 return replaceInstUsesWith(
3452 GEP, Builder.CreateGEP(GEP.getSourceElementType(), PtrOp,
3453 drop_end(Indices), "", GEP.getNoWrapFlags()));
3454 }
3455
3456 // Strip leading zero indices.
3457 auto *FirstIdx = dyn_cast<Constant>(Indices.front());
3458 if (FirstIdx && FirstIdx->isNullValue() &&
3459 !FirstIdx->getType()->isVectorTy()) {
3461 ++GTI;
3462 if (!GTI.isStruct() && GTI.getSequentialElementStride(DL) ==
3463 DL.getTypeAllocSize(GTI.getIndexedType()))
3464 return replaceInstUsesWith(GEP, Builder.CreateGEP(GTI.getIndexedType(),
3465 GEP.getPointerOperand(),
3466 drop_begin(Indices), "",
3467 GEP.getNoWrapFlags()));
3468 }
3469
3470 // Scalarize vector operands; prefer splat-of-gep.as canonical form.
3471 // Note that this looses information about undef lanes; we run it after
3472 // demanded bits to partially mitigate that loss.
3473 if (GEPType->isVectorTy() && llvm::any_of(GEP.operands(), [](Value *Op) {
3474 return Op->getType()->isVectorTy() && getSplatValue(Op);
3475 })) {
3476 SmallVector<Value *> NewOps;
3477 for (auto &Op : GEP.operands()) {
3478 if (Op->getType()->isVectorTy())
3479 if (Value *Scalar = getSplatValue(Op)) {
3480 NewOps.push_back(Scalar);
3481 continue;
3482 }
3483 NewOps.push_back(Op);
3484 }
3485
3486 Value *Res = Builder.CreateGEP(GEP.getSourceElementType(), NewOps[0],
3487 ArrayRef(NewOps).drop_front(), GEP.getName(),
3488 GEP.getNoWrapFlags());
3489 if (!Res->getType()->isVectorTy()) {
3490 ElementCount EC = cast<VectorType>(GEPType)->getElementCount();
3491 Res = Builder.CreateVectorSplat(EC, Res);
3492 }
3493 return replaceInstUsesWith(GEP, Res);
3494 }
3495
3496 bool SeenNonZeroIndex = false;
3497 for (auto [IdxNum, Idx] : enumerate(Indices)) {
3498 // Ignore one leading zero index.
3499 auto *C = dyn_cast<Constant>(Idx);
3500 if (C && C->isNullValue() && IdxNum == 0)
3501 continue;
3502
3503 if (!SeenNonZeroIndex) {
3504 SeenNonZeroIndex = true;
3505 continue;
3506 }
3507
3508 // GEP has multiple non-zero indices: Split it.
3509 ArrayRef<Value *> FrontIndices = ArrayRef(Indices).take_front(IdxNum);
3510 Value *FrontGEP =
3511 Builder.CreateGEP(GEPEltType, PtrOp, FrontIndices,
3512 GEP.getName() + ".split", GEP.getNoWrapFlags());
3513
3514 SmallVector<Value *> BackIndices;
3515 BackIndices.push_back(Constant::getNullValue(NewScalarIndexTy));
3516 append_range(BackIndices, drop_begin(Indices, IdxNum));
3518 GetElementPtrInst::getIndexedType(GEPEltType, FrontIndices), FrontGEP,
3519 BackIndices, GEP.getNoWrapFlags());
3520 }
3521
3522 // Canonicalize gep %T to gep [sizeof(%T) x i8]:
3523 auto IsCanonicalType = [](Type *Ty) {
3524 if (auto *AT = dyn_cast<ArrayType>(Ty))
3525 Ty = AT->getElementType();
3526 return Ty->isIntegerTy(8);
3527 };
3528 if (Indices.size() == 1 && !IsCanonicalType(GEPEltType)) {
3529 TypeSize Scale = DL.getTypeAllocSize(GEPEltType);
3530 assert(!Scale.isScalable() && "Should have been handled earlier");
3531 Type *NewElemTy = Builder.getInt8Ty();
3532 if (Scale.getFixedValue() != 1)
3533 NewElemTy = ArrayType::get(NewElemTy, Scale.getFixedValue());
3534 GEP.setSourceElementType(NewElemTy);
3535 GEP.setResultElementType(NewElemTy);
3536 // Don't bother revisiting the GEP after this change.
3537 MadeIRChange = true;
3538 }
3539
3540 // Check to see if the inputs to the PHI node are getelementptr instructions.
3541 if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
3542 if (Value *NewPtrOp = foldGEPOfPhi(GEP, PN, Builder))
3543 return replaceOperand(GEP, 0, NewPtrOp);
3544 }
3545
3546 if (auto *Src = dyn_cast<GEPOperator>(PtrOp))
3547 if (Instruction *I = visitGEPOfGEP(GEP, Src))
3548 return I;
3549
3550 if (GEP.getNumIndices() == 1) {
3551 unsigned AS = GEP.getPointerAddressSpace();
3552 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
3553 DL.getIndexSizeInBits(AS)) {
3554 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();
3555
3556 if (TyAllocSize == 1) {
3557 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),
3558 // but only if the result pointer is only used as if it were an integer.
3559 // (The case where the underlying object is the same is handled by
3560 // InstSimplify.)
3561 Value *X = GEP.getPointerOperand();
3562 Value *Y;
3563 if (match(GEP.getOperand(1), m_Sub(m_PtrToIntOrAddr(m_Value(Y)),
3565 GEPType == Y->getType()) {
3566 bool HasNonAddressBits =
3567 DL.getAddressSizeInBits(AS) != DL.getPointerSizeInBits(AS);
3568 bool Changed = GEP.replaceUsesWithIf(Y, [&](Use &U) {
3569 return isa<PtrToAddrInst, ICmpInst>(U.getUser()) ||
3570 (!HasNonAddressBits && isa<PtrToIntInst>(U.getUser()));
3571 });
3572 return Changed ? &GEP : nullptr;
3573 }
3574 } else if (auto *ExactIns =
3575 dyn_cast<PossiblyExactOperator>(GEP.getOperand(1))) {
3576 // Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)
3577 Value *V;
3578 if (ExactIns->isExact()) {
3579 if ((has_single_bit(TyAllocSize) &&
3580 match(GEP.getOperand(1),
3581 m_Shr(m_Value(V),
3582 m_SpecificInt(countr_zero(TyAllocSize))))) ||
3583 match(GEP.getOperand(1),
3584 m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize)))) {
3585 return GetElementPtrInst::Create(Builder.getInt8Ty(),
3586 GEP.getPointerOperand(), V,
3587 GEP.getNoWrapFlags());
3588 }
3589 }
3590 if (ExactIns->isExact() && ExactIns->hasOneUse()) {
3591 // Try to canonicalize non-i8 element type to i8 if the index is an
3592 // exact instruction. If the index is an exact instruction (div/shr)
3593 // with a constant RHS, we can fold the non-i8 element scale into the
3594 // div/shr (similiar to the mul case, just inverted).
3595 const APInt *C;
3596 std::optional<APInt> NewC;
3597 if (has_single_bit(TyAllocSize) &&
3598 match(ExactIns, m_Shr(m_Value(V), m_APInt(C))) &&
3599 C->uge(countr_zero(TyAllocSize)))
3600 NewC = *C - countr_zero(TyAllocSize);
3601 else if (match(ExactIns, m_UDiv(m_Value(V), m_APInt(C)))) {
3602 APInt Quot;
3603 uint64_t Rem;
3604 APInt::udivrem(*C, TyAllocSize, Quot, Rem);
3605 if (Rem == 0)
3606 NewC = Quot;
3607 } else if (match(ExactIns, m_SDiv(m_Value(V), m_APInt(C)))) {
3608 APInt Quot;
3609 int64_t Rem;
3610 APInt::sdivrem(*C, TyAllocSize, Quot, Rem);
3611 // For sdiv we need to make sure we arent creating INT_MIN / -1.
3612 if (!Quot.isAllOnes() && Rem == 0)
3613 NewC = Quot;
3614 }
3615
3616 if (NewC.has_value()) {
3617 Value *NewOp = Builder.CreateExactBinOp(
3618 static_cast<Instruction::BinaryOps>(ExactIns->getOpcode()), V,
3619 ConstantInt::get(V->getType(), *NewC), /*IsExact=*/true);
3620 return GetElementPtrInst::Create(Builder.getInt8Ty(),
3621 GEP.getPointerOperand(), NewOp,
3622 GEP.getNoWrapFlags());
3623 }
3624 }
3625 }
3626 }
3627 }
3628 // We do not handle pointer-vector geps here.
3629 if (GEPType->isVectorTy())
3630 return nullptr;
3631
3632 if (!GEP.isInBounds()) {
3633 unsigned IdxWidth =
3634 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
3635 APInt BasePtrOffset(IdxWidth, 0);
3636 Value *UnderlyingPtrOp =
3637 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, BasePtrOffset);
3638 bool CanBeNull;
3639 uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(
3640 DL, CanBeNull, /*CanBeFreed=*/nullptr);
3641 // We can ignore CanBeFreed here, because inbounds is explicitly allowed to
3642 // refer to a deallocated object.
3643 if (!CanBeNull && DerefBytes != 0) {
3644 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
3645 BasePtrOffset.isNonNegative()) {
3646 APInt AllocSize(IdxWidth, DerefBytes);
3647 if (BasePtrOffset.ule(AllocSize)) {
3649 GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());
3650 }
3651 }
3652 }
3653 }
3654
3655 // nusw + nneg -> nuw
3656 if (GEP.hasNoUnsignedSignedWrap() && !GEP.hasNoUnsignedWrap() &&
3657 all_of(GEP.indices(), [&](Value *Idx) {
3658 return isKnownNonNegative(Idx, SQ.getWithInstruction(&GEP));
3659 })) {
3660 GEP.setNoWrapFlags(GEP.getNoWrapFlags() | GEPNoWrapFlags::noUnsignedWrap());
3661 return &GEP;
3662 }
3663
3664 // These rewrites are trying to preserve inbounds/nuw attributes. So we want
3665 // to do this after having tried to derive "nuw" above.
3666 if (GEP.getNumIndices() == 1) {
3667 // Given (gep p, x+y) we want to determine the common nowrap flags for both
3668 // geps if transforming into (gep (gep p, x), y).
3669 auto GetPreservedNoWrapFlags = [&](bool AddIsNUW) {
3670 // We can preserve both "inbounds nuw", "nusw nuw" and "nuw" if we know
3671 // that x + y does not have unsigned wrap.
3672 if (GEP.hasNoUnsignedWrap() && AddIsNUW)
3673 return GEP.getNoWrapFlags();
3674 return GEPNoWrapFlags::none();
3675 };
3676
3677 // Try to replace ADD + GEP with GEP + GEP.
3678 Value *Idx1, *Idx2;
3679 if (match(GEP.getOperand(1),
3680 m_OneUse(m_AddLike(m_Value(Idx1), m_Value(Idx2))))) {
3681 // %idx = add i64 %idx1, %idx2
3682 // %gep = getelementptr i32, ptr %ptr, i64 %idx
3683 // as:
3684 // %newptr = getelementptr i32, ptr %ptr, i64 %idx1
3685 // %newgep = getelementptr i32, ptr %newptr, i64 %idx2
3686 bool NUW = match(GEP.getOperand(1), m_NUWAddLike(m_Value(), m_Value()));
3687 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3688 auto *NewPtr =
3689 Builder.CreateGEP(GEP.getSourceElementType(), GEP.getPointerOperand(),
3690 Idx1, "", NWFlags);
3691 return replaceInstUsesWith(GEP,
3692 Builder.CreateGEP(GEP.getSourceElementType(),
3693 NewPtr, Idx2, "", NWFlags));
3694 }
3695 ConstantInt *C;
3696 if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAddLike(
3697 m_Value(Idx1), m_ConstantInt(C))))))) {
3698 // %add = add nsw i32 %idx1, idx2
3699 // %sidx = sext i32 %add to i64
3700 // %gep = getelementptr i32, ptr %ptr, i64 %sidx
3701 // as:
3702 // %newptr = getelementptr i32, ptr %ptr, i32 %idx1
3703 // %newgep = getelementptr i32, ptr %newptr, i32 idx2
3704 bool NUW = match(GEP.getOperand(1),
3706 GEPNoWrapFlags NWFlags = GetPreservedNoWrapFlags(NUW);
3707 auto *NewPtr = Builder.CreateGEP(
3708 GEP.getSourceElementType(), GEP.getPointerOperand(),
3709 Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType()), "", NWFlags);
3710 return replaceInstUsesWith(
3711 GEP,
3712 Builder.CreateGEP(GEP.getSourceElementType(), NewPtr,
3713 Builder.CreateSExt(C, GEP.getOperand(1)->getType()),
3714 "", NWFlags));
3715 }
3716 }
3717
3719 return R;
3720
3721 // srem -> (and/urem) for inbounds+nuw GEP
3722 if (Indices.size() == 1 && GEP.isInBounds() && GEP.hasNoUnsignedWrap()) {
3723 Value *X, *Y;
3724
3725 // Match: idx = srem X, Y -- where Y is a power-of-two value.
3726 if (match(Indices[0], m_OneUse(m_SRem(m_Value(X), m_Value(Y)))) &&
3727 isKnownToBeAPowerOfTwo(Y, /*OrZero=*/true, &GEP)) {
3728 // If GEP is inbounds+nuw, the offset cannot be negative
3729 // -> srem by power-of-two can be treated as urem,
3730 // and urem by power-of-two folds to 'and' later.
3731 // OrZero=true is fine here because division by zero is UB.
3732 Instruction *OldIdxI = cast<Instruction>(Indices[0]);
3733 Value *NewIdx = Builder.CreateURem(X, Y, OldIdxI->getName());
3734
3735 return GetElementPtrInst::Create(GEPEltType, PtrOp, {NewIdx},
3736 GEP.getNoWrapFlags());
3737 }
3738 }
3739
3740 return nullptr;
3741}
3742
3744 Instruction *AI) {
3746 return true;
3747 if (auto *LI = dyn_cast<LoadInst>(V))
3748 return isa<GlobalVariable>(LI->getPointerOperand());
3749 // Two distinct allocations will never be equal.
3750 return isAllocLikeFn(V, &TLI) && V != AI;
3751}
3752
3753/// Given a call CB which uses an address UsedV, return true if we can prove the
3754/// call's only possible effect is storing to V.
3755static bool isRemovableWrite(CallBase &CB, Value *UsedV,
3756 const TargetLibraryInfo &TLI) {
3757 if (!CB.use_empty())
3758 // TODO: add recursion if returned attribute is present
3759 return false;
3760
3761 if (CB.isTerminator())
3762 // TODO: remove implementation restriction
3763 return false;
3764
3765 if (!CB.willReturn() || !CB.doesNotThrow())
3766 return false;
3767
3768 // If the only possible side effect of the call is writing to the alloca,
3769 // and the result isn't used, we can safely remove any reads implied by the
3770 // call including those which might read the alloca itself.
3771 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);
3772 return Dest && Dest->Ptr == UsedV;
3773}
3774
3775static std::optional<ModRefInfo>
3777 const TargetLibraryInfo &TLI, bool KnowInit,
3778 unsigned MaxUsers) {
3780 const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI);
3781 Worklist.push_back(AI);
3783
3784 do {
3785 Instruction *PI = Worklist.pop_back_val();
3786 for (User *U : PI->users()) {
3788 if (Users.size() >= MaxUsers)
3789 return std::nullopt;
3790 switch (I->getOpcode()) {
3791 default:
3792 // Give up the moment we see something we can't handle.
3793 return std::nullopt;
3794
3795 case Instruction::AddrSpaceCast:
3796 case Instruction::BitCast:
3797 case Instruction::GetElementPtr:
3798 Users.emplace_back(I);
3799 Worklist.push_back(I);
3800 continue;
3801
3802 case Instruction::ICmp: {
3803 ICmpInst *ICI = cast<ICmpInst>(I);
3804 // We can fold eq/ne comparisons with null to false/true, respectively.
3805 // We also fold comparisons in some conditions provided the alloc has
3806 // not escaped (see isNeverEqualToUnescapedAlloc).
3807 if (!ICI->isEquality())
3808 return std::nullopt;
3809 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
3810 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
3811 return std::nullopt;
3812
3813 // Do not fold compares to aligned_alloc calls, as they may have to
3814 // return null in case the required alignment cannot be satisfied,
3815 // unless we can prove that both alignment and size are valid.
3816 auto AlignmentAndSizeKnownValid = [](CallBase *CB) {
3817 // Check if alignment and size of a call to aligned_alloc is valid,
3818 // that is alignment is a power-of-2 and the size is a multiple of the
3819 // alignment.
3820 const APInt *Alignment;
3821 const APInt *Size;
3822 return match(CB->getArgOperand(0), m_APInt(Alignment)) &&
3823 match(CB->getArgOperand(1), m_APInt(Size)) &&
3824 Alignment->isPowerOf2() && Size->urem(*Alignment).isZero();
3825 };
3826 auto *CB = dyn_cast<CallBase>(AI);
3827 if (CB &&
3828 TLI.getLibFunc(*CB->getCalledFunction()) == LibFunc_aligned_alloc &&
3829 TLI.has(LibFunc_aligned_alloc) && !AlignmentAndSizeKnownValid(CB))
3830 return std::nullopt;
3831 Users.emplace_back(I);
3832 continue;
3833 }
3834
3835 case Instruction::Call:
3836 // Ignore no-op and store intrinsics.
3838 switch (II->getIntrinsicID()) {
3839 default:
3840 return std::nullopt;
3841
3842 case Intrinsic::memmove:
3843 case Intrinsic::memcpy:
3844 case Intrinsic::memset: {
3846 if (MI->isVolatile())
3847 return std::nullopt;
3848 // Note: this could also be ModRef, but we can still interpret that
3849 // as just Mod in that case.
3850 ModRefInfo NewAccess =
3851 MI->getRawDest() == PI ? ModRefInfo::Mod : ModRefInfo::Ref;
3852 if ((Access & ~NewAccess) != ModRefInfo::NoModRef)
3853 return std::nullopt;
3854 Access |= NewAccess;
3855 [[fallthrough]];
3856 }
3857 case Intrinsic::assume:
3858 case Intrinsic::invariant_start:
3859 case Intrinsic::invariant_end:
3860 case Intrinsic::lifetime_start:
3861 case Intrinsic::lifetime_end:
3862 case Intrinsic::objectsize:
3863 Users.emplace_back(I);
3864 continue;
3865 case Intrinsic::launder_invariant_group:
3866 Users.emplace_back(I);
3867 Worklist.push_back(I);
3868 continue;
3869 }
3870 }
3871
3872 if (Family && getFreedOperand(cast<CallBase>(I), &TLI) == PI &&
3873 getAllocationFamily(I, &TLI) == Family) {
3874 Users.emplace_back(I);
3875 continue;
3876 }
3877
3878 if (Family && getReallocatedOperand(cast<CallBase>(I)) == PI &&
3879 getAllocationFamily(I, &TLI) == Family) {
3880 Users.emplace_back(I);
3881 Worklist.push_back(I);
3882 continue;
3883 }
3884
3885 if (!isRefSet(Access) &&
3886 isRemovableWrite(*cast<CallBase>(I), PI, TLI)) {
3888 Users.emplace_back(I);
3889 continue;
3890 }
3891
3892 return std::nullopt;
3893
3894 case Instruction::Store: {
3896 if (SI->isVolatile() || SI->getPointerOperand() != PI)
3897 return std::nullopt;
3898 if (isRefSet(Access))
3899 return std::nullopt;
3901 Users.emplace_back(I);
3902 continue;
3903 }
3904
3905 case Instruction::Load: {
3906 LoadInst *LI = cast<LoadInst>(I);
3907 if (LI->isVolatile() || LI->getPointerOperand() != PI)
3908 return std::nullopt;
3909 if (isModSet(Access))
3910 return std::nullopt;
3912 Users.emplace_back(I);
3913 continue;
3914 }
3915 }
3916 llvm_unreachable("missing a return?");
3917 }
3918 } while (!Worklist.empty());
3919
3921 return Access;
3922}
3923
3926
3927 // If we have a malloc call which is only used in any amount of comparisons to
3928 // null and free calls, delete the calls and replace the comparisons with true
3929 // or false as appropriate.
3930
3931 // This is based on the principle that we can substitute our own allocation
3932 // function (which will never return null) rather than knowledge of the
3933 // specific function being called. In some sense this can change the permitted
3934 // outputs of a program (when we convert a malloc to an alloca, the fact that
3935 // the allocation is now on the stack is potentially visible, for example),
3936 // but we believe in a permissible manner.
3937 //
3938 // Collect into Instruction* first to avoid expensive WeakTrackingVH
3939 // register/unregister overhead; convert to WeakTrackingVH only when the
3940 // site is actually removable.
3942
3943 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
3944 // before each store.
3946 std::unique_ptr<DIBuilder> DIB;
3947 if (isa<AllocaInst>(MI)) {
3948 findDbgUsers(&MI, DVRs);
3949 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
3950 }
3951
3952 // Determine what getInitialValueOfAllocation would return without actually
3953 // allocating the result.
3954 bool KnowInitUndef = false;
3955 bool KnowInitZero = false;
3956 Constant *Init =
3958 if (Init) {
3959 if (isa<UndefValue>(Init))
3960 KnowInitUndef = true;
3961 else if (Init->isNullValue())
3962 KnowInitZero = true;
3963 }
3964 // The various sanitizers don't actually return undef memory, but rather
3965 // memory initialized with special forms of runtime poison
3966 auto &F = *MI.getFunction();
3967 if (F.hasFnAttribute(Attribute::SanitizeMemory) ||
3968 F.hasFnAttribute(Attribute::SanitizeAddress))
3969 KnowInitUndef = false;
3970
3971 auto Removable =
3972 isAllocSiteRemovable(&MI, RawUsers, TLI, KnowInitZero | KnowInitUndef,
3973 CLOpts.max_allocsite_removable_users);
3974 if (Removable) {
3975 SmallVector<WeakTrackingVH, 64> Users(RawUsers.begin(), RawUsers.end());
3976 for (WeakTrackingVH &User : Users) {
3977 // Lowering all @llvm.objectsize and MTI calls first because they may use
3978 // a bitcast/GEP of the alloca we are removing.
3979 if (!User)
3980 continue;
3981
3983
3985 if (II->getIntrinsicID() == Intrinsic::objectsize) {
3986 SmallVector<Instruction *> InsertedInstructions;
3987 Value *Result = lowerObjectSizeCall(
3988 II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions);
3989 for (Instruction *Inserted : InsertedInstructions)
3990 Worklist.add(Inserted);
3991 replaceInstUsesWith(*I, Result);
3993 User = nullptr; // Skip examining in the next loop.
3994 continue;
3995 }
3996 if (auto *MTI = dyn_cast<MemTransferInst>(I)) {
3997 if (KnowInitZero && isRefSet(*Removable)) {
3999 Builder.SetInsertPoint(MTI);
4000 auto *M = Builder.CreateMemSet(
4001 MTI->getRawDest(),
4002 ConstantInt::get(Type::getInt8Ty(MI.getContext()), 0),
4003 MTI->getLength(), MTI->getDestAlign());
4004 M->copyMetadata(*MTI);
4005 }
4006 }
4007 }
4008 }
4009 for (WeakTrackingVH &User : Users) {
4010 if (!User)
4011 continue;
4012
4014
4015 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
4017 *C, ConstantInt::get(C->getType(), C->isFalseWhenEqual()));
4018 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
4019 for (auto *DVR : DVRs)
4020 if (DVR->isAddressOfVariable())
4022 } else {
4023 // Casts, GEP, or anything else: we're about to delete this instruction,
4024 // so it can not have any valid uses.
4026 if (isa<LoadInst>(I)) {
4027 assert(KnowInitZero || KnowInitUndef);
4028 Replace = KnowInitUndef ? UndefValue::get(I->getType())
4029 : Constant::getNullValue(I->getType());
4030 } else
4031 Replace = PoisonValue::get(I->getType());
4033 }
4035 }
4036
4038 // Replace invoke with a NOP intrinsic to maintain the original CFG
4039 Module *M = II->getModule();
4040 Function *F = Intrinsic::getOrInsertDeclaration(M, Intrinsic::donothing);
4041 auto *NewII = InvokeInst::Create(
4042 F, II->getNormalDest(), II->getUnwindDest(), {}, "", II->getParent());
4043 NewII->setDebugLoc(II->getDebugLoc());
4044 }
4045
4046 // Remove debug intrinsics which describe the value contained within the
4047 // alloca. In addition to removing dbg.{declare,addr} which simply point to
4048 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
4049 //
4050 // ```
4051 // define void @foo(i32 %0) {
4052 // %a = alloca i32 ; Deleted.
4053 // store i32 %0, i32* %a
4054 // dbg.value(i32 %0, "arg0") ; Not deleted.
4055 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
4056 // call void @trivially_inlinable_no_op(i32* %a)
4057 // ret void
4058 // }
4059 // ```
4060 //
4061 // This may not be required if we stop describing the contents of allocas
4062 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
4063 // the LowerDbgDeclare utility.
4064 //
4065 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
4066 // "arg0" dbg.value may be stale after the call. However, failing to remove
4067 // the DW_OP_deref dbg.value causes large gaps in location coverage.
4068 //
4069 // FIXME: the Assignment Tracking project has now likely made this
4070 // redundant (and it's sometimes harmful).
4071 for (auto *DVR : DVRs)
4072 if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())
4073 DVR->eraseFromParent();
4074
4075 return eraseInstFromFunction(MI);
4076 }
4077 return nullptr;
4078}
4079
4080/// Move the call to free before a NULL test.
4081///
4082/// Check if this free is accessed after its argument has been test
4083/// against NULL (property 0).
4084/// If yes, it is legal to move this call in its predecessor block.
4085///
4086/// The move is performed only if the block containing the call to free
4087/// will be removed, i.e.:
4088/// 1. it has only one predecessor P, and P has two successors
4089/// 2. it contains the call, noops, and an unconditional branch
4090/// 3. its successor is the same as its predecessor's successor
4091///
4092/// The profitability is out-of concern here and this function should
4093/// be called only if the caller knows this transformation would be
4094/// profitable (e.g., for code size).
4096 const DataLayout &DL) {
4097 Value *Op = FI.getArgOperand(0);
4098 BasicBlock *FreeInstrBB = FI.getParent();
4099 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
4100
4101 // Validate part of constraint #1: Only one predecessor
4102 // FIXME: We can extend the number of predecessor, but in that case, we
4103 // would duplicate the call to free in each predecessor and it may
4104 // not be profitable even for code size.
4105 if (!PredBB)
4106 return nullptr;
4107
4108 // Validate constraint #2: Does this block contains only the call to
4109 // free, noops, and an unconditional branch?
4110 BasicBlock *SuccBB;
4111 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
4112 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
4113 return nullptr;
4114
4115 // If there are only 2 instructions in the block, at this point,
4116 // this is the call to free and unconditional.
4117 // If there are more than 2 instructions, check that they are noops
4118 // i.e., they won't hurt the performance of the generated code.
4119 if (FreeInstrBB->size() != 2) {
4120 for (const Instruction &Inst : *FreeInstrBB) {
4121 if (&Inst == &FI || &Inst == FreeInstrBBTerminator ||
4123 continue;
4124 auto *Cast = dyn_cast<CastInst>(&Inst);
4125 if (!Cast || !Cast->isNoopCast(DL))
4126 return nullptr;
4127 }
4128 }
4129 // Validate the rest of constraint #1 by matching on the pred branch.
4130 Instruction *TI = PredBB->getTerminator();
4131 BasicBlock *TrueBB, *FalseBB;
4132 CmpPredicate Pred;
4133 if (!match(TI, m_Br(m_ICmp(Pred,
4135 m_Specific(Op->stripPointerCasts())),
4136 m_Zero()),
4137 TrueBB, FalseBB)))
4138 return nullptr;
4139 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
4140 return nullptr;
4141
4142 // Validate constraint #3: Ensure the null case just falls through.
4143 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
4144 return nullptr;
4145 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
4146 "Broken CFG: missing edge from predecessor to successor");
4147
4148 // At this point, we know that everything in FreeInstrBB can be moved
4149 // before TI.
4150 for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {
4151 if (&Instr == FreeInstrBBTerminator)
4152 break;
4153 Instr.moveBeforePreserving(TI->getIterator());
4154 }
4155 assert(FreeInstrBB->size() == 1 &&
4156 "Only the branch instruction should remain");
4157
4158 // Now that we've moved the call to free before the NULL check, we have to
4159 // remove any attributes on its parameter that imply it's non-null, because
4160 // those attributes might have only been valid because of the NULL check, and
4161 // we can get miscompiles if we keep them. This is conservative if non-null is
4162 // also implied by something other than the NULL check, but it's guaranteed to
4163 // be correct, and the conservativeness won't matter in practice, since the
4164 // attributes are irrelevant for the call to free itself and the pointer
4165 // shouldn't be used after the call.
4166 AttributeList Attrs = FI.getAttributes();
4167 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);
4168 Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);
4169 if (Dereferenceable.isValid()) {
4170 uint64_t Bytes = Dereferenceable.getDereferenceableBytes();
4171 Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,
4172 Attribute::Dereferenceable);
4173 Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);
4174 }
4175 FI.setAttributes(Attrs);
4176
4177 return &FI;
4178}
4179
4181 // free undef -> unreachable.
4182 if (isa<UndefValue>(Op)) {
4183 // Leave a marker since we can't modify the CFG here.
4185 return eraseInstFromFunction(FI);
4186 }
4187
4188 // If we have 'free null' delete the instruction. This can happen in stl code
4189 // when lots of inlining happens.
4191 return eraseInstFromFunction(FI);
4192
4193 // If we had free(realloc(...)) with no intervening uses, then eliminate the
4194 // realloc() entirely.
4196 if (CI && CI->hasOneUse())
4197 if (Value *ReallocatedOp = getReallocatedOperand(CI))
4198 return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));
4199
4200 // If we optimize for code size, try to move the call to free before the null
4201 // test so that simplify cfg can remove the empty block and dead code
4202 // elimination the branch. I.e., helps to turn something like:
4203 // if (foo) free(foo);
4204 // into
4205 // free(foo);
4206 //
4207 // Note that we can only do this for 'free' and not for any flavor of
4208 // 'operator delete'; there is no 'operator delete' symbol for which we are
4209 // permitted to invent a call, even if we're passing in a null pointer.
4210 if (MinimizeSize) {
4211 if (TLI.getLibFunc(FI) == LibFunc_free && TLI.has(LibFunc_free))
4213 return I;
4214 }
4215
4216 return nullptr;
4217}
4218
4220 Value *RetVal = RI.getReturnValue();
4221 if (!RetVal)
4222 return nullptr;
4223
4224 Function *F = RI.getFunction();
4225 Type *RetTy = RetVal->getType();
4226 if (RetTy->isPointerTy()) {
4227 bool UseProvenance =
4228 F->getAttributes().getRetDereferenceableBytes() > 0 &&
4230 if (F->hasRetAttribute(Attribute::NonNull) || UseProvenance) {
4231 if (Value *V = simplifyNonNullOperand(RetVal, UseProvenance))
4232 return replaceOperand(RI, 0, V);
4233 }
4234 }
4235
4236 if (!AttributeFuncs::isNoFPClassCompatibleType(RetTy))
4237 return nullptr;
4238
4239 FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();
4240 if (ReturnClass == fcNone)
4241 return nullptr;
4242
4243 KnownFPClass KnownClass;
4244 if (SimplifyDemandedFPClass(&RI, 0, ~ReturnClass, KnownClass,
4245 SQ.getWithInstruction(&RI)))
4246 return &RI;
4247
4248 return nullptr;
4249}
4250
4251// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
4253 // Try to remove the previous instruction if it must lead to unreachable.
4254 // This includes instructions like stores and "llvm.assume" that may not get
4255 // removed by simple dead code elimination.
4256 bool Changed = false;
4257 while (Instruction *Prev = I.getPrevNode()) {
4258 // While we theoretically can erase EH, that would result in a block that
4259 // used to start with an EH no longer starting with EH, which is invalid.
4260 // To make it valid, we'd need to fixup predecessors to no longer refer to
4261 // this block, but that changes CFG, which is not allowed in InstCombine.
4262 if (Prev->isEHPad())
4263 break; // Can not drop any more instructions. We're done here.
4264
4266 break; // Can not drop any more instructions. We're done here.
4267 // Otherwise, this instruction can be freely erased,
4268 // even if it is not side-effect free.
4269
4270 // A value may still have uses before we process it here (for example, in
4271 // another unreachable block), so convert those to poison.
4272 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
4273 eraseInstFromFunction(*Prev);
4274 Changed = true;
4275 }
4276 return Changed;
4277}
4278
4283
4285 // If this store is the second-to-last instruction in the basic block
4286 // (excluding debug info) and if the block ends with
4287 // an unconditional branch, try to move the store to the successor block.
4288
4289 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
4290 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
4291 do {
4292 if (BBI != FirstInstr)
4293 --BBI;
4294 } while (BBI != FirstInstr && isa<PseudoProbeInst>(BBI));
4295
4296 return dyn_cast<StoreInst>(BBI);
4297 };
4298
4299 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
4301 return &BI;
4302
4303 return nullptr;
4304}
4305
4308 if (!DeadEdges.insert({From, To}).second)
4309 return;
4310
4311 // Replace phi node operands in successor with poison.
4312 for (PHINode &PN : To->phis())
4313 for (Use &U : PN.incoming_values())
4314 if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) {
4315 replaceUse(U, PoisonValue::get(PN.getType()));
4316 addToWorklist(&PN);
4317 MadeIRChange = true;
4318 }
4319
4320 Worklist.push_back(To);
4321}
4322
4323// Under the assumption that I is unreachable, remove it and following
4324// instructions. Changes are reported directly to MadeIRChange.
4327 BasicBlock *BB = I->getParent();
4328 for (Instruction &Inst : make_early_inc_range(
4329 make_range(std::next(BB->getTerminator()->getReverseIterator()),
4330 std::next(I->getReverseIterator())))) {
4331 if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {
4332 replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType()));
4333 MadeIRChange = true;
4334 }
4335 if (Inst.isEHPad() || Inst.getType()->isTokenTy())
4336 continue;
4337 // RemoveDIs: erase debug-info on this instruction manually.
4338 Inst.dropDbgRecords();
4340 MadeIRChange = true;
4341 }
4342
4345 MadeIRChange = true;
4346 for (Value *V : Changed)
4348 }
4349
4350 // Handle potentially dead successors.
4351 for (BasicBlock *Succ : successors(BB))
4352 addDeadEdge(BB, Succ, Worklist);
4353}
4354
4357 while (!Worklist.empty()) {
4358 BasicBlock *BB = Worklist.pop_back_val();
4359 if (!all_of(predecessors(BB), [&](BasicBlock *Pred) {
4360 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
4361 }))
4362 continue;
4363
4365 }
4366}
4367
4369 BasicBlock *LiveSucc) {
4371 for (BasicBlock *Succ : successors(BB)) {
4372 // The live successor isn't dead.
4373 if (Succ == LiveSucc)
4374 continue;
4375
4376 addDeadEdge(BB, Succ, Worklist);
4377 }
4378
4380}
4381
4383 // Change br (not X), label True, label False to: br X, label False, True
4384 Value *Cond = BI.getCondition();
4385 Value *X;
4386 if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {
4387 // Swap Destinations and condition...
4388 BI.swapSuccessors();
4389 if (BPI)
4390 BPI->swapSuccEdgesProbabilities(BI.getParent());
4391 return replaceOperand(BI, 0, X);
4392 }
4393
4394 // Canonicalize logical-and-with-invert as logical-or-with-invert.
4395 // This is done by inverting the condition and swapping successors:
4396 // br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T
4397 Value *Y;
4398 if (isa<SelectInst>(Cond) &&
4399 match(Cond,
4401 Value *NotX = Builder.CreateNot(X, "not." + X->getName());
4402 Value *Or = Builder.CreateLogicalOr(NotX, Y);
4403
4404 // Set weights for the new OR select instruction too.
4405 if (auto *OrInst = dyn_cast<Instruction>(Or)) {
4406 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
4407 SmallVector<uint32_t> Weights;
4408 if (extractBranchWeights(*CondInst, Weights)) {
4409 assert(Weights.size() == 2 && "Unexpected number of branch weights!");
4410 std::swap(Weights[0], Weights[1]);
4411 setBranchWeights(*OrInst, Weights, /*IsExpected=*/false);
4412 }
4413 }
4414 }
4415 BI.swapSuccessors();
4416 if (BPI)
4417 BPI->swapSuccEdgesProbabilities(BI.getParent());
4418 return replaceOperand(BI, 0, Or);
4419 }
4420
4421 // If the condition is irrelevant, remove the use so that other
4422 // transforms on the condition become more effective.
4423 if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))
4424 return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));
4425
4426 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
4427 CmpPredicate Pred;
4428 if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&
4429 !isCanonicalPredicate(Pred)) {
4430 // Swap destinations and condition.
4431 auto *Cmp = cast<CmpInst>(Cond);
4432 Cmp->setPredicate(CmpInst::getInversePredicate(Pred));
4433 BI.swapSuccessors();
4434 if (BPI)
4435 BPI->swapSuccEdgesProbabilities(BI.getParent());
4436 Worklist.push(Cmp);
4437 return &BI;
4438 }
4439
4440 if (isa<UndefValue>(Cond)) {
4441 handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr);
4442 return nullptr;
4443 }
4444 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
4446 BI.getSuccessor(!CI->getZExtValue()));
4447 return nullptr;
4448 }
4449
4450 // Replace all dominated uses of the condition with true/false
4451 // Ignore constant expressions to avoid iterating over uses on other
4452 // functions.
4453 if (!isa<Constant>(Cond) && BI.getSuccessor(0) != BI.getSuccessor(1)) {
4454 for (auto &U : make_early_inc_range(Cond->uses())) {
4455 BasicBlockEdge Edge0(BI.getParent(), BI.getSuccessor(0));
4456 if (DT.dominates(Edge0, U)) {
4457 replaceUse(U, ConstantInt::getTrue(Cond->getType()));
4458 addToWorklist(cast<Instruction>(U.getUser()));
4459 continue;
4460 }
4461 BasicBlockEdge Edge1(BI.getParent(), BI.getSuccessor(1));
4462 if (DT.dominates(Edge1, U)) {
4463 replaceUse(U, ConstantInt::getFalse(Cond->getType()));
4464 addToWorklist(cast<Instruction>(U.getUser()));
4465 }
4466 }
4467 }
4468
4469 DC.registerBranch(&BI);
4470 return nullptr;
4471}
4472
4473// Replaces (switch (select cond, X, C)/(select cond, C, X)) with (switch X) if
4474// we can prove that both (switch C) and (switch X) go to the default when cond
4475// is false/true.
4478 bool IsTrueArm) {
4479 unsigned CstOpIdx = IsTrueArm ? 1 : 2;
4480 auto *C = dyn_cast<ConstantInt>(Select->getOperand(CstOpIdx));
4481 if (!C)
4482 return nullptr;
4483
4484 BasicBlock *CstBB = SI.findCaseValue(C)->getCaseSuccessor();
4485 if (CstBB != SI.getDefaultDest())
4486 return nullptr;
4487 Value *X = Select->getOperand(3 - CstOpIdx);
4488 CmpPredicate Pred;
4489 const APInt *RHSC;
4490 if (!match(Select->getCondition(),
4491 m_ICmp(Pred, m_Specific(X), m_APInt(RHSC))))
4492 return nullptr;
4493 if (IsTrueArm)
4494 Pred = ICmpInst::getInversePredicate(Pred);
4495
4496 // See whether we can replace the select with X
4498 for (auto Case : SI.cases())
4499 if (!CR.contains(Case.getCaseValue()->getValue()))
4500 return nullptr;
4501
4502 return X;
4503}
4504
4506 Value *Cond = SI.getCondition();
4507 Value *Op0;
4508 const APInt *CondOpC;
4509 using InvertFn = std::function<APInt(const APInt &Case, const APInt &C)>;
4510
4511 auto MaybeInvertible = [&](Value *Cond) -> InvertFn {
4512 if (match(Cond, m_Add(m_Value(Op0), m_APInt(CondOpC))))
4513 // Change 'switch (X+C) case Case:' into 'switch (X) case Case-C'.
4514 return [](const APInt &Case, const APInt &C) { return Case - C; };
4515
4516 if (match(Cond, m_Sub(m_APInt(CondOpC), m_Value(Op0))))
4517 // Change 'switch (C-X) case Case:' into 'switch (X) case C-Case'.
4518 return [](const APInt &Case, const APInt &C) { return C - Case; };
4519
4520 if (match(Cond, m_Xor(m_Value(Op0), m_APInt(CondOpC))) &&
4521 !CondOpC->isMinSignedValue() && !CondOpC->isMaxSignedValue())
4522 // Change 'switch (X^C) case Case:' into 'switch (X) case Case^C'.
4523 // Prevent creation of large case values by excluding extremes.
4524 return [](const APInt &Case, const APInt &C) { return Case ^ C; };
4525
4526 return nullptr;
4527 };
4528
4529 // Attempt to invert and simplify the switch condition, as long as the
4530 // condition is not used further, as it may not be profitable otherwise.
4531 if (auto InvertFn = MaybeInvertible(Cond); InvertFn && Cond->hasOneUse()) {
4532 for (auto &Case : SI.cases()) {
4533 const APInt &New = InvertFn(Case.getCaseValue()->getValue(), *CondOpC);
4534 Case.setValue(ConstantInt::get(SI.getContext(), New));
4535 }
4536 return replaceOperand(SI, 0, Op0);
4537 }
4538
4539 uint64_t ShiftAmt;
4540 if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) &&
4541 ShiftAmt < Op0->getType()->getScalarSizeInBits() &&
4542 all_of(SI.cases(), [&](const auto &Case) {
4543 return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;
4544 })) {
4545 // Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.
4547 if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||
4548 Shl->hasOneUse()) {
4549 Value *NewCond = Op0;
4550 if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {
4551 // If the shift may wrap, we need to mask off the shifted bits.
4552 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
4553 NewCond = Builder.CreateAnd(
4554 Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt));
4555 }
4556 for (auto Case : SI.cases()) {
4557 const APInt &CaseVal = Case.getCaseValue()->getValue();
4558 APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)
4559 : CaseVal.lshr(ShiftAmt);
4560 Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase));
4561 }
4562 return replaceOperand(SI, 0, NewCond);
4563 }
4564 }
4565
4566 // Fold switch(zext/sext(X)) into switch(X) if possible.
4567 if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) {
4568 bool IsZExt = isa<ZExtInst>(Cond);
4569 Type *SrcTy = Op0->getType();
4570 unsigned NewWidth = SrcTy->getScalarSizeInBits();
4571
4572 if (all_of(SI.cases(), [&](const auto &Case) {
4573 const APInt &CaseVal = Case.getCaseValue()->getValue();
4574 return IsZExt ? CaseVal.isIntN(NewWidth)
4575 : CaseVal.isSignedIntN(NewWidth);
4576 })) {
4577 for (auto &Case : SI.cases()) {
4578 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
4579 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
4580 }
4581 return replaceOperand(SI, 0, Op0);
4582 }
4583 }
4584
4585 // Fold switch(select cond, X, Y) into switch(X/Y) if possible
4586 if (auto *Select = dyn_cast<SelectInst>(Cond)) {
4587 if (Value *V =
4588 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/true))
4589 return replaceOperand(SI, 0, V);
4590 if (Value *V =
4591 simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/false))
4592 return replaceOperand(SI, 0, V);
4593 }
4594
4596 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
4597 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
4598
4599 // Compute the number of leading bits we can ignore.
4600 // TODO: A better way to determine this would use ComputeNumSignBits().
4601 for (const auto &C : SI.cases()) {
4602 LeadingKnownZeros =
4603 std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());
4604 LeadingKnownOnes =
4605 std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());
4606 }
4607
4608 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
4609
4610 // Shrink the condition operand if the new type is smaller than the old type.
4611 // But do not shrink to a non-standard type, because backend can't generate
4612 // good code for that yet.
4613 // TODO: We can make it aggressive again after fixing PR39569.
4614 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
4615 shouldChangeType(Known.getBitWidth(), NewWidth)) {
4616 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
4617 Builder.SetInsertPoint(&SI);
4618 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
4619
4620 for (auto Case : SI.cases()) {
4621 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
4622 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
4623 }
4624 return replaceOperand(SI, 0, NewCond);
4625 }
4626
4627 if (isa<UndefValue>(Cond)) {
4628 handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr);
4629 return nullptr;
4630 }
4631 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
4633 SI.findCaseValue(CI)->getCaseSuccessor());
4634 return nullptr;
4635 }
4636
4637 return nullptr;
4638}
4639
4641InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {
4643 if (!WO)
4644 return nullptr;
4645
4646 Intrinsic::ID OvID = WO->getIntrinsicID();
4647 const APInt *C = nullptr;
4648 if (match(WO->getRHS(), m_APIntAllowPoison(C))) {
4649 if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||
4650 OvID == Intrinsic::umul_with_overflow)) {
4651 // extractvalue (any_mul_with_overflow X, -1), 0 --> -X
4652 if (C->isAllOnes())
4653 return BinaryOperator::CreateNeg(WO->getLHS());
4654 // extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n
4655 if (C->isPowerOf2()) {
4656 return BinaryOperator::CreateShl(
4657 WO->getLHS(),
4658 ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));
4659 }
4660 }
4661 }
4662
4663 // We're extracting from an overflow intrinsic. See if we're the only user.
4664 // That allows us to simplify multiple result intrinsics to simpler things
4665 // that just get one value.
4666 if (!WO->hasOneUse())
4667 return nullptr;
4668
4669 // Check if we're grabbing only the result of a 'with overflow' intrinsic
4670 // and replace it with a traditional binary instruction.
4671 if (*EV.idx_begin() == 0) {
4672 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4673 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
4674 // Replace the old instruction's uses with poison.
4675 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
4677 return BinaryOperator::Create(BinOp, LHS, RHS);
4678 }
4679
4680 assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");
4681
4682 // (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.
4683 if (OvID == Intrinsic::usub_with_overflow)
4684 return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());
4685
4686 // smul with i1 types overflows when both sides are set: -1 * -1 == +1, but
4687 // +1 is not possible because we assume signed values.
4688 if (OvID == Intrinsic::smul_with_overflow &&
4689 WO->getLHS()->getType()->isIntOrIntVectorTy(1))
4690 return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());
4691
4692 // extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-1
4693 if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {
4694 unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();
4695 // Only handle even bitwidths for performance reasons.
4696 if (BitWidth % 2 == 0)
4697 return new ICmpInst(
4698 ICmpInst::ICMP_UGT, WO->getLHS(),
4699 ConstantInt::get(WO->getLHS()->getType(),
4701 }
4702
4703 // If only the overflow result is used, and the right hand side is a
4704 // constant (or constant splat), we can remove the intrinsic by directly
4705 // checking for overflow.
4706 if (C) {
4707 // Compute the no-wrap range for LHS given RHS=C, then construct an
4708 // equivalent icmp, potentially using an offset.
4709 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
4710 WO->getBinaryOp(), *C, WO->getNoWrapKind());
4711
4712 CmpInst::Predicate Pred;
4713 APInt NewRHSC, Offset;
4714 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
4715 auto *OpTy = WO->getRHS()->getType();
4716 auto *NewLHS = WO->getLHS();
4717 if (Offset != 0)
4718 NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));
4719 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
4720 ConstantInt::get(OpTy, NewRHSC));
4721 }
4722
4723 return nullptr;
4724}
4725
4728 InstCombiner::BuilderTy &Builder) {
4729 // Helper to fold frexp of select to select of frexp.
4730
4731 if (!SelectInst->hasOneUse() || !FrexpCall->hasOneUse())
4732 return nullptr;
4734 Value *TrueVal = SelectInst->getTrueValue();
4735 Value *FalseVal = SelectInst->getFalseValue();
4736
4737 const APFloat *ConstVal = nullptr;
4738 Value *VarOp = nullptr;
4739 bool ConstIsTrue = false;
4740
4741 if (match(TrueVal, m_APFloat(ConstVal))) {
4742 VarOp = FalseVal;
4743 ConstIsTrue = true;
4744 } else if (match(FalseVal, m_APFloat(ConstVal))) {
4745 VarOp = TrueVal;
4746 ConstIsTrue = false;
4747 } else {
4748 return nullptr;
4749 }
4750
4751 Builder.SetInsertPoint(&EV);
4752
4753 CallInst *NewFrexp =
4754 Builder.CreateCall(FrexpCall->getCalledFunction(), {VarOp}, "frexp");
4755 NewFrexp->copyIRFlags(FrexpCall);
4756
4757 Value *NewEV = Builder.CreateExtractValue(NewFrexp, 0, "mantissa");
4758
4759 int Exp;
4760 APFloat Mantissa = frexp(*ConstVal, Exp, APFloat::rmNearestTiesToEven);
4761
4762 Constant *ConstantMantissa = ConstantFP::get(TrueVal->getType(), Mantissa);
4763
4764 Value *NewSel = Builder.CreateSelectFMF(
4765 Cond, ConstIsTrue ? ConstantMantissa : NewEV,
4766 ConstIsTrue ? NewEV : ConstantMantissa, SelectInst, "select.frexp");
4767 return NewSel;
4768}
4770 Value *Agg = EV.getAggregateOperand();
4771
4772 if (!EV.hasIndices())
4773 return replaceInstUsesWith(EV, Agg);
4774
4775 if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),
4776 SQ.getWithInstruction(&EV)))
4777 return replaceInstUsesWith(EV, V);
4778
4779 Value *Cond, *TrueVal, *FalseVal;
4781 m_Value(Cond), m_Value(TrueVal), m_Value(FalseVal)))))) {
4782 auto *SelInst =
4783 cast<SelectInst>(cast<IntrinsicInst>(Agg)->getArgOperand(0));
4784 if (Value *Result =
4785 foldFrexpOfSelect(EV, cast<IntrinsicInst>(Agg), SelInst, Builder))
4786 return replaceInstUsesWith(EV, Result);
4787 }
4789 // We're extracting from an insertvalue instruction, compare the indices
4790 const unsigned *exti, *exte, *insi, *inse;
4791 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
4792 exte = EV.idx_end(), inse = IV->idx_end();
4793 exti != exte && insi != inse;
4794 ++exti, ++insi) {
4795 if (*insi != *exti)
4796 // The insert and extract both reference distinctly different elements.
4797 // This means the extract is not influenced by the insert, and we can
4798 // replace the aggregate operand of the extract with the aggregate
4799 // operand of the insert. i.e., replace
4800 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4801 // %E = extractvalue { i32, { i32 } } %I, 0
4802 // with
4803 // %E = extractvalue { i32, { i32 } } %A, 0
4804 return ExtractValueInst::Create(IV->getAggregateOperand(),
4805 EV.getIndices());
4806 }
4807 if (exti == exte && insi == inse)
4808 // Both iterators are at the end: Index lists are identical. Replace
4809 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4810 // %C = extractvalue { i32, { i32 } } %B, 1, 0
4811 // with "i32 42"
4812 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
4813 if (exti == exte) {
4814 // The extract list is a prefix of the insert list. i.e. replace
4815 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
4816 // %E = extractvalue { i32, { i32 } } %I, 1
4817 // with
4818 // %X = extractvalue { i32, { i32 } } %A, 1
4819 // %E = insertvalue { i32 } %X, i32 42, 0
4820 // by switching the order of the insert and extract (though the
4821 // insertvalue should be left in, since it may have other uses).
4822 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
4823 EV.getIndices());
4824 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
4825 ArrayRef(insi, inse));
4826 }
4827 if (insi == inse)
4828 // The insert list is a prefix of the extract list
4829 // We can simply remove the common indices from the extract and make it
4830 // operate on the inserted value instead of the insertvalue result.
4831 // i.e., replace
4832 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
4833 // %E = extractvalue { i32, { i32 } } %I, 1, 0
4834 // with
4835 // %E extractvalue { i32 } { i32 42 }, 0
4836 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
4837 ArrayRef(exti, exte));
4838 }
4839
4840 if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))
4841 return R;
4842
4843 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {
4844 // Bail out if the aggregate contains scalable vector type
4845 if (auto *STy = dyn_cast<StructType>(Agg->getType());
4846 STy && STy->isScalableTy())
4847 return nullptr;
4848
4849 // If the (non-volatile) load only has one use, we can rewrite this to a
4850 // load from a GEP. This reduces the size of the load. If a load is used
4851 // only by extractvalue instructions then this either must have been
4852 // optimized before, or it is a struct with padding, in which case we
4853 // don't want to do the transformation as it loses padding knowledge.
4854 if (L->isSimple() && L->hasOneUse()) {
4855 // extractvalue has integer indices, getelementptr has Value*s. Convert.
4856 SmallVector<Value*, 4> Indices;
4857 // Prefix an i32 0 since we need the first element.
4858 Indices.push_back(Builder.getInt32(0));
4859 for (unsigned Idx : EV.indices())
4860 Indices.push_back(Builder.getInt32(Idx));
4861
4862 // We need to insert these at the location of the old load, not at that of
4863 // the extractvalue.
4864 Builder.SetInsertPoint(L);
4865 Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
4866 L->getPointerOperand(), Indices);
4867 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
4868 // Whatever aliasing information we had for the orignal load must also
4869 // hold for the smaller load, so propagate the annotations.
4870 NL->setAAMetadata(L->getAAMetadata());
4871 // Returning the load directly will cause the main loop to insert it in
4872 // the wrong spot, so use replaceInstUsesWith().
4873 return replaceInstUsesWith(EV, NL);
4874 }
4875 }
4876
4877 if (auto *PN = dyn_cast<PHINode>(Agg))
4878 if (Instruction *Res = foldOpIntoPhi(EV, PN))
4879 return Res;
4880
4881 // Canonicalize extract (select Cond, TV, FV)
4882 // -> select cond, (extract TV), (extract FV)
4883 if (auto *SI = dyn_cast<SelectInst>(Agg))
4884 if (Instruction *R = FoldOpIntoSelect(EV, SI, /*FoldWithMultiUse=*/true))
4885 return R;
4886
4887 // We could simplify extracts from other values. Note that nested extracts may
4888 // already be simplified implicitly by the above: extract (extract (insert) )
4889 // will be translated into extract ( insert ( extract ) ) first and then just
4890 // the value inserted, if appropriate. Similarly for extracts from single-use
4891 // loads: extract (extract (load)) will be translated to extract (load (gep))
4892 // and if again single-use then via load (gep (gep)) to load (gep).
4893 // However, double extracts from e.g. function arguments or return values
4894 // aren't handled yet.
4895 return nullptr;
4896}
4897
4898/// Return 'true' if the given typeinfo will match anything.
4899static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
4900 switch (Personality) {
4904 // The GCC C EH and Rust personality only exists to support cleanups, so
4905 // it's not clear what the semantics of catch clauses are.
4906 return false;
4908 return false;
4910 // While __gnat_all_others_value will match any Ada exception, it doesn't
4911 // match foreign exceptions (or didn't, before gcc-4.7).
4912 return false;
4924 return isa<ConstantPointerNull>(TypeInfo);
4925 }
4926 llvm_unreachable("invalid enum");
4927}
4928
4929static bool shorter_filter(const Value *LHS, const Value *RHS) {
4930 return
4931 cast<ArrayType>(LHS->getType())->getNumElements()
4932 <
4933 cast<ArrayType>(RHS->getType())->getNumElements();
4934}
4935
4937 // The logic here should be correct for any real-world personality function.
4938 // However if that turns out not to be true, the offending logic can always
4939 // be conditioned on the personality function, like the catch-all logic is.
4940 EHPersonality Personality =
4941 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
4942
4943 // Simplify the list of clauses, eg by removing repeated catch clauses
4944 // (these are often created by inlining).
4945 bool MakeNewInstruction = false; // If true, recreate using the following:
4946 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
4947 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
4948
4949 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
4950 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
4951 bool isLastClause = i + 1 == e;
4952 if (LI.isCatch(i)) {
4953 // A catch clause.
4954 Constant *CatchClause = LI.getClause(i);
4955 Constant *TypeInfo = CatchClause->stripPointerCasts();
4956
4957 // If we already saw this clause, there is no point in having a second
4958 // copy of it.
4959 if (AlreadyCaught.insert(TypeInfo).second) {
4960 // This catch clause was not already seen.
4961 NewClauses.push_back(CatchClause);
4962 } else {
4963 // Repeated catch clause - drop the redundant copy.
4964 MakeNewInstruction = true;
4965 }
4966
4967 // If this is a catch-all then there is no point in keeping any following
4968 // clauses or marking the landingpad as having a cleanup.
4969 if (isCatchAll(Personality, TypeInfo)) {
4970 if (!isLastClause)
4971 MakeNewInstruction = true;
4972 CleanupFlag = false;
4973 break;
4974 }
4975 } else {
4976 // A filter clause. If any of the filter elements were already caught
4977 // then they can be dropped from the filter. It is tempting to try to
4978 // exploit the filter further by saying that any typeinfo that does not
4979 // occur in the filter can't be caught later (and thus can be dropped).
4980 // However this would be wrong, since typeinfos can match without being
4981 // equal (for example if one represents a C++ class, and the other some
4982 // class derived from it).
4983 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
4984 Constant *FilterClause = LI.getClause(i);
4985 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
4986 unsigned NumTypeInfos = FilterType->getNumElements();
4987
4988 // An empty filter catches everything, so there is no point in keeping any
4989 // following clauses or marking the landingpad as having a cleanup. By
4990 // dealing with this case here the following code is made a bit simpler.
4991 if (!NumTypeInfos) {
4992 NewClauses.push_back(FilterClause);
4993 if (!isLastClause)
4994 MakeNewInstruction = true;
4995 CleanupFlag = false;
4996 break;
4997 }
4998
4999 bool MakeNewFilter = false; // If true, make a new filter.
5000 SmallVector<Constant *, 16> NewFilterElts; // New elements.
5001 if (isa<ConstantAggregateZero>(FilterClause)) {
5002 // Not an empty filter - it contains at least one null typeinfo.
5003 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
5004 Constant *TypeInfo =
5006 // If this typeinfo is a catch-all then the filter can never match.
5007 if (isCatchAll(Personality, TypeInfo)) {
5008 // Throw the filter away.
5009 MakeNewInstruction = true;
5010 continue;
5011 }
5012
5013 // There is no point in having multiple copies of this typeinfo, so
5014 // discard all but the first copy if there is more than one.
5015 NewFilterElts.push_back(TypeInfo);
5016 if (NumTypeInfos > 1)
5017 MakeNewFilter = true;
5018 } else {
5019 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
5020 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
5021 NewFilterElts.reserve(NumTypeInfos);
5022
5023 // Remove any filter elements that were already caught or that already
5024 // occurred in the filter. While there, see if any of the elements are
5025 // catch-alls. If so, the filter can be discarded.
5026 bool SawCatchAll = false;
5027 for (unsigned j = 0; j != NumTypeInfos; ++j) {
5028 Constant *Elt = Filter->getOperand(j);
5029 Constant *TypeInfo = Elt->stripPointerCasts();
5030 if (isCatchAll(Personality, TypeInfo)) {
5031 // This element is a catch-all. Bail out, noting this fact.
5032 SawCatchAll = true;
5033 break;
5034 }
5035
5036 // Even if we've seen a type in a catch clause, we don't want to
5037 // remove it from the filter. An unexpected type handler may be
5038 // set up for a call site which throws an exception of the same
5039 // type caught. In order for the exception thrown by the unexpected
5040 // handler to propagate correctly, the filter must be correctly
5041 // described for the call site.
5042 //
5043 // Example:
5044 //
5045 // void unexpected() { throw 1;}
5046 // void foo() throw (int) {
5047 // std::set_unexpected(unexpected);
5048 // try {
5049 // throw 2.0;
5050 // } catch (int i) {}
5051 // }
5052
5053 // There is no point in having multiple copies of the same typeinfo in
5054 // a filter, so only add it if we didn't already.
5055 if (SeenInFilter.insert(TypeInfo).second)
5056 NewFilterElts.push_back(cast<Constant>(Elt));
5057 }
5058 // A filter containing a catch-all cannot match anything by definition.
5059 if (SawCatchAll) {
5060 // Throw the filter away.
5061 MakeNewInstruction = true;
5062 continue;
5063 }
5064
5065 // If we dropped something from the filter, make a new one.
5066 if (NewFilterElts.size() < NumTypeInfos)
5067 MakeNewFilter = true;
5068 }
5069 if (MakeNewFilter) {
5070 FilterType = ArrayType::get(FilterType->getElementType(),
5071 NewFilterElts.size());
5072 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
5073 MakeNewInstruction = true;
5074 }
5075
5076 NewClauses.push_back(FilterClause);
5077
5078 // If the new filter is empty then it will catch everything so there is
5079 // no point in keeping any following clauses or marking the landingpad
5080 // as having a cleanup. The case of the original filter being empty was
5081 // already handled above.
5082 if (MakeNewFilter && !NewFilterElts.size()) {
5083 assert(MakeNewInstruction && "New filter but not a new instruction!");
5084 CleanupFlag = false;
5085 break;
5086 }
5087 }
5088 }
5089
5090 // If several filters occur in a row then reorder them so that the shortest
5091 // filters come first (those with the smallest number of elements). This is
5092 // advantageous because shorter filters are more likely to match, speeding up
5093 // unwinding, but mostly because it increases the effectiveness of the other
5094 // filter optimizations below.
5095 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
5096 unsigned j;
5097 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
5098 for (j = i; j != e; ++j)
5099 if (!isa<ArrayType>(NewClauses[j]->getType()))
5100 break;
5101
5102 // Check whether the filters are already sorted by length. We need to know
5103 // if sorting them is actually going to do anything so that we only make a
5104 // new landingpad instruction if it does.
5105 for (unsigned k = i; k + 1 < j; ++k)
5106 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
5107 // Not sorted, so sort the filters now. Doing an unstable sort would be
5108 // correct too but reordering filters pointlessly might confuse users.
5109 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
5111 MakeNewInstruction = true;
5112 break;
5113 }
5114
5115 // Look for the next batch of filters.
5116 i = j + 1;
5117 }
5118
5119 // If typeinfos matched if and only if equal, then the elements of a filter L
5120 // that occurs later than a filter F could be replaced by the intersection of
5121 // the elements of F and L. In reality two typeinfos can match without being
5122 // equal (for example if one represents a C++ class, and the other some class
5123 // derived from it) so it would be wrong to perform this transform in general.
5124 // However the transform is correct and useful if F is a subset of L. In that
5125 // case L can be replaced by F, and thus removed altogether since repeating a
5126 // filter is pointless. So here we look at all pairs of filters F and L where
5127 // L follows F in the list of clauses, and remove L if every element of F is
5128 // an element of L. This can occur when inlining C++ functions with exception
5129 // specifications.
5130 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
5131 // Examine each filter in turn.
5132 Value *Filter = NewClauses[i];
5133 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
5134 if (!FTy)
5135 // Not a filter - skip it.
5136 continue;
5137 unsigned FElts = FTy->getNumElements();
5138 // Examine each filter following this one. Doing this backwards means that
5139 // we don't have to worry about filters disappearing under us when removed.
5140 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
5141 Value *LFilter = NewClauses[j];
5142 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
5143 if (!LTy)
5144 // Not a filter - skip it.
5145 continue;
5146 // If Filter is a subset of LFilter, i.e. every element of Filter is also
5147 // an element of LFilter, then discard LFilter.
5148 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
5149 // If Filter is empty then it is a subset of LFilter.
5150 if (!FElts) {
5151 // Discard LFilter.
5152 NewClauses.erase(J);
5153 MakeNewInstruction = true;
5154 // Move on to the next filter.
5155 continue;
5156 }
5157 unsigned LElts = LTy->getNumElements();
5158 // If Filter is longer than LFilter then it cannot be a subset of it.
5159 if (FElts > LElts)
5160 // Move on to the next filter.
5161 continue;
5162 // At this point we know that LFilter has at least one element.
5163 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
5164 // Filter is a subset of LFilter iff Filter contains only zeros (as we
5165 // already know that Filter is not longer than LFilter).
5167 assert(FElts <= LElts && "Should have handled this case earlier!");
5168 // Discard LFilter.
5169 NewClauses.erase(J);
5170 MakeNewInstruction = true;
5171 }
5172 // Move on to the next filter.
5173 continue;
5174 }
5175 ConstantArray *LArray = cast<ConstantArray>(LFilter);
5176 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
5177 // Since Filter is non-empty and contains only zeros, it is a subset of
5178 // LFilter iff LFilter contains a zero.
5179 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
5180 for (unsigned l = 0; l != LElts; ++l)
5181 if (isa<ConstantPointerNull>(LArray->getOperand(l))) {
5182 // LFilter contains a zero - discard it.
5183 NewClauses.erase(J);
5184 MakeNewInstruction = true;
5185 break;
5186 }
5187 // Move on to the next filter.
5188 continue;
5189 }
5190 // At this point we know that both filters are ConstantArrays. Loop over
5191 // operands to see whether every element of Filter is also an element of
5192 // LFilter. Since filters tend to be short this is probably faster than
5193 // using a method that scales nicely.
5195 bool AllFound = true;
5196 for (unsigned f = 0; f != FElts; ++f) {
5197 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
5198 AllFound = false;
5199 for (unsigned l = 0; l != LElts; ++l) {
5200 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
5201 if (LTypeInfo == FTypeInfo) {
5202 AllFound = true;
5203 break;
5204 }
5205 }
5206 if (!AllFound)
5207 break;
5208 }
5209 if (AllFound) {
5210 // Discard LFilter.
5211 NewClauses.erase(J);
5212 MakeNewInstruction = true;
5213 }
5214 // Move on to the next filter.
5215 }
5216 }
5217
5218 // If we changed any of the clauses, replace the old landingpad instruction
5219 // with a new one.
5220 if (MakeNewInstruction) {
5222 NewClauses.size());
5223 for (Constant *C : NewClauses)
5224 NLI->addClause(C);
5225 // A landing pad with no clauses must have the cleanup flag set. It is
5226 // theoretically possible, though highly unlikely, that we eliminated all
5227 // clauses. If so, force the cleanup flag to true.
5228 if (NewClauses.empty())
5229 CleanupFlag = true;
5230 NLI->setCleanup(CleanupFlag);
5231 return NLI;
5232 }
5233
5234 // Even if none of the clauses changed, we may nonetheless have understood
5235 // that the cleanup flag is pointless. Clear it if so.
5236 if (LI.isCleanup() != CleanupFlag) {
5237 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
5238 LI.setCleanup(CleanupFlag);
5239 return &LI;
5240 }
5241
5242 return nullptr;
5243}
5244
5245Value *
5247 // Try to push freeze through instructions that propagate but don't produce
5248 // poison as far as possible. If an operand of freeze follows three
5249 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
5250 // guaranteed-non-poison operands then push the freeze through to the one
5251 // operand that is not guaranteed non-poison. The actual transform is as
5252 // follows.
5253 // Op1 = ... ; Op1 can be posion
5254 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
5255 // ; single guaranteed-non-poison operands
5256 // ... = Freeze(Op0)
5257 // =>
5258 // Op1 = ...
5259 // Op1.fr = Freeze(Op1)
5260 // ... = Inst(Op1.fr, NonPoisonOps...)
5261 auto *OrigOp = OrigFI.getOperand(0);
5262 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
5263
5264 // While we could change the other users of OrigOp to use freeze(OrigOp), that
5265 // potentially reduces their optimization potential, so let's only do this iff
5266 // the OrigOp is only used by the freeze.
5267 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))
5268 return nullptr;
5269
5270 // We can't push the freeze through an instruction which can itself create
5271 // poison. If the only source of new poison is flags, we can simply
5272 // strip them (since we know the only use is the freeze and nothing can
5273 // benefit from them.)
5275 /*ConsiderFlagsAndMetadata*/ false))
5276 return nullptr;
5277
5278 // If operand is guaranteed not to be poison, there is no need to add freeze
5279 // to the operand. So we first find the operand that is not guaranteed to be
5280 // poison.
5281 Value *MaybePoisonOperand = nullptr;
5282 for (Value *V : OrigOpInst->operands()) {
5284 // Treat identical operands as a single operand.
5285 (MaybePoisonOperand && MaybePoisonOperand == V))
5286 continue;
5287 if (!MaybePoisonOperand)
5288 MaybePoisonOperand = V;
5289 else
5290 return nullptr;
5291 }
5292
5293 OrigOpInst->dropPoisonGeneratingAnnotations();
5294
5295 // If all operands are guaranteed to be non-poison, we can drop freeze.
5296 if (!MaybePoisonOperand)
5297 return OrigOp;
5298
5299 Builder.SetInsertPoint(OrigOpInst);
5300 Value *FrozenMaybePoisonOperand = Builder.CreateFreeze(
5301 MaybePoisonOperand, MaybePoisonOperand->getName() + ".fr");
5302
5303 OrigOpInst->replaceUsesOfWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
5304 return OrigOp;
5305}
5306
5308 PHINode *PN) {
5309 // Detect whether this is a recurrence with a start value and some number of
5310 // backedge values. We'll check whether we can push the freeze through the
5311 // backedge values (possibly dropping poison flags along the way) until we
5312 // reach the phi again. In that case, we can move the freeze to the start
5313 // value.
5314 Use *StartU = nullptr;
5316 for (Use &U : PN->incoming_values()) {
5317 if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {
5318 // Add backedge value to worklist.
5319 Worklist.push_back(U.get());
5320 continue;
5321 }
5322
5323 // Don't bother handling multiple start values.
5324 if (StartU)
5325 return nullptr;
5326 StartU = &U;
5327 }
5328
5329 if (!StartU || Worklist.empty())
5330 return nullptr; // Not a recurrence.
5331
5332 Value *StartV = StartU->get();
5333 BasicBlock *StartBB = PN->getIncomingBlock(*StartU);
5334 bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);
5335 // We can't insert freeze if the start value is the result of the
5336 // terminator (e.g. an invoke).
5337 if (StartNeedsFreeze && StartBB->getTerminator() == StartV)
5338 return nullptr;
5339
5342 while (!Worklist.empty()) {
5343 Value *V = Worklist.pop_back_val();
5344 if (!Visited.insert(V).second)
5345 continue;
5346
5347 if (Visited.size() > 32)
5348 return nullptr; // Limit the total number of values we inspect.
5349
5350 // Assume that PN is non-poison, because it will be after the transform.
5351 if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))
5352 continue;
5353
5356 /*ConsiderFlagsAndMetadata*/ false))
5357 return nullptr;
5358
5359 DropFlags.push_back(I);
5360 append_range(Worklist, I->operands());
5361 }
5362
5363 for (Instruction *I : DropFlags)
5364 I->dropPoisonGeneratingAnnotations();
5365
5366 if (StartNeedsFreeze) {
5367 Builder.SetInsertPoint(StartBB->getTerminator());
5368 Value *FrozenStartV = Builder.CreateFreeze(StartV,
5369 StartV->getName() + ".fr");
5370 replaceUse(*StartU, FrozenStartV);
5371 }
5372 return replaceInstUsesWith(FI, PN);
5373}
5374
5376 Value *Op = FI.getOperand(0);
5377
5378 if (isa<Constant>(Op) || Op->hasOneUse())
5379 return false;
5380
5381 // Move the freeze directly after the definition of its operand, so that
5382 // it dominates the maximum number of uses. Note that it may not dominate
5383 // *all* uses if the operand is an invoke/callbr and the use is in a phi on
5384 // the normal/default destination. This is why the domination check in the
5385 // replacement below is still necessary.
5386 BasicBlock::iterator MoveBefore;
5387 if (isa<Argument>(Op)) {
5388 MoveBefore = FI.getFunction()->getEntryBlock().getFirstNonPHIOrAlloca();
5389 } else {
5390 auto MoveBeforeOpt = cast<Instruction>(Op)->getInsertionPointAfterDef();
5391 if (!MoveBeforeOpt)
5392 return false;
5393 MoveBefore = *MoveBeforeOpt;
5394 }
5395
5396 // Re-point iterator to come after any debug-info records.
5397 MoveBefore.setHeadBit(false);
5398
5399 bool Changed = false;
5400 if (&FI != &*MoveBefore) {
5401 FI.moveBefore(*MoveBefore->getParent(), MoveBefore);
5402 Changed = true;
5403 }
5404
5406 Changed |= Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {
5407 if (!DT.dominates(&FI, U))
5408 return false;
5409
5410 Users.push_back(U.getUser());
5411 return true;
5412 });
5413
5414 for (auto *U : Users) {
5415 // Re-queue U and its users: freezing U's operand can expose a fold on a
5416 // user of U (e.g. a freeze of U can now be pushed through it) that would
5417 // otherwise only fire on a later iteration, tripping the fixpoint verifier.
5418 auto *UI = cast<Instruction>(U);
5419 Worklist.pushUsersToWorkList(*UI);
5420 Worklist.push(UI);
5421 }
5422
5423 return Changed;
5424}
5425
5426// Check if any direct or bitcast user of this value is a shuffle instruction.
5428 for (auto *U : V->users()) {
5430 return true;
5431 else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U))
5432 return true;
5433 }
5434 return false;
5435}
5436
5438 Value *Op0 = I.getOperand(0);
5439
5440 if (Value *V = simplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
5441 return replaceInstUsesWith(I, V);
5442
5443 // freeze (phi const, x) --> phi const, (freeze x)
5444 if (auto *PN = dyn_cast<PHINode>(Op0)) {
5445 if (Instruction *NV = foldOpIntoPhi(I, PN))
5446 return NV;
5447 if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))
5448 return NV;
5449 }
5450
5452 return replaceInstUsesWith(I, NI);
5453
5454 // If I is freeze(undef), check its uses and fold it to a fixed constant.
5455 // - or: pick -1
5456 // - select's condition: if the true value is constant, choose it by making
5457 // the condition true.
5458 // - phi: pick the common constant across operands
5459 // - default: pick 0
5460 //
5461 // Note that this transform is intentionally done here rather than
5462 // via an analysis in InstSimplify or at individual user sites. That is
5463 // because we must produce the same value for all uses of the freeze -
5464 // it's the reason "freeze" exists!
5465 //
5466 // TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid
5467 // duplicating logic for binops at least.
5468 auto getUndefReplacement = [&](Type *Ty) {
5469 auto pickCommonConstantFromPHI = [](PHINode &PN) -> Value * {
5470 // phi(freeze(undef), C, C). Choose C for freeze so the PHI can be
5471 // removed.
5472 Constant *BestValue = nullptr;
5473 for (Value *V : PN.incoming_values()) {
5474 if (match(V, m_Freeze(m_Undef())))
5475 continue;
5476
5478 if (!C)
5479 return nullptr;
5480
5482 return nullptr;
5483
5484 if (BestValue && BestValue != C)
5485 return nullptr;
5486
5487 BestValue = C;
5488 }
5489 return BestValue;
5490 };
5491
5492 Value *NullValue = Constant::getNullValue(Ty);
5493 Value *BestValue = nullptr;
5494 for (auto *U : I.users()) {
5495 Value *V = NullValue;
5496 if (match(U, m_Or(m_Value(), m_Value())))
5498 else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))
5499 V = ConstantInt::getTrue(Ty);
5500 else if (match(U, m_c_Select(m_Specific(&I), m_Value(V)))) {
5501 if (V == &I || !isGuaranteedNotToBeUndefOrPoison(V, &AC, &I, &DT))
5502 V = NullValue;
5503 } else if (auto *PHI = dyn_cast<PHINode>(U)) {
5504 if (Value *MaybeV = pickCommonConstantFromPHI(*PHI))
5505 V = MaybeV;
5506 }
5507
5508 if (!BestValue)
5509 BestValue = V;
5510 else if (BestValue != V)
5511 BestValue = NullValue;
5512 }
5513 assert(BestValue && "Must have at least one use");
5514 assert(BestValue != &I && "Cannot replace with itself");
5515 return BestValue;
5516 };
5517
5518 if (match(Op0, m_Undef())) {
5519 // Don't fold freeze(undef/poison) if it's used as a vector operand in
5520 // a shuffle. This may improve codegen for shuffles that allow
5521 // unspecified inputs.
5523 return nullptr;
5524 return replaceInstUsesWith(I, getUndefReplacement(I.getType()));
5525 }
5526
5527 auto getFreezeVectorReplacement = [](Constant *C) -> Constant * {
5528 Type *Ty = C->getType();
5529 auto *VTy = dyn_cast<FixedVectorType>(Ty);
5530 if (!VTy)
5531 return nullptr;
5532 Constant *BestValue;
5534 m_Unless(m_Undef()), m_Constant(BestValue)))))
5535 BestValue = Constant::getNullValue(VTy->getScalarType());
5536 return Constant::replaceUndefsWith(C, BestValue);
5537 };
5538
5539 Constant *C;
5540 if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement() &&
5541 !C->containsConstantExpression()) {
5542 if (Constant *Repl = getFreezeVectorReplacement(C))
5543 return replaceInstUsesWith(I, Repl);
5544 }
5545
5546 // Replace uses of Op with freeze(Op).
5547 if (freezeOtherUses(I))
5548 return &I;
5549
5550 return nullptr;
5551}
5552
5553/// Check for case where the call writes to an otherwise dead alloca. This
5554/// shows up for unused out-params in idiomatic C/C++ code. Note that this
5555/// helper *only* analyzes the write; doesn't check any other legality aspect.
5557 auto *CB = dyn_cast<CallBase>(I);
5558 if (!CB)
5559 // TODO: handle e.g. store to alloca here - only worth doing if we extend
5560 // to allow reload along used path as described below. Otherwise, this
5561 // is simply a store to a dead allocation which will be removed.
5562 return false;
5563 std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);
5564 if (!Dest)
5565 return false;
5566 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));
5567 if (!AI)
5568 // TODO: allow malloc?
5569 return false;
5570 // TODO: allow memory access dominated by move point? Note that since AI
5571 // could have a reference to itself captured by the call, we would need to
5572 // account for cycles in doing so.
5573 SmallVector<const User *> AllocaUsers;
5575 auto pushUsers = [&](const Instruction &I) {
5576 for (const User *U : I.users()) {
5577 if (Visited.insert(U).second)
5578 AllocaUsers.push_back(U);
5579 }
5580 };
5581 pushUsers(*AI);
5582 while (!AllocaUsers.empty()) {
5583 auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());
5584 if (isa<GetElementPtrInst>(UserI) || isa<AddrSpaceCastInst>(UserI)) {
5585 pushUsers(*UserI);
5586 continue;
5587 }
5588 if (UserI == CB)
5589 continue;
5590 // TODO: support lifetime.start/end here
5591 return false;
5592 }
5593 return true;
5594}
5595
5596/// Try to move the specified instruction from its current block into the
5597/// beginning of DestBlock, which can only happen if it's safe to move the
5598/// instruction past all of the instructions between it and the end of its
5599/// block.
5601 BasicBlock *DestBlock) {
5602 BasicBlock *SrcBlock = I->getParent();
5603
5604 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5605 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||
5606 I->isTerminator())
5607 return false;
5608
5609 // Do not sink static or dynamic alloca instructions. Static allocas must
5610 // remain in the entry block, and dynamic allocas must not be sunk in between
5611 // a stacksave / stackrestore pair, which would incorrectly shorten its
5612 // lifetime.
5613 if (isa<AllocaInst>(I))
5614 return false;
5615
5616 // Do not sink into catchswitch blocks.
5617 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
5618 return false;
5619
5620 // Do not sink convergent call instructions.
5621 if (auto *CI = dyn_cast<CallInst>(I)) {
5622 if (CI->isConvergent())
5623 return false;
5624 }
5625
5626 // Unless we can prove that the memory write isn't visibile except on the
5627 // path we're sinking to, we must bail.
5628 if (I->mayWriteToMemory()) {
5629 if (!SoleWriteToDeadLocal(I, TLI))
5630 return false;
5631 }
5632
5633 // We can only sink load instructions if there is nothing between the load and
5634 // the end of block that could change the value.
5635 if (I->mayReadFromMemory() &&
5636 !I->hasMetadata(LLVMContext::MD_invariant_load)) {
5637 // We don't want to do any sophisticated alias analysis, so we only check
5638 // the instructions after I in I's parent block if we try to sink to its
5639 // successor block.
5640 if (DestBlock->getUniquePredecessor() != I->getParent())
5641 return false;
5642 for (BasicBlock::iterator Scan = std::next(I->getIterator()),
5643 E = I->getParent()->end();
5644 Scan != E; ++Scan)
5645 if (Scan->mayWriteToMemory() && !isa<AssumeInst>(Scan))
5646 return false;
5647 }
5648
5649 SmallVector<AssumeInst *, 2> AssumesToSink;
5650 I->dropDroppableUses([&](const Use *U) {
5651 auto *User = dyn_cast<Instruction>(U->getUser());
5652 if (User && User->getParent() != DestBlock) {
5653 if (auto *Assume = dyn_cast<AssumeInst>(User);
5654 Assume && Assume->getParent() == SrcBlock) {
5655 AssumesToSink.push_back(Assume);
5656 return false;
5657 }
5658 Worklist.add(User);
5659 return true;
5660 }
5661 return false;
5662 });
5663
5664 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
5665 I->moveBefore(*DestBlock, InsertPos);
5666 ++NumSunkInst;
5667
5668 // Sink the collected assumes right after I in DestBlock so that the
5669 // alignment/attribute guarantees they encode remain visible to later passes.
5670 for (AssumeInst *Assume : AssumesToSink)
5671 Assume->moveAfter(I);
5672
5673 // Also sink all related debug uses from the source basic block. Otherwise we
5674 // get debug use before the def. Attempt to salvage debug uses first, to
5675 // maximise the range variables have location for. If we cannot salvage, then
5676 // mark the location undef: we know it was supposed to receive a new location
5677 // here, but that computation has been sunk.
5678 SmallVector<DbgVariableRecord *, 2> DbgVariableRecords;
5679 findDbgUsers(I, DbgVariableRecords);
5680 if (!DbgVariableRecords.empty())
5681 tryToSinkInstructionDbgVariableRecords(I, InsertPos, SrcBlock, DestBlock,
5682 DbgVariableRecords);
5683
5684 // PS: there are numerous flaws with this behaviour, not least that right now
5685 // assignments can be re-ordered past other assignments to the same variable
5686 // if they use different Values. Creating more undef assignements can never be
5687 // undone. And salvaging all users outside of this block can un-necessarily
5688 // alter the lifetime of the live-value that the variable refers to.
5689 // Some of these things can be resolved by tolerating debug use-before-defs in
5690 // LLVM-IR, however it depends on the instruction-referencing CodeGen backend
5691 // being used for more architectures.
5692
5693 return true;
5694}
5695
5697 Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,
5698 BasicBlock *DestBlock,
5699 SmallVectorImpl<DbgVariableRecord *> &DbgVariableRecords) {
5700 // For all debug values in the destination block, the sunk instruction
5701 // will still be available, so they do not need to be dropped.
5702
5703 // Fetch all DbgVariableRecords not already in the destination.
5704 SmallVector<DbgVariableRecord *, 2> DbgVariableRecordsToSalvage;
5705 for (auto &DVR : DbgVariableRecords)
5706 if (DVR->getParent() != DestBlock)
5707 DbgVariableRecordsToSalvage.push_back(DVR);
5708
5709 // Fetch a second collection, of DbgVariableRecords in the source block that
5710 // we're going to sink.
5711 SmallVector<DbgVariableRecord *> DbgVariableRecordsToSink;
5712 for (DbgVariableRecord *DVR : DbgVariableRecordsToSalvage)
5713 if (DVR->getParent() == SrcBlock)
5714 DbgVariableRecordsToSink.push_back(DVR);
5715
5716 // Sort DbgVariableRecords according to their position in the block. This is a
5717 // partial order: DbgVariableRecords attached to different instructions will
5718 // be ordered by the instruction order, but DbgVariableRecords attached to the
5719 // same instruction won't have an order.
5720 auto Order = [](DbgVariableRecord *A, DbgVariableRecord *B) -> bool {
5721 return B->getInstruction()->comesBefore(A->getInstruction());
5722 };
5723 llvm::stable_sort(DbgVariableRecordsToSink, Order);
5724
5725 // If there are two assignments to the same variable attached to the same
5726 // instruction, the ordering between the two assignments is important. Scan
5727 // for this (rare) case and establish which is the last assignment.
5728 using InstVarPair = std::pair<const Instruction *, DebugVariable>;
5730 if (DbgVariableRecordsToSink.size() > 1) {
5732 // Count how many assignments to each variable there is per instruction.
5733 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5734 DebugVariable DbgUserVariable =
5735 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5736 DVR->getDebugLoc()->getInlinedAt());
5737 CountMap[std::make_pair(DVR->getInstruction(), DbgUserVariable)] += 1;
5738 }
5739
5740 // If there are any instructions with two assignments, add them to the
5741 // FilterOutMap to record that they need extra filtering.
5743 for (auto It : CountMap) {
5744 if (It.second > 1) {
5745 FilterOutMap[It.first] = nullptr;
5746 DupSet.insert(It.first.first);
5747 }
5748 }
5749
5750 // For all instruction/variable pairs needing extra filtering, find the
5751 // latest assignment.
5752 for (const Instruction *Inst : DupSet) {
5753 for (DbgVariableRecord &DVR :
5754 llvm::reverse(filterDbgVars(Inst->getDbgRecordRange()))) {
5755 DebugVariable DbgUserVariable =
5756 DebugVariable(DVR.getVariable(), DVR.getExpression(),
5757 DVR.getDebugLoc()->getInlinedAt());
5758 auto FilterIt =
5759 FilterOutMap.find(std::make_pair(Inst, DbgUserVariable));
5760 if (FilterIt == FilterOutMap.end())
5761 continue;
5762 if (FilterIt->second != nullptr)
5763 continue;
5764 FilterIt->second = &DVR;
5765 }
5766 }
5767 }
5768
5769 // Perform cloning of the DbgVariableRecords that we plan on sinking, filter
5770 // out any duplicate assignments identified above.
5772 SmallSet<DebugVariable, 4> SunkVariables;
5773 for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {
5775 continue;
5776
5777 DebugVariable DbgUserVariable =
5778 DebugVariable(DVR->getVariable(), DVR->getExpression(),
5779 DVR->getDebugLoc()->getInlinedAt());
5780
5781 // For any variable where there were multiple assignments in the same place,
5782 // ignore all but the last assignment.
5783 if (!FilterOutMap.empty()) {
5784 InstVarPair IVP = std::make_pair(DVR->getInstruction(), DbgUserVariable);
5785 auto It = FilterOutMap.find(IVP);
5786
5787 // Filter out.
5788 if (It != FilterOutMap.end() && It->second != DVR)
5789 continue;
5790 }
5791
5792 if (!SunkVariables.insert(DbgUserVariable).second)
5793 continue;
5794
5795 if (DVR->isDbgAssign())
5796 continue;
5797
5798 DVRClones.emplace_back(DVR->clone());
5799 LLVM_DEBUG(dbgs() << "CLONE: " << *DVRClones.back() << '\n');
5800 }
5801
5802 // Perform salvaging without the clones, then sink the clones.
5803 if (DVRClones.empty())
5804 return;
5805
5806 salvageDebugInfoForDbgValues(*I, DbgVariableRecordsToSalvage);
5807
5808 // The clones are in reverse order of original appearance. Assert that the
5809 // head bit is set on the iterator as we _should_ have received it via
5810 // getFirstInsertionPt. Inserting like this will reverse the clone order as
5811 // we'll repeatedly insert at the head, such as:
5812 // DVR-3 (third insertion goes here)
5813 // DVR-2 (second insertion goes here)
5814 // DVR-1 (first insertion goes here)
5815 // Any-Prior-DVRs
5816 // InsertPtInst
5817 assert(InsertPos.getHeadBit());
5818 for (DbgVariableRecord *DVRClone : DVRClones) {
5819 InsertPos->getParent()->insertDbgRecordBefore(DVRClone, InsertPos);
5820 LLVM_DEBUG(dbgs() << "SINK: " << *DVRClone << '\n');
5821 }
5822}
5823
5825 while (!Worklist.isEmpty()) {
5826 // Walk deferred instructions in reverse order, and push them to the
5827 // worklist, which means they'll end up popped from the worklist in-order.
5828 while (Instruction *I = Worklist.popDeferred()) {
5829 // Check to see if we can DCE the instruction. We do this already here to
5830 // reduce the number of uses and thus allow other folds to trigger.
5831 // Note that eraseInstFromFunction() may push additional instructions on
5832 // the deferred worklist, so this will DCE whole instruction chains.
5835 ++NumDeadInst;
5836 continue;
5837 }
5838
5839 Worklist.push(I);
5840 }
5841
5842 Instruction *I = Worklist.removeOne();
5843 if (I == nullptr) continue; // skip null values.
5844
5845 // Check to see if we can DCE the instruction.
5848 ++NumDeadInst;
5849 continue;
5850 }
5851
5852 if (!DebugCounter::shouldExecute(VisitCounter))
5853 continue;
5854
5855 // See if we can trivially sink this instruction to its user if we can
5856 // prove that the successor is not executed more frequently than our block.
5857 // Return the UserBlock if successful.
5858 auto getOptionalSinkBlockForInst =
5859 [this](Instruction *I) -> std::optional<BasicBlock *> {
5860 if (!CLOpts.code_sinking)
5861 return std::nullopt;
5862
5863 BasicBlock *BB = I->getParent();
5864 BasicBlock *UserParent = nullptr;
5865 unsigned NumUsers = 0;
5866
5867 for (Use &U : I->uses()) {
5868 User *User = U.getUser();
5869 if (User->isDroppable()) {
5870 // Do not sink if there are dereferenceable assumes that would be
5871 // removed.
5873 if (II->getIntrinsicID() != Intrinsic::assume ||
5874 !II->getOperandBundle("dereferenceable"))
5875 continue;
5876 }
5877
5878 if (NumUsers > CLOpts.max_sink_users)
5879 return std::nullopt;
5880
5881 Instruction *UserInst = cast<Instruction>(User);
5882 // Special handling for Phi nodes - get the block the use occurs in.
5883 BasicBlock *UserBB = UserInst->getParent();
5884 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5885 UserBB = PN->getIncomingBlock(U);
5886 // Bail out if we have uses in different blocks. We don't do any
5887 // sophisticated analysis (i.e finding NearestCommonDominator of these
5888 // use blocks).
5889 if (UserParent && UserParent != UserBB)
5890 return std::nullopt;
5891 UserParent = UserBB;
5892
5893 // Make sure these checks are done only once, naturally we do the checks
5894 // the first time we get the userparent, this will save compile time.
5895 if (NumUsers == 0) {
5896 // Try sinking to another block. If that block is unreachable, then do
5897 // not bother. SimplifyCFG should handle it.
5898 if (UserParent == BB || !DT.isReachableFromEntry(UserParent))
5899 return std::nullopt;
5900
5901 auto *Term = UserParent->getTerminator();
5902 // See if the user is one of our successors that has only one
5903 // predecessor, so that we don't have to split the critical edge.
5904 // Another option where we can sink is a block that ends with a
5905 // terminator that does not pass control to other block (such as
5906 // return or unreachable or resume). In this case:
5907 // - I dominates the User (by SSA form);
5908 // - the User will be executed at most once.
5909 // So sinking I down to User is always profitable or neutral.
5910 if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term))
5911 return std::nullopt;
5912
5913 assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");
5914 }
5915
5916 NumUsers++;
5917 }
5918
5919 // No user or only has droppable users.
5920 if (!UserParent)
5921 return std::nullopt;
5922
5923 return UserParent;
5924 };
5925
5926 auto OptBB = getOptionalSinkBlockForInst(I);
5927 if (OptBB) {
5928 auto *UserParent = *OptBB;
5929 // Okay, the CFG is simple enough, try to sink this instruction.
5930 if (tryToSinkInstruction(I, UserParent)) {
5931 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
5932 MadeIRChange = true;
5933 // We'll add uses of the sunk instruction below, but since
5934 // sinking can expose opportunities for it's *operands* add
5935 // them to the worklist
5936 for (Use &U : I->operands())
5937 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
5938 Worklist.push(OpI);
5939 }
5940 }
5941
5942 // Now that we have an instruction, try combining it to simplify it.
5943 Builder.SetInsertPoint(I);
5944 Builder.SetCurrentDebugLocation(I->getDebugLoc());
5945 // Used by our IRBuilder inserter to copy annotation metadata.
5947
5948#ifndef NDEBUG
5949 std::string OrigI;
5950#endif
5951 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS););
5952 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
5953
5954 if (Instruction *Result = visit(*I)) {
5955 ++NumCombined;
5956 // Should we replace the old instruction with a new one?
5957 if (Result != I) {
5958 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'
5959 << " New = " << *Result << '\n');
5960
5961 // We copy the old instruction's DebugLoc to the new instruction, unless
5962 // InstCombine already assigned a DebugLoc to it, in which case we
5963 // should trust the more specifically selected DebugLoc.
5964 Result->setDebugLoc(Result->getDebugLoc().orElse(I->getDebugLoc()));
5965 // We also copy annotation metadata to the new instruction.
5966 Result->copyMetadata(*I, LLVMContext::MD_annotation);
5967 // Everything uses the new instruction now.
5968 I->replaceAllUsesWith(Result);
5969
5970 // Move the name to the new instruction first.
5971 Result->takeName(I);
5972
5973 // Insert the new instruction into the basic block...
5974 BasicBlock *InstParent = I->getParent();
5975 BasicBlock::iterator InsertPos = I->getIterator();
5976
5977 // Are we replace a PHI with something that isn't a PHI, or vice versa?
5978 if (isa<PHINode>(Result) != isa<PHINode>(I)) {
5979 // We need to fix up the insertion point.
5980 if (isa<PHINode>(I)) // PHI -> Non-PHI
5981 InsertPos = InstParent->getFirstInsertionPt();
5982 else // Non-PHI -> PHI
5983 InsertPos = InstParent->getFirstNonPHIIt();
5984 }
5985
5986 Result->insertInto(InstParent, InsertPos);
5987
5988 // Register newly created assumptions.
5989 if (auto *Assume = dyn_cast<AssumeInst>(Result))
5990 AC.registerAssumption(Assume);
5991
5992 // Push the new instruction and any users onto the worklist.
5993 Worklist.pushUsersToWorkList(*Result);
5994 Worklist.push(Result);
5995
5997 } else {
5998 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
5999 << " New = " << *I << '\n');
6000
6001 // If the instruction was modified, it's possible that it is now dead.
6002 // if so, remove it.
6005 } else {
6006 Worklist.pushUsersToWorkList(*I);
6007 Worklist.push(I);
6008 }
6009 }
6010 MadeIRChange = true;
6011 }
6012 }
6013
6014 Worklist.zap();
6015 return MadeIRChange;
6016}
6017
6018// Track the scopes used by !alias.scope and !noalias. In a function, a
6019// @llvm.experimental.noalias.scope.decl is only useful if that scope is used
6020// by both sets. If not, the declaration of the scope can be safely omitted.
6021// The MDNode of the scope can be omitted as well for the instructions that are
6022// part of this function. We do not do that at this point, as this might become
6023// too time consuming to do.
6025 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
6026 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
6027 // Scopes used by every !alias.scope list that scopes from a disjoint-scope
6028 // domain appears in. This is used to catch scopes that don't actually make
6029 // anything noalias.
6031 CommonScopesOfDisjointDomain;
6032
6033 // Record, for each disjoint-scope domain \p ScopeList uses, which of its
6034 // scopes are used by \p ScopeList, adding to a running intersection.
6035 void recordDisjointDomainScopes(const MDNode *ScopeList) {
6037 for (const MDOperand &MDOperand : ScopeList->operands()) {
6038 const auto *MDScope = cast<MDNode>(MDOperand);
6039 const MDNode *Domain = AliasScopeNode(MDScope).getDomain();
6040 if (AliasScopeDomainNode(Domain).hasDisjointScopes())
6041 UsedScopes[Domain].insert(MDScope);
6042 }
6043
6044 for (auto &[Domain, Scopes] : UsedScopes) {
6045 auto [It, Inserted] =
6046 CommonScopesOfDisjointDomain.try_emplace(Domain, Scopes);
6047 if (!Inserted)
6048 llvm::set_intersect(It->second, Scopes);
6049 }
6050 }
6051
6052 // Return true if \p Scope is on the implicit !noalias list of one of the
6053 // analysed accesses, that is, if it belongs to a disjoint-scope domain and
6054 // some access uses that domain without using \p Scope.
6055 bool isImplicitlyNoAlias(const MDNode *Scope) const {
6056 auto It =
6057 CommonScopesOfDisjointDomain.find(AliasScopeNode(Scope).getDomain());
6058 return It != CommonScopesOfDisjointDomain.end() &&
6059 !It->second.contains(Scope);
6060 }
6061
6062public:
6064 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
6065 if (!I->hasMetadataOtherThanDebugLoc())
6066 return;
6067
6068 auto Track = [](Metadata *ScopeList, auto &Container) -> const MDNode * {
6069 const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
6070 if (!MDScopeList || !Container.insert(MDScopeList).second)
6071 return nullptr;
6072 for (const auto &MDOperand : MDScopeList->operands())
6073 if (auto *MDScope = dyn_cast<MDNode>(MDOperand))
6074 Container.insert(MDScope);
6075 return MDScopeList;
6076 };
6077
6078 if (const MDNode *AliasScopeList =
6079 Track(I->getMetadata(LLVMContext::MD_alias_scope),
6080 UsedAliasScopesAndLists))
6081 recordDisjointDomainScopes(AliasScopeList);
6082 Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
6083 }
6084
6087 if (!Decl)
6088 return false;
6089
6090 assert(Decl->use_empty() &&
6091 "llvm.experimental.noalias.scope.decl in use ?");
6092 const MDNode *MDSL = Decl->getScopeList();
6093 assert(MDSL->getNumOperands() == 1 &&
6094 "llvm.experimental.noalias.scope should refer to a single scope");
6095 auto &MDOperand = MDSL->getOperand(0);
6096 // A scope is relevant if it appears in an !alias.scope list, and either it
6097 // appears in a !noalias list, or it is on the implicit !noalias list of
6098 // some access using its disjoint-scope domain.
6099 if (auto *MD = dyn_cast<MDNode>(MDOperand))
6100 return !UsedAliasScopesAndLists.contains(MD) ||
6101 (!UsedNoAliasScopesAndLists.contains(MD) &&
6102 !isImplicitlyNoAlias(MD));
6103
6104 // Not an MDNode ? throw away.
6105 return true;
6106 }
6107};
6108
6109/// Populate the IC worklist from a function, by walking it in reverse
6110/// post-order and adding all reachable code to the worklist.
6111///
6112/// This has a couple of tricks to make the code faster and more powerful. In
6113/// particular, we constant fold and DCE instructions as we go, to avoid adding
6114/// them to the worklist (this significantly speeds up instcombine on code where
6115/// many instructions are dead or constant). Additionally, if we find a branch
6116/// whose condition is a known constant, we only visit the reachable successors.
6118 bool MadeIRChange = false;
6120 SmallVector<Instruction *, 128> InstrsForInstructionWorklist;
6121 DenseMap<Constant *, Constant *> FoldedConstants;
6122 AliasScopeTracker SeenAliasScopes;
6123
6124 auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) {
6125 for (BasicBlock *Succ : successors(BB))
6126 if (Succ != LiveSucc && DeadEdges.insert({BB, Succ}).second)
6127 for (PHINode &PN : Succ->phis())
6128 for (Use &U : PN.incoming_values())
6129 if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(U)) {
6130 U.set(PoisonValue::get(PN.getType()));
6131 MadeIRChange = true;
6132 }
6133 };
6134
6135 for (BasicBlock *BB : RPOT) {
6136 if (!BB->isEntryBlock() && all_of(predecessors(BB), [&](BasicBlock *Pred) {
6137 return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);
6138 })) {
6139 HandleOnlyLiveSuccessor(BB, nullptr);
6140 continue;
6141 }
6142 LiveBlocks.insert(BB);
6143
6144 for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
6145 // ConstantProp instruction if trivially constant.
6146 if (!Inst.use_empty() &&
6147 (Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0))))
6148 if (Constant *C = ConstantFoldInstruction(&Inst, DL, &TLI)) {
6149 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst
6150 << '\n');
6151 Inst.replaceAllUsesWith(C);
6152 ++NumConstProp;
6153 if (isInstructionTriviallyDead(&Inst, &TLI))
6154 Inst.eraseFromParent();
6155 MadeIRChange = true;
6156 continue;
6157 }
6158
6159 // See if we can constant fold its operands.
6160 for (Use &U : Inst.operands()) {
6162 continue;
6163
6164 auto *C = cast<Constant>(U);
6165 Constant *&FoldRes = FoldedConstants[C];
6166 if (!FoldRes)
6167 FoldRes = ConstantFoldConstant(C, DL, &TLI);
6168
6169 if (FoldRes != C) {
6170 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst
6171 << "\n Old = " << *C
6172 << "\n New = " << *FoldRes << '\n');
6173 U = FoldRes;
6174 MadeIRChange = true;
6175 }
6176 }
6177
6178 // Skip processing pseudo intrinsics in InstCombine. Processing
6179 // these call instructions consumes non-trivial amount of time and
6180 // provides no value for the optimization.
6181 if (!isa<PseudoProbeInst>(Inst)) {
6182 InstrsForInstructionWorklist.push_back(&Inst);
6183 SeenAliasScopes.analyse(&Inst);
6184 }
6185 }
6186
6187 // If this is a branch or switch on a constant, mark only the single
6188 // live successor. Otherwise assume all successors are live.
6189 Instruction *TI = BB->getTerminator();
6190 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
6191 if (isa<UndefValue>(BI->getCondition())) {
6192 // Branch on undef is UB.
6193 HandleOnlyLiveSuccessor(BB, nullptr);
6194 continue;
6195 }
6196 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
6197 bool CondVal = Cond->getZExtValue();
6198 HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal));
6199 continue;
6200 }
6201 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
6202 if (isa<UndefValue>(SI->getCondition())) {
6203 // Switch on undef is UB.
6204 HandleOnlyLiveSuccessor(BB, nullptr);
6205 continue;
6206 }
6207 if (auto *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
6208 HandleOnlyLiveSuccessor(BB,
6209 SI->findCaseValue(Cond)->getCaseSuccessor());
6210 continue;
6211 }
6212 }
6213 }
6214
6215 // Remove instructions inside unreachable blocks. This prevents the
6216 // instcombine code from having to deal with some bad special cases, and
6217 // reduces use counts of instructions.
6218 for (BasicBlock &BB : F) {
6219 if (LiveBlocks.count(&BB))
6220 continue;
6221
6222 unsigned NumDeadInstInBB;
6223 NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
6224
6225 MadeIRChange |= NumDeadInstInBB != 0;
6226 NumDeadInst += NumDeadInstInBB;
6227 }
6228
6229 // Once we've found all of the instructions to add to instcombine's worklist,
6230 // add them in reverse order. This way instcombine will visit from the top
6231 // of the function down. This jives well with the way that it adds all uses
6232 // of instructions to the worklist after doing a transformation, thus avoiding
6233 // some N^2 behavior in pathological cases.
6234 Worklist.reserve(InstrsForInstructionWorklist.size());
6235 for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) {
6236 // DCE instruction if trivially dead. As we iterate in reverse program
6237 // order here, we will clean up whole chains of dead instructions.
6238 if (isInstructionTriviallyDead(Inst, &TLI) ||
6239 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
6240 ++NumDeadInst;
6241 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
6242 salvageDebugInfo(*Inst);
6243 Inst->eraseFromParent();
6244 MadeIRChange = true;
6245 continue;
6246 }
6247
6248 Worklist.push(Inst);
6249 }
6250
6251 return MadeIRChange;
6252}
6253
6255 // Collect backedges.
6256 SmallVector<bool> Visited(F.getMaxBlockNumber());
6257 for (BasicBlock *BB : RPOT) {
6258 Visited[BB->getNumber()] = true;
6259 for (BasicBlock *Succ : successors(BB))
6260 if (Visited[Succ->getNumber()])
6261 BackEdges.insert({BB, Succ});
6262 }
6263 ComputedBackEdges = true;
6264}
6265
6271 const InstCombineOptions &Opts) {
6272 auto &DL = F.getDataLayout();
6273 bool VerifyFixpoint = Opts.VerifyFixpoint &&
6274 !F.hasFnAttribute("instcombine-no-verify-fixpoint");
6275
6277
6278 // Lower dbg.declare intrinsics otherwise their value may be clobbered
6279 // by instcombiner.
6280 const auto &CLOpts =
6281 F.getContext().getLibraryOptions().get<InstCombineCLOptions>();
6282 bool MadeIRChange = false;
6283 if (CLOpts.lower_dbg_declare)
6284 MadeIRChange = LowerDbgDeclare(F);
6285
6286 // Iterate while there is work to do.
6287 unsigned Iteration = 0;
6288 while (true) {
6289 if (Iteration >= Opts.MaxIterations && !VerifyFixpoint) {
6290 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations
6291 << " on " << F.getName()
6292 << " reached; stopping without verifying fixpoint\n");
6293 break;
6294 }
6295
6296 ++Iteration;
6297 ++NumWorklistIterations;
6298 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
6299 << F.getName() << "\n");
6300
6301 InstCombinerImpl IC(Worklist, F, AA, AC, TLI, TTI, DT, ORE, BFI, BPI, PSI,
6302 DL, RPOT, CLOpts);
6303 bool MadeChangeInThisIteration = IC.prepareWorklist(F);
6304 MadeChangeInThisIteration |= IC.run();
6305 if (!MadeChangeInThisIteration)
6306 break;
6307
6308 MadeIRChange = true;
6309 if (Iteration > Opts.MaxIterations) {
6311 "Instruction Combining on " + Twine(F.getName()) +
6312 " did not reach a fixpoint after " + Twine(Opts.MaxIterations) +
6313 " iterations. " +
6314 "Use 'instcombine<no-verify-fixpoint>' or function attribute "
6315 "'instcombine-no-verify-fixpoint' to suppress this error.");
6316 }
6317 }
6318
6319 if (Iteration == 1)
6320 ++NumOneIteration;
6321 else if (Iteration == 2)
6322 ++NumTwoIterations;
6323 else if (Iteration == 3)
6324 ++NumThreeIterations;
6325 else
6326 ++NumFourOrMoreIterations;
6327
6328 return MadeIRChange;
6329}
6330
6332
6334 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
6335 static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(
6336 OS, MapClassName2PassName);
6337 OS << '<';
6338 OS << "max-iterations=" << Options.MaxIterations << ";";
6339 OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint";
6340 OS << '>';
6341}
6342
6343char InstCombinePass::ID = 0;
6344
6347 auto &LRT = AM.getResult<LastRunTrackingAnalysis>(F);
6348 // No changes since last InstCombine pass, exit early.
6349 if (LRT.shouldSkip(&ID))
6350 return PreservedAnalyses::all();
6351
6352 auto &AC = AM.getResult<AssumptionAnalysis>(F);
6353 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
6354 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
6356 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
6357
6358 auto *AA = &AM.getResult<AAManager>(F);
6359 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
6360 ProfileSummaryInfo *PSI =
6361 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
6362 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
6363 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
6365
6366 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6367 BFI, BPI, PSI, Options)) {
6368 // No changes, all analyses are preserved.
6369 LRT.update(&ID, /*Changed=*/false);
6370 return PreservedAnalyses::all();
6371 }
6372
6373 // Mark all the analyses that instcombine updates as preserved.
6375 LRT.update(&ID, /*Changed=*/true);
6378 return PA;
6379}
6380
6394
6396 if (skipFunction(F))
6397 return false;
6398
6399 // Required analyses.
6400 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
6401 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
6402 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
6404 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6406
6407 // Optional analyses.
6408 ProfileSummaryInfo *PSI =
6410 BlockFrequencyInfo *BFI =
6411 (PSI && PSI->hasProfileSummary()) ?
6413 nullptr;
6414 BranchProbabilityInfo *BPI = nullptr;
6415 if (auto *WrapperPass =
6417 BPI = &WrapperPass->getBPI();
6418
6419 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
6420 BFI, BPI, PSI, InstCombineOptions());
6421}
6422
6424
6426
6428 "Combine redundant instructions", false, false)
6439 "Combine redundant instructions", false, false)
6440
6441// Initialization Routines.
6445
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:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI)
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 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.
const SmallVectorImpl< MachineOperand > & Cond
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
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition ArrayRef.h:218
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
uint64_t getNumElements() const
Type * getElementType() const
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
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
void setAttributes(AttributeList A)
Set the attributes for this call.
bool doesNotThrow() const
Determine if the call cannot unwind.
Value * getArgOperand(unsigned i) const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
Constant Vector Declarations.
Definition Constants.h:674
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
const Constant * stripPointerCasts() const
Definition Constant.h:237
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 LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Legacy wrapper pass to provide the GlobalsAAResult object.
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2092
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:480
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 * 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
Instruction * visitReturnInst(ReturnInst &RI)
Instruction * visitSwitchInst(SwitchInst &SI)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; }...
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * visitUncondBrInst(UncondBrInst &BI)
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:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
Unconditional Branch instruction.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Use * op_iterator
Definition User.h:254
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition User.cpp: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:159
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:143
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
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:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
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:914
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Value handle that is nullable, but tries to track the Value.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
br_match m_UnconditionalBr(BasicBlock *&Succ)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
auto m_ConstantExpr()
Match a constant expression or a constant that contains a constant expression.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
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.
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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI void initializeInstructionCombiningPassPass(PassRegistry &)
LLVM_ABI 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:2512
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Value * simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef< Value * > Indices, GEPNoWrapFlags NW, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
bool succ_empty(const Instruction *I)
Definition CFG.h:141
LLVM_ABI Value * simplifyFreezeInst(Value *Op, const SimplifyQuery &Q)
Given an operand for a Freeze, see if we can fold the result.
LLVM_ABI FunctionPass * createInstructionCombiningPass()
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
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:1678
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI std::optional< StringRef > getAllocationFamily(const Value *I, const TargetLibraryInfo *TLI)
If a function is part of an allocation family (e.g.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI Value * getReallocatedOperand(const CallBase *CB)
If this is a call to a realloc function, return the reallocated operand.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1713
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc,...
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
Definition Local.cpp:2495
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI 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:406
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition Local.cpp:1813
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DbgRecords)
Salvage only the records in DbgRecords instead of finding every debug user of I.
Definition Local.cpp:2118
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1654
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2441
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
TargetTransformInfo TTI
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
constexpr unsigned BitWidth
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void initializeInstCombine(PassRegistry &)
Initialize all passes linked into the InstCombine library.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
SimplifyQuery getWithInstruction(const Instruction *I) const