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