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