1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #include "InstCombineInternal.h"
37 #include "llvm-c/Initialization.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/BasicAliasAnalysis.h"
44 #include "llvm/Analysis/CFG.h"
45 #include "llvm/Analysis/ConstantFolding.h"
46 #include "llvm/Analysis/EHPersonalities.h"
47 #include "llvm/Analysis/GlobalsModRef.h"
48 #include "llvm/Analysis/InstructionSimplify.h"
49 #include "llvm/Analysis/LoopInfo.h"
50 #include "llvm/Analysis/MemoryBuiltins.h"
51 #include "llvm/Analysis/TargetLibraryInfo.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/GetElementPtrTypeIterator.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/PatternMatch.h"
59 #include "llvm/IR/ValueHandle.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Scalar.h"
66 #include "llvm/Transforms/Utils/Local.h"
70 using namespace llvm::PatternMatch;
72 #define DEBUG_TYPE "instcombine"
74 STATISTIC(NumCombined , "Number of insts combined");
75 STATISTIC(NumConstProp, "Number of constant folds");
76 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
77 STATISTIC(NumSunkInst , "Number of instructions sunk");
78 STATISTIC(NumExpand, "Number of expansions");
79 STATISTIC(NumFactor , "Number of factorizations");
80 STATISTIC(NumReassoc , "Number of reassociations");
83 EnableExpensiveCombines("expensive-combines",
84 cl::desc("Enable expensive instruction combines"));
86 static cl::opt<unsigned>
87 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
88 cl::desc("Maximum array size considered when doing a combine"));
90 Value *InstCombiner::EmitGEPOffset(User *GEP) {
91 return llvm::EmitGEPOffset(Builder, DL, GEP);
94 /// Return true if it is desirable to convert an integer computation from a
95 /// given bit width to a new bit width.
96 /// We don't want to convert from a legal to an illegal type or from a smaller
97 /// to a larger illegal type. A width of '1' is always treated as a legal type
98 /// because i1 is a fundamental type in IR, and there are many specialized
99 /// optimizations for i1 types.
100 bool InstCombiner::shouldChangeType(unsigned FromWidth,
101 unsigned ToWidth) const {
102 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
103 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
105 // If this is a legal integer from type, and the result would be an illegal
106 // type, don't do the transformation.
107 if (FromLegal && !ToLegal)
110 // Otherwise, if both are illegal, do not increase the size of the result. We
111 // do allow things like i160 -> i64, but not i64 -> i160.
112 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
118 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
119 /// We don't want to convert from a legal to an illegal type or from a smaller
120 /// to a larger illegal type. i1 is always treated as a legal type because it is
121 /// a fundamental type in IR, and there are many specialized optimizations for
123 bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
124 assert(From->isIntegerTy() && To->isIntegerTy());
126 unsigned FromWidth = From->getPrimitiveSizeInBits();
127 unsigned ToWidth = To->getPrimitiveSizeInBits();
128 return shouldChangeType(FromWidth, ToWidth);
131 // Return true, if No Signed Wrap should be maintained for I.
132 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
133 // where both B and C should be ConstantInts, results in a constant that does
134 // not overflow. This function only handles the Add and Sub opcodes. For
135 // all other opcodes, the function conservatively returns false.
136 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
137 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
138 if (!OBO || !OBO->hasNoSignedWrap())
141 // We reason about Add and Sub Only.
142 Instruction::BinaryOps Opcode = I.getOpcode();
143 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
146 const APInt *BVal, *CVal;
147 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
150 bool Overflow = false;
151 if (Opcode == Instruction::Add)
152 (void)BVal->sadd_ov(*CVal, Overflow);
154 (void)BVal->ssub_ov(*CVal, Overflow);
159 /// Conservatively clears subclassOptionalData after a reassociation or
160 /// commutation. We preserve fast-math flags when applicable as they can be
162 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
163 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
165 I.clearSubclassOptionalData();
169 FastMathFlags FMF = I.getFastMathFlags();
170 I.clearSubclassOptionalData();
171 I.setFastMathFlags(FMF);
174 /// Combine constant operands of associative operations either before or after a
175 /// cast to eliminate one of the associative operations:
176 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
177 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
178 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
179 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
180 if (!Cast || !Cast->hasOneUse())
183 // TODO: Enhance logic for other casts and remove this check.
184 auto CastOpcode = Cast->getOpcode();
185 if (CastOpcode != Instruction::ZExt)
188 // TODO: Enhance logic for other BinOps and remove this check.
189 if (!BinOp1->isBitwiseLogicOp())
192 auto AssocOpcode = BinOp1->getOpcode();
193 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
194 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
198 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
199 !match(BinOp2->getOperand(1), m_Constant(C2)))
202 // TODO: This assumes a zext cast.
203 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
204 // to the destination type might lose bits.
206 // Fold the constants together in the destination type:
207 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
208 Type *DestTy = C1->getType();
209 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
210 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
211 Cast->setOperand(0, BinOp2->getOperand(0));
212 BinOp1->setOperand(1, FoldedC);
216 /// This performs a few simplifications for operators that are associative or
219 /// Commutative operators:
221 /// 1. Order operands such that they are listed from right (least complex) to
222 /// left (most complex). This puts constants before unary operators before
223 /// binary operators.
225 /// Associative operators:
227 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
228 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
230 /// Associative and commutative operators:
232 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
233 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
234 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
235 /// if C1 and C2 are constants.
236 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
237 Instruction::BinaryOps Opcode = I.getOpcode();
238 bool Changed = false;
241 // Order operands such that they are listed from right (least complex) to
242 // left (most complex). This puts constants before unary operators before
244 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
245 getComplexity(I.getOperand(1)))
246 Changed = !I.swapOperands();
248 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
249 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
251 if (I.isAssociative()) {
252 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
253 if (Op0 && Op0->getOpcode() == Opcode) {
254 Value *A = Op0->getOperand(0);
255 Value *B = Op0->getOperand(1);
256 Value *C = I.getOperand(1);
258 // Does "B op C" simplify?
259 if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
260 // It simplifies to V. Form "A op V".
263 // Conservatively clear the optional flags, since they may not be
264 // preserved by the reassociation.
265 if (MaintainNoSignedWrap(I, B, C) &&
266 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
267 // Note: this is only valid because SimplifyBinOp doesn't look at
268 // the operands to Op0.
269 I.clearSubclassOptionalData();
270 I.setHasNoSignedWrap(true);
272 ClearSubclassDataAfterReassociation(I);
281 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
282 if (Op1 && Op1->getOpcode() == Opcode) {
283 Value *A = I.getOperand(0);
284 Value *B = Op1->getOperand(0);
285 Value *C = Op1->getOperand(1);
287 // Does "A op B" simplify?
288 if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
289 // It simplifies to V. Form "V op C".
292 // Conservatively clear the optional flags, since they may not be
293 // preserved by the reassociation.
294 ClearSubclassDataAfterReassociation(I);
302 if (I.isAssociative() && I.isCommutative()) {
303 if (simplifyAssocCastAssoc(&I)) {
309 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
310 if (Op0 && Op0->getOpcode() == Opcode) {
311 Value *A = Op0->getOperand(0);
312 Value *B = Op0->getOperand(1);
313 Value *C = I.getOperand(1);
315 // Does "C op A" simplify?
316 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
317 // It simplifies to V. Form "V op B".
320 // Conservatively clear the optional flags, since they may not be
321 // preserved by the reassociation.
322 ClearSubclassDataAfterReassociation(I);
329 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
330 if (Op1 && Op1->getOpcode() == Opcode) {
331 Value *A = I.getOperand(0);
332 Value *B = Op1->getOperand(0);
333 Value *C = Op1->getOperand(1);
335 // Does "C op A" simplify?
336 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
337 // It simplifies to V. Form "B op V".
340 // Conservatively clear the optional flags, since they may not be
341 // preserved by the reassociation.
342 ClearSubclassDataAfterReassociation(I);
349 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
350 // if C1 and C2 are constants.
352 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
353 isa<Constant>(Op0->getOperand(1)) &&
354 isa<Constant>(Op1->getOperand(1)) &&
355 Op0->hasOneUse() && Op1->hasOneUse()) {
356 Value *A = Op0->getOperand(0);
357 Constant *C1 = cast<Constant>(Op0->getOperand(1));
358 Value *B = Op1->getOperand(0);
359 Constant *C2 = cast<Constant>(Op1->getOperand(1));
361 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
362 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
363 if (isa<FPMathOperator>(New)) {
364 FastMathFlags Flags = I.getFastMathFlags();
365 Flags &= Op0->getFastMathFlags();
366 Flags &= Op1->getFastMathFlags();
367 New->setFastMathFlags(Flags);
369 InsertNewInstWith(New, I);
371 I.setOperand(0, New);
372 I.setOperand(1, Folded);
373 // Conservatively clear the optional flags, since they may not be
374 // preserved by the reassociation.
375 ClearSubclassDataAfterReassociation(I);
382 // No further simplifications.
387 /// Return whether "X LOp (Y ROp Z)" is always equal to
388 /// "(X LOp Y) ROp (X LOp Z)".
389 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
390 Instruction::BinaryOps ROp) {
395 case Instruction::And:
396 // And distributes over Or and Xor.
400 case Instruction::Or:
401 case Instruction::Xor:
405 case Instruction::Mul:
406 // Multiplication distributes over addition and subtraction.
410 case Instruction::Add:
411 case Instruction::Sub:
415 case Instruction::Or:
416 // Or distributes over And.
420 case Instruction::And:
426 /// Return whether "(X LOp Y) ROp Z" is always equal to
427 /// "(X ROp Z) LOp (Y ROp Z)".
428 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
429 Instruction::BinaryOps ROp) {
430 if (Instruction::isCommutative(ROp))
431 return LeftDistributesOverRight(ROp, LOp);
436 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
437 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
438 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
439 case Instruction::And:
440 case Instruction::Or:
441 case Instruction::Xor:
445 case Instruction::Shl:
446 case Instruction::LShr:
447 case Instruction::AShr:
451 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
452 // but this requires knowing that the addition does not overflow and other
457 /// This function returns identity value for given opcode, which can be used to
458 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
459 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
460 if (isa<Constant>(V))
463 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
466 /// This function factors binary ops which can be combined using distributive
467 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
468 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
469 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
470 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
472 static Instruction::BinaryOps
473 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
474 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
475 assert(Op && "Expected a binary operator");
477 LHS = Op->getOperand(0);
478 RHS = Op->getOperand(1);
480 switch (TopLevelOpcode) {
482 return Op->getOpcode();
484 case Instruction::Add:
485 case Instruction::Sub:
486 if (Op->getOpcode() == Instruction::Shl) {
487 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
488 // The multiplier is really 1 << CST.
489 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
490 return Instruction::Mul;
493 return Op->getOpcode();
496 // TODO: We can add other conversions e.g. shr => div etc.
499 /// This tries to simplify binary operations by factorizing out common terms
500 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
501 Value *InstCombiner::tryFactorization(InstCombiner::BuilderTy *Builder,
503 Instruction::BinaryOps InnerOpcode,
504 Value *A, Value *B, Value *C, Value *D) {
505 assert(A && B && C && D && "All values must be provided");
508 Value *SimplifiedInst = nullptr;
509 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
510 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
512 // Does "X op' Y" always equal "Y op' X"?
513 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
515 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
516 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
517 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
518 // commutative case, "(A op' B) op (C op' A)"?
519 if (A == C || (InnerCommutative && A == D)) {
522 // Consider forming "A op' (B op D)".
523 // If "B op D" simplifies then it can be formed with no cost.
524 V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
525 // If "B op D" doesn't simplify then only go on if both of the existing
526 // operations "A op' B" and "C op' D" will be zapped as no longer used.
527 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
528 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
530 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
534 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
535 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
536 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
537 // commutative case, "(A op' B) op (B op' D)"?
538 if (B == D || (InnerCommutative && B == C)) {
541 // Consider forming "(A op C) op' B".
542 // If "A op C" simplifies then it can be formed with no cost.
543 V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
545 // If "A op C" doesn't simplify then only go on if both of the existing
546 // operations "A op' B" and "C op' D" will be zapped as no longer used.
547 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
548 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
550 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
554 if (SimplifiedInst) {
556 SimplifiedInst->takeName(&I);
558 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
559 // TODO: Check for NUW.
560 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
561 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
563 if (isa<OverflowingBinaryOperator>(&I))
564 HasNSW = I.hasNoSignedWrap();
566 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
567 HasNSW &= LOBO->hasNoSignedWrap();
569 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
570 HasNSW &= ROBO->hasNoSignedWrap();
572 // We can propagate 'nsw' if we know that
573 // %Y = mul nsw i16 %X, C
574 // %Z = add nsw i16 %Y, %X
576 // %Z = mul nsw i16 %X, C+1
578 // iff C+1 isn't INT_MIN
580 if (TopLevelOpcode == Instruction::Add &&
581 InnerOpcode == Instruction::Mul)
582 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
583 BO->setHasNoSignedWrap(HasNSW);
587 return SimplifiedInst;
590 /// This tries to simplify binary operations which some other binary operation
591 /// distributes over either by factorizing out common terms
592 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
593 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
594 /// Returns the simplified value, or null if it didn't simplify.
595 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
596 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
597 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
598 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
599 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
603 Value *A, *B, *C, *D;
604 Instruction::BinaryOps LHSOpcode, RHSOpcode;
606 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
608 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
610 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
612 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
613 if (Value *V = tryFactorization(Builder, I, LHSOpcode, A, B, C, D))
616 // The instruction has the form "(A op' B) op (C)". Try to factorize common
619 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
621 tryFactorization(Builder, I, LHSOpcode, A, B, RHS, Ident))
624 // The instruction has the form "(B) op (C op' D)". Try to factorize common
627 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
629 tryFactorization(Builder, I, RHSOpcode, LHS, Ident, C, D))
634 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
635 // The instruction has the form "(A op' B) op C". See if expanding it out
636 // to "(A op C) op' (B op C)" results in simplifications.
637 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
638 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
640 // Do "A op C" and "B op C" both simplify?
642 SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)))
644 SimplifyBinOp(TopLevelOpcode, B, C, SQ.getWithInstruction(&I))) {
645 // They do! Return "L op' R".
647 C = Builder->CreateBinOp(InnerOpcode, L, R);
653 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
654 // The instruction has the form "A op (B op' C)". See if expanding it out
655 // to "(A op B) op' (A op C)" results in simplifications.
656 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
657 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
659 // Do "A op B" and "A op C" both simplify?
661 SimplifyBinOp(TopLevelOpcode, A, B, SQ.getWithInstruction(&I)))
663 SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I))) {
664 // They do! Return "L op' R".
666 A = Builder->CreateBinOp(InnerOpcode, L, R);
672 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
673 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
674 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
675 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
676 if (SI0->getCondition() == SI1->getCondition()) {
679 SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
680 SI1->getFalseValue(), SQ.getWithInstruction(&I)))
681 SI = Builder->CreateSelect(SI0->getCondition(),
682 Builder->CreateBinOp(TopLevelOpcode,
684 SI1->getTrueValue()),
687 SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
688 SI1->getTrueValue(), SQ.getWithInstruction(&I)))
689 SI = Builder->CreateSelect(
690 SI0->getCondition(), V,
691 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
692 SI1->getFalseValue()));
704 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
705 /// constant zero (which is the 'negate' form).
706 Value *InstCombiner::dyn_castNegVal(Value *V) const {
707 if (BinaryOperator::isNeg(V))
708 return BinaryOperator::getNegArgument(V);
710 // Constants can be considered to be negated values if they can be folded.
711 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
712 return ConstantExpr::getNeg(C);
714 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
715 if (C->getType()->getElementType()->isIntegerTy())
716 return ConstantExpr::getNeg(C);
718 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
719 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
720 Constant *Elt = CV->getAggregateElement(i);
724 if (isa<UndefValue>(Elt))
727 if (!isa<ConstantInt>(Elt))
730 return ConstantExpr::getNeg(CV);
736 /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
737 /// a constant negative zero (which is the 'negate' form).
738 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
739 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
740 return BinaryOperator::getFNegArgument(V);
742 // Constants can be considered to be negated values if they can be folded.
743 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
744 return ConstantExpr::getFNeg(C);
746 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
747 if (C->getType()->getElementType()->isFloatingPointTy())
748 return ConstantExpr::getFNeg(C);
753 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
755 if (auto *Cast = dyn_cast<CastInst>(&I))
756 return IC->Builder->CreateCast(Cast->getOpcode(), SO, I.getType());
758 assert(I.isBinaryOp() && "Unexpected opcode for select folding");
760 // Figure out if the constant is the left or the right argument.
761 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
762 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
764 if (auto *SOC = dyn_cast<Constant>(SO)) {
766 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
767 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
770 Value *Op0 = SO, *Op1 = ConstOperand;
774 auto *BO = cast<BinaryOperator>(&I);
775 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
776 SO->getName() + ".op");
777 auto *FPInst = dyn_cast<Instruction>(RI);
778 if (FPInst && isa<FPMathOperator>(FPInst))
779 FPInst->copyFastMathFlags(BO);
783 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
784 // Don't modify shared select instructions.
785 if (!SI->hasOneUse())
788 Value *TV = SI->getTrueValue();
789 Value *FV = SI->getFalseValue();
790 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
793 // Bool selects with constant operands can be folded to logical ops.
794 if (SI->getType()->getScalarType()->isIntegerTy(1))
797 // If it's a bitcast involving vectors, make sure it has the same number of
798 // elements on both sides.
799 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
800 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
801 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
803 // Verify that either both or neither are vectors.
804 if ((SrcTy == nullptr) != (DestTy == nullptr))
807 // If vectors, verify that they have the same number of elements.
808 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
812 // Test if a CmpInst instruction is used exclusively by a select as
813 // part of a minimum or maximum operation. If so, refrain from doing
814 // any other folding. This helps out other analyses which understand
815 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
816 // and CodeGen. And in this case, at least one of the comparison
817 // operands has at least one user besides the compare (the select),
818 // which would often largely negate the benefit of folding anyway.
819 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
820 if (CI->hasOneUse()) {
821 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
822 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
823 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
828 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, this);
829 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, this);
830 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
833 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
835 bool ConstIsRHS = isa<Constant>(I->getOperand(1));
836 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
838 if (auto *InC = dyn_cast<Constant>(InV)) {
840 return ConstantExpr::get(I->getOpcode(), InC, C);
841 return ConstantExpr::get(I->getOpcode(), C, InC);
844 Value *Op0 = InV, *Op1 = C;
848 Value *RI = IC->Builder->CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
849 auto *FPInst = dyn_cast<Instruction>(RI);
850 if (FPInst && isa<FPMathOperator>(FPInst))
851 FPInst->copyFastMathFlags(I);
855 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
856 unsigned NumPHIValues = PN->getNumIncomingValues();
857 if (NumPHIValues == 0)
860 // We normally only transform phis with a single use. However, if a PHI has
861 // multiple uses and they are all the same operation, we can fold *all* of the
862 // uses into the PHI.
863 if (!PN->hasOneUse()) {
864 // Walk the use list for the instruction, comparing them to I.
865 for (User *U : PN->users()) {
866 Instruction *UI = cast<Instruction>(U);
867 if (UI != &I && !I.isIdenticalTo(UI))
870 // Otherwise, we can replace *all* users with the new PHI we form.
873 // Check to see if all of the operands of the PHI are simple constants
874 // (constantint/constantfp/undef). If there is one non-constant value,
875 // remember the BB it is in. If there is more than one or if *it* is a PHI,
876 // bail out. We don't do arbitrary constant expressions here because moving
877 // their computation can be expensive without a cost model.
878 BasicBlock *NonConstBB = nullptr;
879 for (unsigned i = 0; i != NumPHIValues; ++i) {
880 Value *InVal = PN->getIncomingValue(i);
881 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
884 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
885 if (NonConstBB) return nullptr; // More than one non-const value.
887 NonConstBB = PN->getIncomingBlock(i);
889 // If the InVal is an invoke at the end of the pred block, then we can't
890 // insert a computation after it without breaking the edge.
891 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
892 if (II->getParent() == NonConstBB)
895 // If the incoming non-constant value is in I's block, we will remove one
896 // instruction, but insert another equivalent one, leading to infinite
898 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
902 // If there is exactly one non-constant value, we can insert a copy of the
903 // operation in that block. However, if this is a critical edge, we would be
904 // inserting the computation on some other paths (e.g. inside a loop). Only
905 // do this if the pred block is unconditionally branching into the phi block.
906 if (NonConstBB != nullptr) {
907 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
908 if (!BI || !BI->isUnconditional()) return nullptr;
911 // Okay, we can do the transformation: create the new PHI node.
912 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
913 InsertNewInstBefore(NewPN, *PN);
916 // If we are going to have to insert a new computation, do so right before the
917 // predecessor's terminator.
919 Builder->SetInsertPoint(NonConstBB->getTerminator());
921 // Next, add all of the operands to the PHI.
922 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
923 // We only currently try to fold the condition of a select when it is a phi,
924 // not the true/false values.
925 Value *TrueV = SI->getTrueValue();
926 Value *FalseV = SI->getFalseValue();
927 BasicBlock *PhiTransBB = PN->getParent();
928 for (unsigned i = 0; i != NumPHIValues; ++i) {
929 BasicBlock *ThisBB = PN->getIncomingBlock(i);
930 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
931 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
932 Value *InV = nullptr;
933 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
934 // even if currently isNullValue gives false.
935 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
936 // For vector constants, we cannot use isNullValue to fold into
937 // FalseVInPred versus TrueVInPred. When we have individual nonzero
938 // elements in the vector, we will incorrectly fold InC to
940 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
941 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
943 InV = Builder->CreateSelect(PN->getIncomingValue(i),
944 TrueVInPred, FalseVInPred, "phitmp");
945 NewPN->addIncoming(InV, ThisBB);
947 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
948 Constant *C = cast<Constant>(I.getOperand(1));
949 for (unsigned i = 0; i != NumPHIValues; ++i) {
950 Value *InV = nullptr;
951 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
952 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
953 else if (isa<ICmpInst>(CI))
954 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
957 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
959 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
961 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
962 for (unsigned i = 0; i != NumPHIValues; ++i) {
963 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), this);
964 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
967 CastInst *CI = cast<CastInst>(&I);
968 Type *RetTy = CI->getType();
969 for (unsigned i = 0; i != NumPHIValues; ++i) {
971 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
972 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
974 InV = Builder->CreateCast(CI->getOpcode(),
975 PN->getIncomingValue(i), I.getType(), "phitmp");
976 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
980 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
981 Instruction *User = cast<Instruction>(*UI++);
982 if (User == &I) continue;
983 replaceInstUsesWith(*User, NewPN);
984 eraseInstFromFunction(*User);
986 return replaceInstUsesWith(I, NewPN);
989 Instruction *InstCombiner::foldOpWithConstantIntoOperand(BinaryOperator &I) {
990 assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
992 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
993 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
995 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
996 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1002 /// Given a pointer type and a constant offset, determine whether or not there
1003 /// is a sequence of GEP indices into the pointed type that will land us at the
1004 /// specified offset. If so, fill them into NewIndices and return the resultant
1005 /// element type, otherwise return null.
1006 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1007 SmallVectorImpl<Value *> &NewIndices) {
1008 Type *Ty = PtrTy->getElementType();
1012 // Start with the index over the outer type. Note that the type size
1013 // might be zero (even if the offset isn't zero) if the indexed type
1014 // is something like [0 x {int, int}]
1015 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
1016 int64_t FirstIdx = 0;
1017 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1018 FirstIdx = Offset/TySize;
1019 Offset -= FirstIdx*TySize;
1021 // Handle hosts where % returns negative instead of values [0..TySize).
1025 assert(Offset >= 0);
1027 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1030 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
1032 // Index into the types. If we fail, set OrigBase to null.
1034 // Indexing into tail padding between struct/array elements.
1035 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1038 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1039 const StructLayout *SL = DL.getStructLayout(STy);
1040 assert(Offset < (int64_t)SL->getSizeInBytes() &&
1041 "Offset must stay within the indexed type");
1043 unsigned Elt = SL->getElementContainingOffset(Offset);
1044 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1047 Offset -= SL->getElementOffset(Elt);
1048 Ty = STy->getElementType(Elt);
1049 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1050 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1051 assert(EltSize && "Cannot index into a zero-sized array");
1052 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
1054 Ty = AT->getElementType();
1056 // Otherwise, we can't index into the middle of this atomic type, bail.
1064 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1065 // If this GEP has only 0 indices, it is the same pointer as
1066 // Src. If Src is not a trivial GEP too, don't combine
1068 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1074 /// Return a value X such that Val = X * Scale, or null if none.
1075 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1076 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1077 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1078 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1079 Scale.getBitWidth() && "Scale not compatible with value!");
1081 // If Val is zero or Scale is one then Val = Val * Scale.
1082 if (match(Val, m_Zero()) || Scale == 1) {
1083 NoSignedWrap = true;
1087 // If Scale is zero then it does not divide Val.
1088 if (Scale.isMinValue())
1091 // Look through chains of multiplications, searching for a constant that is
1092 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1093 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1094 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1097 // Val = M1 * X || Analysis starts here and works down
1098 // M1 = M2 * Y || Doesn't descend into terms with more
1099 // M2 = Z * 4 \/ than one use
1101 // Then to modify a term at the bottom:
1104 // M1 = Z * Y || Replaced M2 with Z
1106 // Then to work back up correcting nsw flags.
1108 // Op - the term we are currently analyzing. Starts at Val then drills down.
1109 // Replaced with its descaled value before exiting from the drill down loop.
1112 // Parent - initially null, but after drilling down notes where Op came from.
1113 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1114 // 0'th operand of Val.
1115 std::pair<Instruction*, unsigned> Parent;
1117 // Set if the transform requires a descaling at deeper levels that doesn't
1119 bool RequireNoSignedWrap = false;
1121 // Log base 2 of the scale. Negative if not a power of 2.
1122 int32_t logScale = Scale.exactLogBase2();
1124 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1126 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1127 // If Op is a constant divisible by Scale then descale to the quotient.
1128 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1129 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1130 if (!Remainder.isMinValue())
1131 // Not divisible by Scale.
1133 // Replace with the quotient in the parent.
1134 Op = ConstantInt::get(CI->getType(), Quotient);
1135 NoSignedWrap = true;
1139 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1141 if (BO->getOpcode() == Instruction::Mul) {
1143 NoSignedWrap = BO->hasNoSignedWrap();
1144 if (RequireNoSignedWrap && !NoSignedWrap)
1147 // There are three cases for multiplication: multiplication by exactly
1148 // the scale, multiplication by a constant different to the scale, and
1149 // multiplication by something else.
1150 Value *LHS = BO->getOperand(0);
1151 Value *RHS = BO->getOperand(1);
1153 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1154 // Multiplication by a constant.
1155 if (CI->getValue() == Scale) {
1156 // Multiplication by exactly the scale, replace the multiplication
1157 // by its left-hand side in the parent.
1162 // Otherwise drill down into the constant.
1163 if (!Op->hasOneUse())
1166 Parent = std::make_pair(BO, 1);
1170 // Multiplication by something else. Drill down into the left-hand side
1171 // since that's where the reassociate pass puts the good stuff.
1172 if (!Op->hasOneUse())
1175 Parent = std::make_pair(BO, 0);
1179 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1180 isa<ConstantInt>(BO->getOperand(1))) {
1181 // Multiplication by a power of 2.
1182 NoSignedWrap = BO->hasNoSignedWrap();
1183 if (RequireNoSignedWrap && !NoSignedWrap)
1186 Value *LHS = BO->getOperand(0);
1187 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1188 getLimitedValue(Scale.getBitWidth());
1191 if (Amt == logScale) {
1192 // Multiplication by exactly the scale, replace the multiplication
1193 // by its left-hand side in the parent.
1197 if (Amt < logScale || !Op->hasOneUse())
1200 // Multiplication by more than the scale. Reduce the multiplying amount
1201 // by the scale in the parent.
1202 Parent = std::make_pair(BO, 1);
1203 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1208 if (!Op->hasOneUse())
1211 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1212 if (Cast->getOpcode() == Instruction::SExt) {
1213 // Op is sign-extended from a smaller type, descale in the smaller type.
1214 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1215 APInt SmallScale = Scale.trunc(SmallSize);
1216 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1217 // descale Op as (sext Y) * Scale. In order to have
1218 // sext (Y * SmallScale) = (sext Y) * Scale
1219 // some conditions need to hold however: SmallScale must sign-extend to
1220 // Scale and the multiplication Y * SmallScale should not overflow.
1221 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1222 // SmallScale does not sign-extend to Scale.
1224 assert(SmallScale.exactLogBase2() == logScale);
1225 // Require that Y * SmallScale must not overflow.
1226 RequireNoSignedWrap = true;
1228 // Drill down through the cast.
1229 Parent = std::make_pair(Cast, 0);
1234 if (Cast->getOpcode() == Instruction::Trunc) {
1235 // Op is truncated from a larger type, descale in the larger type.
1236 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1237 // trunc (Y * sext Scale) = (trunc Y) * Scale
1238 // always holds. However (trunc Y) * Scale may overflow even if
1239 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1240 // from this point up in the expression (see later).
1241 if (RequireNoSignedWrap)
1244 // Drill down through the cast.
1245 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1246 Parent = std::make_pair(Cast, 0);
1247 Scale = Scale.sext(LargeSize);
1248 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1250 assert(Scale.exactLogBase2() == logScale);
1255 // Unsupported expression, bail out.
1259 // If Op is zero then Val = Op * Scale.
1260 if (match(Op, m_Zero())) {
1261 NoSignedWrap = true;
1265 // We know that we can successfully descale, so from here on we can safely
1266 // modify the IR. Op holds the descaled version of the deepest term in the
1267 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1271 // The expression only had one term.
1274 // Rewrite the parent using the descaled version of its operand.
1275 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1276 assert(Op != Parent.first->getOperand(Parent.second) &&
1277 "Descaling was a no-op?");
1278 Parent.first->setOperand(Parent.second, Op);
1279 Worklist.Add(Parent.first);
1281 // Now work back up the expression correcting nsw flags. The logic is based
1282 // on the following observation: if X * Y is known not to overflow as a signed
1283 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1284 // then X * Z will not overflow as a signed multiplication either. As we work
1285 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1286 // current level has strictly smaller absolute value than the original.
1287 Instruction *Ancestor = Parent.first;
1289 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1290 // If the multiplication wasn't nsw then we can't say anything about the
1291 // value of the descaled multiplication, and we have to clear nsw flags
1292 // from this point on up.
1293 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1294 NoSignedWrap &= OpNoSignedWrap;
1295 if (NoSignedWrap != OpNoSignedWrap) {
1296 BO->setHasNoSignedWrap(NoSignedWrap);
1297 Worklist.Add(Ancestor);
1299 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1300 // The fact that the descaled input to the trunc has smaller absolute
1301 // value than the original input doesn't tell us anything useful about
1302 // the absolute values of the truncations.
1303 NoSignedWrap = false;
1305 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1306 "Failed to keep proper track of nsw flags while drilling down?");
1308 if (Ancestor == Val)
1309 // Got to the top, all done!
1312 // Move up one level in the expression.
1313 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1314 Ancestor = Ancestor->user_back();
1318 /// \brief Creates node of binary operation with the same attributes as the
1319 /// specified one but with other operands.
1320 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1321 InstCombiner::BuilderTy *B) {
1322 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1323 // If LHS and RHS are constant, BO won't be a binary operator.
1324 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1325 NewBO->copyIRFlags(&Inst);
1329 /// \brief Makes transformation of binary operation specific for vector types.
1330 /// \param Inst Binary operator to transform.
1331 /// \return Pointer to node that must replace the original binary operator, or
1332 /// null pointer if no transformation was made.
1333 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1334 if (!Inst.getType()->isVectorTy()) return nullptr;
1336 // It may not be safe to reorder shuffles and things like div, urem, etc.
1337 // because we may trap when executing those ops on unknown vector elements.
1339 if (!isSafeToSpeculativelyExecute(&Inst))
1342 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1343 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1344 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1345 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1347 // If both arguments of the binary operation are shuffles that use the same
1348 // mask and shuffle within a single vector, move the shuffle after the binop:
1349 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1350 auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1351 auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1352 if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1353 isa<UndefValue>(LShuf->getOperand(1)) &&
1354 isa<UndefValue>(RShuf->getOperand(1)) &&
1355 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1356 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1357 RShuf->getOperand(0), Builder);
1358 return Builder->CreateShuffleVector(
1359 NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
1362 // If one argument is a shuffle within one vector, the other is a constant,
1363 // try moving the shuffle after the binary operation.
1364 ShuffleVectorInst *Shuffle = nullptr;
1365 Constant *C1 = nullptr;
1366 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1367 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1368 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1369 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1370 if (Shuffle && C1 &&
1371 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1372 isa<UndefValue>(Shuffle->getOperand(1)) &&
1373 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1374 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1375 // Find constant C2 that has property:
1376 // shuffle(C2, ShMask) = C1
1377 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1378 // reorder is not possible.
1379 SmallVector<Constant*, 16> C2M(VWidth,
1380 UndefValue::get(C1->getType()->getScalarType()));
1381 bool MayChange = true;
1382 for (unsigned I = 0; I < VWidth; ++I) {
1383 if (ShMask[I] >= 0) {
1384 assert(ShMask[I] < (int)VWidth);
1385 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1389 C2M[ShMask[I]] = C1->getAggregateElement(I);
1393 Constant *C2 = ConstantVector::get(C2M);
1394 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1395 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1396 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1397 return Builder->CreateShuffleVector(NewBO,
1398 UndefValue::get(Inst.getType()), Shuffle->getMask());
1405 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1406 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1408 if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops,
1409 SQ.getWithInstruction(&GEP)))
1410 return replaceInstUsesWith(GEP, V);
1412 Value *PtrOp = GEP.getOperand(0);
1414 // Eliminate unneeded casts for indices, and replace indices which displace
1415 // by multiples of a zero size type with zero.
1416 bool MadeChange = false;
1418 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1420 gep_type_iterator GTI = gep_type_begin(GEP);
1421 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1423 // Skip indices into struct types.
1427 // Index type should have the same width as IntPtr
1428 Type *IndexTy = (*I)->getType();
1429 Type *NewIndexType = IndexTy->isVectorTy() ?
1430 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1432 // If the element type has zero size then any index over it is equivalent
1433 // to an index of zero, so replace it with zero if it is not zero already.
1434 Type *EltTy = GTI.getIndexedType();
1435 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1436 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1437 *I = Constant::getNullValue(NewIndexType);
1441 if (IndexTy != NewIndexType) {
1442 // If we are using a wider index than needed for this platform, shrink
1443 // it to what we need. If narrower, sign-extend it to what we need.
1444 // This explicit cast can make subsequent optimizations more obvious.
1445 *I = Builder->CreateIntCast(*I, NewIndexType, true);
1452 // Check to see if the inputs to the PHI node are getelementptr instructions.
1453 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1454 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1458 // Don't fold a GEP into itself through a PHI node. This can only happen
1459 // through the back-edge of a loop. Folding a GEP into itself means that
1460 // the value of the previous iteration needs to be stored in the meantime,
1461 // thus requiring an additional register variable to be live, but not
1462 // actually achieving anything (the GEP still needs to be executed once per
1469 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1470 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1471 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1474 // As for Op1 above, don't try to fold a GEP into itself.
1478 // Keep track of the type as we walk the GEP.
1479 Type *CurTy = nullptr;
1481 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1482 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1485 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1487 // We have not seen any differences yet in the GEPs feeding the
1488 // PHI yet, so we record this one if it is allowed to be a
1491 // The first two arguments can vary for any GEP, the rest have to be
1492 // static for struct slots
1493 if (J > 1 && CurTy->isStructTy())
1498 // The GEP is different by more than one input. While this could be
1499 // extended to support GEPs that vary by more than one variable it
1500 // doesn't make sense since it greatly increases the complexity and
1501 // would result in an R+R+R addressing mode which no backend
1502 // directly supports and would need to be broken into several
1503 // simpler instructions anyway.
1508 // Sink down a layer of the type for the next iteration.
1511 CurTy = Op1->getSourceElementType();
1512 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1513 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1521 // If not all GEPs are identical we'll have to create a new PHI node.
1522 // Check that the old PHI node has only one use so that it will get
1524 if (DI != -1 && !PN->hasOneUse())
1527 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1529 // All the GEPs feeding the PHI are identical. Clone one down into our
1530 // BB so that it can be merged with the current GEP.
1531 GEP.getParent()->getInstList().insert(
1532 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1534 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1535 // into the current block so it can be merged, and create a new PHI to
1539 IRBuilderBase::InsertPointGuard Guard(*Builder);
1540 Builder->SetInsertPoint(PN);
1541 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1542 PN->getNumOperands());
1545 for (auto &I : PN->operands())
1546 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1547 PN->getIncomingBlock(I));
1549 NewGEP->setOperand(DI, NewPN);
1550 GEP.getParent()->getInstList().insert(
1551 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1552 NewGEP->setOperand(DI, NewPN);
1555 GEP.setOperand(0, NewGEP);
1559 // Combine Indices - If the source pointer to this getelementptr instruction
1560 // is a getelementptr instruction, combine the indices of the two
1561 // getelementptr instructions into a single instruction.
1563 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1564 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1567 // Note that if our source is a gep chain itself then we wait for that
1568 // chain to be resolved before we perform this transformation. This
1569 // avoids us creating a TON of code in some cases.
1570 if (GEPOperator *SrcGEP =
1571 dyn_cast<GEPOperator>(Src->getOperand(0)))
1572 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1573 return nullptr; // Wait until our source is folded to completion.
1575 SmallVector<Value*, 8> Indices;
1577 // Find out whether the last index in the source GEP is a sequential idx.
1578 bool EndsWithSequential = false;
1579 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1581 EndsWithSequential = I.isSequential();
1583 // Can we combine the two pointer arithmetics offsets?
1584 if (EndsWithSequential) {
1585 // Replace: gep (gep %P, long B), long A, ...
1586 // With: T = long A+B; gep %P, T, ...
1588 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1589 Value *GO1 = GEP.getOperand(1);
1591 // If they aren't the same type, then the input hasn't been processed
1592 // by the loop above yet (which canonicalizes sequential index types to
1593 // intptr_t). Just avoid transforming this until the input has been
1595 if (SO1->getType() != GO1->getType())
1599 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
1600 // Only do the combine when we are sure the cost after the
1601 // merge is never more than that before the merge.
1605 // Update the GEP in place if possible.
1606 if (Src->getNumOperands() == 2) {
1607 GEP.setOperand(0, Src->getOperand(0));
1608 GEP.setOperand(1, Sum);
1611 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1612 Indices.push_back(Sum);
1613 Indices.append(GEP.op_begin()+2, GEP.op_end());
1614 } else if (isa<Constant>(*GEP.idx_begin()) &&
1615 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1616 Src->getNumOperands() != 1) {
1617 // Otherwise we can do the fold if the first index of the GEP is a zero
1618 Indices.append(Src->op_begin()+1, Src->op_end());
1619 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1622 if (!Indices.empty())
1623 return GEP.isInBounds() && Src->isInBounds()
1624 ? GetElementPtrInst::CreateInBounds(
1625 Src->getSourceElementType(), Src->getOperand(0), Indices,
1627 : GetElementPtrInst::Create(Src->getSourceElementType(),
1628 Src->getOperand(0), Indices,
1632 if (GEP.getNumIndices() == 1) {
1633 unsigned AS = GEP.getPointerAddressSpace();
1634 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1635 DL.getPointerSizeInBits(AS)) {
1636 Type *Ty = GEP.getSourceElementType();
1637 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1639 bool Matched = false;
1642 if (TyAllocSize == 1) {
1643 V = GEP.getOperand(1);
1645 } else if (match(GEP.getOperand(1),
1646 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1647 if (TyAllocSize == 1ULL << C)
1649 } else if (match(GEP.getOperand(1),
1650 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1651 if (TyAllocSize == C)
1656 // Canonicalize (gep i8* X, -(ptrtoint Y))
1657 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1658 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1659 // pointer arithmetic.
1660 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1661 Operator *Index = cast<Operator>(V);
1662 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1663 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1664 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1666 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1669 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1670 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1671 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1678 // We do not handle pointer-vector geps here.
1679 if (GEP.getType()->isVectorTy())
1682 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1683 Value *StrippedPtr = PtrOp->stripPointerCasts();
1684 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1686 if (StrippedPtr != PtrOp) {
1687 bool HasZeroPointerIndex = false;
1688 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1689 HasZeroPointerIndex = C->isZero();
1691 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1692 // into : GEP [10 x i8]* X, i32 0, ...
1694 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1695 // into : GEP i8* X, ...
1697 // This occurs when the program declares an array extern like "int X[];"
1698 if (HasZeroPointerIndex) {
1699 if (ArrayType *CATy =
1700 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1701 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1702 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1703 // -> GEP i8* X, ...
1704 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1705 GetElementPtrInst *Res = GetElementPtrInst::Create(
1706 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1707 Res->setIsInBounds(GEP.isInBounds());
1708 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1710 // Insert Res, and create an addrspacecast.
1712 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1714 // %0 = GEP i8 addrspace(1)* X, ...
1715 // addrspacecast i8 addrspace(1)* %0 to i8*
1716 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1719 if (ArrayType *XATy =
1720 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1721 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1722 if (CATy->getElementType() == XATy->getElementType()) {
1723 // -> GEP [10 x i8]* X, i32 0, ...
1724 // At this point, we know that the cast source type is a pointer
1725 // to an array of the same type as the destination pointer
1726 // array. Because the array type is never stepped over (there
1727 // is a leading zero) we can fold the cast into this GEP.
1728 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1729 GEP.setOperand(0, StrippedPtr);
1730 GEP.setSourceElementType(XATy);
1733 // Cannot replace the base pointer directly because StrippedPtr's
1734 // address space is different. Instead, create a new GEP followed by
1735 // an addrspacecast.
1737 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1740 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1741 // addrspacecast i8 addrspace(1)* %0 to i8*
1742 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1743 Value *NewGEP = GEP.isInBounds()
1744 ? Builder->CreateInBoundsGEP(
1745 nullptr, StrippedPtr, Idx, GEP.getName())
1746 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1748 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1752 } else if (GEP.getNumOperands() == 2) {
1753 // Transform things like:
1754 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1755 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1756 Type *SrcElTy = StrippedPtrTy->getElementType();
1757 Type *ResElTy = GEP.getSourceElementType();
1758 if (SrcElTy->isArrayTy() &&
1759 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1760 DL.getTypeAllocSize(ResElTy)) {
1761 Type *IdxType = DL.getIntPtrType(GEP.getType());
1762 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1765 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1767 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1769 // V and GEP are both pointer types --> BitCast
1770 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1774 // Transform things like:
1775 // %V = mul i64 %N, 4
1776 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1777 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1778 if (ResElTy->isSized() && SrcElTy->isSized()) {
1779 // Check that changing the type amounts to dividing the index by a scale
1781 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1782 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1783 if (ResSize && SrcSize % ResSize == 0) {
1784 Value *Idx = GEP.getOperand(1);
1785 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1786 uint64_t Scale = SrcSize / ResSize;
1788 // Earlier transforms ensure that the index has type IntPtrType, which
1789 // considerably simplifies the logic by eliminating implicit casts.
1790 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1791 "Index not cast to pointer width?");
1794 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1795 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1796 // If the multiplication NewIdx * Scale may overflow then the new
1797 // GEP may not be "inbounds".
1799 GEP.isInBounds() && NSW
1800 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1802 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1805 // The NewGEP must be pointer typed, so must the old one -> BitCast
1806 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1812 // Similarly, transform things like:
1813 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1814 // (where tmp = 8*tmp2) into:
1815 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1816 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1817 // Check that changing to the array element type amounts to dividing the
1818 // index by a scale factor.
1819 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1820 uint64_t ArrayEltSize =
1821 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1822 if (ResSize && ArrayEltSize % ResSize == 0) {
1823 Value *Idx = GEP.getOperand(1);
1824 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1825 uint64_t Scale = ArrayEltSize / ResSize;
1827 // Earlier transforms ensure that the index has type IntPtrType, which
1828 // considerably simplifies the logic by eliminating implicit casts.
1829 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1830 "Index not cast to pointer width?");
1833 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1834 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1835 // If the multiplication NewIdx * Scale may overflow then the new
1836 // GEP may not be "inbounds".
1838 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1841 Value *NewGEP = GEP.isInBounds() && NSW
1842 ? Builder->CreateInBoundsGEP(
1843 SrcElTy, StrippedPtr, Off, GEP.getName())
1844 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1846 // The NewGEP must be pointer typed, so must the old one -> BitCast
1847 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1855 // addrspacecast between types is canonicalized as a bitcast, then an
1856 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1857 // through the addrspacecast.
1858 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1859 // X = bitcast A addrspace(1)* to B addrspace(1)*
1860 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1861 // Z = gep Y, <...constant indices...>
1862 // Into an addrspacecasted GEP of the struct.
1863 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1867 /// See if we can simplify:
1868 /// X = bitcast A* to B*
1869 /// Y = gep X, <...constant indices...>
1870 /// into a gep of the original struct. This is important for SROA and alias
1871 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1872 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1873 Value *Operand = BCI->getOperand(0);
1874 PointerType *OpType = cast<PointerType>(Operand->getType());
1875 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1876 APInt Offset(OffsetBits, 0);
1877 if (!isa<BitCastInst>(Operand) &&
1878 GEP.accumulateConstantOffset(DL, Offset)) {
1880 // If this GEP instruction doesn't move the pointer, just replace the GEP
1881 // with a bitcast of the real input to the dest type.
1883 // If the bitcast is of an allocation, and the allocation will be
1884 // converted to match the type of the cast, don't touch this.
1885 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
1886 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1887 if (Instruction *I = visitBitCast(*BCI)) {
1890 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1891 replaceInstUsesWith(*BCI, I);
1897 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1898 return new AddrSpaceCastInst(Operand, GEP.getType());
1899 return new BitCastInst(Operand, GEP.getType());
1902 // Otherwise, if the offset is non-zero, we need to find out if there is a
1903 // field at Offset in 'A's type. If so, we can pull the cast through the
1905 SmallVector<Value*, 8> NewIndices;
1906 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1909 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1910 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1912 if (NGEP->getType() == GEP.getType())
1913 return replaceInstUsesWith(GEP, NGEP);
1914 NGEP->takeName(&GEP);
1916 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1917 return new AddrSpaceCastInst(NGEP, GEP.getType());
1918 return new BitCastInst(NGEP, GEP.getType());
1923 if (!GEP.isInBounds()) {
1925 DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1926 APInt BasePtrOffset(PtrWidth, 0);
1927 Value *UnderlyingPtrOp =
1928 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1930 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1931 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1932 BasePtrOffset.isNonNegative()) {
1933 APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1934 if (BasePtrOffset.ule(AllocSize)) {
1935 return GetElementPtrInst::CreateInBounds(
1936 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1945 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1947 if (isa<ConstantPointerNull>(V))
1949 if (auto *LI = dyn_cast<LoadInst>(V))
1950 return isa<GlobalVariable>(LI->getPointerOperand());
1951 // Two distinct allocations will never be equal.
1952 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1953 // through bitcasts of V can cause
1954 // the result statement below to be true, even when AI and V (ex:
1955 // i8* ->i32* ->i8* of AI) are the same allocations.
1956 return isAllocLikeFn(V, TLI) && V != AI;
1959 static bool isAllocSiteRemovable(Instruction *AI,
1960 SmallVectorImpl<WeakTrackingVH> &Users,
1961 const TargetLibraryInfo *TLI) {
1962 SmallVector<Instruction*, 4> Worklist;
1963 Worklist.push_back(AI);
1966 Instruction *PI = Worklist.pop_back_val();
1967 for (User *U : PI->users()) {
1968 Instruction *I = cast<Instruction>(U);
1969 switch (I->getOpcode()) {
1971 // Give up the moment we see something we can't handle.
1974 case Instruction::AddrSpaceCast:
1975 case Instruction::BitCast:
1976 case Instruction::GetElementPtr:
1977 Users.emplace_back(I);
1978 Worklist.push_back(I);
1981 case Instruction::ICmp: {
1982 ICmpInst *ICI = cast<ICmpInst>(I);
1983 // We can fold eq/ne comparisons with null to false/true, respectively.
1984 // We also fold comparisons in some conditions provided the alloc has
1985 // not escaped (see isNeverEqualToUnescapedAlloc).
1986 if (!ICI->isEquality())
1988 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
1989 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
1991 Users.emplace_back(I);
1995 case Instruction::Call:
1996 // Ignore no-op and store intrinsics.
1997 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1998 switch (II->getIntrinsicID()) {
2002 case Intrinsic::memmove:
2003 case Intrinsic::memcpy:
2004 case Intrinsic::memset: {
2005 MemIntrinsic *MI = cast<MemIntrinsic>(II);
2006 if (MI->isVolatile() || MI->getRawDest() != PI)
2010 case Intrinsic::dbg_declare:
2011 case Intrinsic::dbg_value:
2012 case Intrinsic::invariant_start:
2013 case Intrinsic::invariant_end:
2014 case Intrinsic::lifetime_start:
2015 case Intrinsic::lifetime_end:
2016 case Intrinsic::objectsize:
2017 Users.emplace_back(I);
2022 if (isFreeCall(I, TLI)) {
2023 Users.emplace_back(I);
2028 case Instruction::Store: {
2029 StoreInst *SI = cast<StoreInst>(I);
2030 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2032 Users.emplace_back(I);
2036 llvm_unreachable("missing a return?");
2038 } while (!Worklist.empty());
2042 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2043 // If we have a malloc call which is only used in any amount of comparisons
2044 // to null and free calls, delete the calls and replace the comparisons with
2045 // true or false as appropriate.
2046 SmallVector<WeakTrackingVH, 64> Users;
2047 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2048 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2049 // Lowering all @llvm.objectsize calls first because they may
2050 // use a bitcast/GEP of the alloca we are removing.
2054 Instruction *I = cast<Instruction>(&*Users[i]);
2056 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2057 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2058 ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2059 /*MustSucceed=*/true);
2060 replaceInstUsesWith(*I, Result);
2061 eraseInstFromFunction(*I);
2062 Users[i] = nullptr; // Skip examining in the next loop.
2066 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2070 Instruction *I = cast<Instruction>(&*Users[i]);
2072 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2073 replaceInstUsesWith(*C,
2074 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2075 C->isFalseWhenEqual()));
2076 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) ||
2077 isa<AddrSpaceCastInst>(I)) {
2078 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2080 eraseInstFromFunction(*I);
2083 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2084 // Replace invoke with a NOP intrinsic to maintain the original CFG
2085 Module *M = II->getModule();
2086 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2087 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2088 None, "", II->getParent());
2090 return eraseInstFromFunction(MI);
2095 /// \brief Move the call to free before a NULL test.
2097 /// Check if this free is accessed after its argument has been test
2098 /// against NULL (property 0).
2099 /// If yes, it is legal to move this call in its predecessor block.
2101 /// The move is performed only if the block containing the call to free
2102 /// will be removed, i.e.:
2103 /// 1. it has only one predecessor P, and P has two successors
2104 /// 2. it contains the call and an unconditional branch
2105 /// 3. its successor is the same as its predecessor's successor
2107 /// The profitability is out-of concern here and this function should
2108 /// be called only if the caller knows this transformation would be
2109 /// profitable (e.g., for code size).
2110 static Instruction *
2111 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2112 Value *Op = FI.getArgOperand(0);
2113 BasicBlock *FreeInstrBB = FI.getParent();
2114 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2116 // Validate part of constraint #1: Only one predecessor
2117 // FIXME: We can extend the number of predecessor, but in that case, we
2118 // would duplicate the call to free in each predecessor and it may
2119 // not be profitable even for code size.
2123 // Validate constraint #2: Does this block contains only the call to
2124 // free and an unconditional branch?
2125 // FIXME: We could check if we can speculate everything in the
2126 // predecessor block
2127 if (FreeInstrBB->size() != 2)
2130 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2133 // Validate the rest of constraint #1 by matching on the pred branch.
2134 TerminatorInst *TI = PredBB->getTerminator();
2135 BasicBlock *TrueBB, *FalseBB;
2136 ICmpInst::Predicate Pred;
2137 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2139 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2142 // Validate constraint #3: Ensure the null case just falls through.
2143 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2145 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2146 "Broken CFG: missing edge from predecessor to successor");
2153 Instruction *InstCombiner::visitFree(CallInst &FI) {
2154 Value *Op = FI.getArgOperand(0);
2156 // free undef -> unreachable.
2157 if (isa<UndefValue>(Op)) {
2158 // Insert a new store to null because we cannot modify the CFG here.
2159 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2160 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2161 return eraseInstFromFunction(FI);
2164 // If we have 'free null' delete the instruction. This can happen in stl code
2165 // when lots of inlining happens.
2166 if (isa<ConstantPointerNull>(Op))
2167 return eraseInstFromFunction(FI);
2169 // If we optimize for code size, try to move the call to free before the null
2170 // test so that simplify cfg can remove the empty block and dead code
2171 // elimination the branch. I.e., helps to turn something like:
2172 // if (foo) free(foo);
2176 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2182 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2183 if (RI.getNumOperands() == 0) // ret void
2186 Value *ResultOp = RI.getOperand(0);
2187 Type *VTy = ResultOp->getType();
2188 if (!VTy->isIntegerTy())
2191 // There might be assume intrinsics dominating this return that completely
2192 // determine the value. If so, constant fold it.
2193 KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2194 if (Known.isConstant())
2195 RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant()));
2200 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2201 // Change br (not X), label True, label False to: br X, label False, True
2203 BasicBlock *TrueDest;
2204 BasicBlock *FalseDest;
2205 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2206 !isa<Constant>(X)) {
2207 // Swap Destinations and condition...
2209 BI.swapSuccessors();
2213 // If the condition is irrelevant, remove the use so that other
2214 // transforms on the condition become more effective.
2215 if (BI.isConditional() &&
2216 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2217 !isa<UndefValue>(BI.getCondition())) {
2218 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2222 // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq.
2223 CmpInst::Predicate Pred;
2224 if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest,
2226 !isCanonicalPredicate(Pred)) {
2227 // Swap destinations and condition.
2228 CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2229 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2230 BI.swapSuccessors();
2238 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2239 Value *Cond = SI.getCondition();
2241 ConstantInt *AddRHS;
2242 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2243 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2244 for (auto Case : SI.cases()) {
2245 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2246 assert(isa<ConstantInt>(NewCase) &&
2247 "Result of expression should be constant");
2248 Case.setValue(cast<ConstantInt>(NewCase));
2250 SI.setCondition(Op0);
2254 KnownBits Known = computeKnownBits(Cond, 0, &SI);
2255 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
2256 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
2258 // Compute the number of leading bits we can ignore.
2259 // TODO: A better way to determine this would use ComputeNumSignBits().
2260 for (auto &C : SI.cases()) {
2261 LeadingKnownZeros = std::min(
2262 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2263 LeadingKnownOnes = std::min(
2264 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2267 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
2269 // Shrink the condition operand if the new type is smaller than the old type.
2270 // This may produce a non-standard type for the switch, but that's ok because
2271 // the backend should extend back to a legal type for the target.
2272 if (NewWidth > 0 && NewWidth < Known.getBitWidth()) {
2273 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2274 Builder->SetInsertPoint(&SI);
2275 Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
2276 SI.setCondition(NewCond);
2278 for (auto Case : SI.cases()) {
2279 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2280 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2288 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2289 Value *Agg = EV.getAggregateOperand();
2291 if (!EV.hasIndices())
2292 return replaceInstUsesWith(EV, Agg);
2294 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
2295 SQ.getWithInstruction(&EV)))
2296 return replaceInstUsesWith(EV, V);
2298 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2299 // We're extracting from an insertvalue instruction, compare the indices
2300 const unsigned *exti, *exte, *insi, *inse;
2301 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2302 exte = EV.idx_end(), inse = IV->idx_end();
2303 exti != exte && insi != inse;
2306 // The insert and extract both reference distinctly different elements.
2307 // This means the extract is not influenced by the insert, and we can
2308 // replace the aggregate operand of the extract with the aggregate
2309 // operand of the insert. i.e., replace
2310 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2311 // %E = extractvalue { i32, { i32 } } %I, 0
2313 // %E = extractvalue { i32, { i32 } } %A, 0
2314 return ExtractValueInst::Create(IV->getAggregateOperand(),
2317 if (exti == exte && insi == inse)
2318 // Both iterators are at the end: Index lists are identical. Replace
2319 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2320 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2322 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2324 // The extract list is a prefix of the insert list. i.e. replace
2325 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2326 // %E = extractvalue { i32, { i32 } } %I, 1
2328 // %X = extractvalue { i32, { i32 } } %A, 1
2329 // %E = insertvalue { i32 } %X, i32 42, 0
2330 // by switching the order of the insert and extract (though the
2331 // insertvalue should be left in, since it may have other uses).
2332 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2334 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2335 makeArrayRef(insi, inse));
2338 // The insert list is a prefix of the extract list
2339 // We can simply remove the common indices from the extract and make it
2340 // operate on the inserted value instead of the insertvalue result.
2342 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2343 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2345 // %E extractvalue { i32 } { i32 42 }, 0
2346 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2347 makeArrayRef(exti, exte));
2349 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2350 // We're extracting from an intrinsic, see if we're the only user, which
2351 // allows us to simplify multiple result intrinsics to simpler things that
2352 // just get one value.
2353 if (II->hasOneUse()) {
2354 // Check if we're grabbing the overflow bit or the result of a 'with
2355 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2356 // and replace it with a traditional binary instruction.
2357 switch (II->getIntrinsicID()) {
2358 case Intrinsic::uadd_with_overflow:
2359 case Intrinsic::sadd_with_overflow:
2360 if (*EV.idx_begin() == 0) { // Normal result.
2361 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2362 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2363 eraseInstFromFunction(*II);
2364 return BinaryOperator::CreateAdd(LHS, RHS);
2367 // If the normal result of the add is dead, and the RHS is a constant,
2368 // we can transform this into a range comparison.
2369 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2370 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2371 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2372 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2373 ConstantExpr::getNot(CI));
2375 case Intrinsic::usub_with_overflow:
2376 case Intrinsic::ssub_with_overflow:
2377 if (*EV.idx_begin() == 0) { // Normal result.
2378 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2379 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2380 eraseInstFromFunction(*II);
2381 return BinaryOperator::CreateSub(LHS, RHS);
2384 case Intrinsic::umul_with_overflow:
2385 case Intrinsic::smul_with_overflow:
2386 if (*EV.idx_begin() == 0) { // Normal result.
2387 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2388 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2389 eraseInstFromFunction(*II);
2390 return BinaryOperator::CreateMul(LHS, RHS);
2398 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2399 // If the (non-volatile) load only has one use, we can rewrite this to a
2400 // load from a GEP. This reduces the size of the load. If a load is used
2401 // only by extractvalue instructions then this either must have been
2402 // optimized before, or it is a struct with padding, in which case we
2403 // don't want to do the transformation as it loses padding knowledge.
2404 if (L->isSimple() && L->hasOneUse()) {
2405 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2406 SmallVector<Value*, 4> Indices;
2407 // Prefix an i32 0 since we need the first element.
2408 Indices.push_back(Builder->getInt32(0));
2409 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2411 Indices.push_back(Builder->getInt32(*I));
2413 // We need to insert these at the location of the old load, not at that of
2414 // the extractvalue.
2415 Builder->SetInsertPoint(L);
2416 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2417 L->getPointerOperand(), Indices);
2418 // Returning the load directly will cause the main loop to insert it in
2419 // the wrong spot, so use replaceInstUsesWith().
2420 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2422 // We could simplify extracts from other values. Note that nested extracts may
2423 // already be simplified implicitly by the above: extract (extract (insert) )
2424 // will be translated into extract ( insert ( extract ) ) first and then just
2425 // the value inserted, if appropriate. Similarly for extracts from single-use
2426 // loads: extract (extract (load)) will be translated to extract (load (gep))
2427 // and if again single-use then via load (gep (gep)) to load (gep).
2428 // However, double extracts from e.g. function arguments or return values
2429 // aren't handled yet.
2433 /// Return 'true' if the given typeinfo will match anything.
2434 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2435 switch (Personality) {
2436 case EHPersonality::GNU_C:
2437 case EHPersonality::GNU_C_SjLj:
2438 case EHPersonality::Rust:
2439 // The GCC C EH and Rust personality only exists to support cleanups, so
2440 // it's not clear what the semantics of catch clauses are.
2442 case EHPersonality::Unknown:
2444 case EHPersonality::GNU_Ada:
2445 // While __gnat_all_others_value will match any Ada exception, it doesn't
2446 // match foreign exceptions (or didn't, before gcc-4.7).
2448 case EHPersonality::GNU_CXX:
2449 case EHPersonality::GNU_CXX_SjLj:
2450 case EHPersonality::GNU_ObjC:
2451 case EHPersonality::MSVC_X86SEH:
2452 case EHPersonality::MSVC_Win64SEH:
2453 case EHPersonality::MSVC_CXX:
2454 case EHPersonality::CoreCLR:
2455 return TypeInfo->isNullValue();
2457 llvm_unreachable("invalid enum");
2460 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2462 cast<ArrayType>(LHS->getType())->getNumElements()
2464 cast<ArrayType>(RHS->getType())->getNumElements();
2467 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2468 // The logic here should be correct for any real-world personality function.
2469 // However if that turns out not to be true, the offending logic can always
2470 // be conditioned on the personality function, like the catch-all logic is.
2471 EHPersonality Personality =
2472 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2474 // Simplify the list of clauses, eg by removing repeated catch clauses
2475 // (these are often created by inlining).
2476 bool MakeNewInstruction = false; // If true, recreate using the following:
2477 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2478 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2480 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2481 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2482 bool isLastClause = i + 1 == e;
2483 if (LI.isCatch(i)) {
2485 Constant *CatchClause = LI.getClause(i);
2486 Constant *TypeInfo = CatchClause->stripPointerCasts();
2488 // If we already saw this clause, there is no point in having a second
2490 if (AlreadyCaught.insert(TypeInfo).second) {
2491 // This catch clause was not already seen.
2492 NewClauses.push_back(CatchClause);
2494 // Repeated catch clause - drop the redundant copy.
2495 MakeNewInstruction = true;
2498 // If this is a catch-all then there is no point in keeping any following
2499 // clauses or marking the landingpad as having a cleanup.
2500 if (isCatchAll(Personality, TypeInfo)) {
2502 MakeNewInstruction = true;
2503 CleanupFlag = false;
2507 // A filter clause. If any of the filter elements were already caught
2508 // then they can be dropped from the filter. It is tempting to try to
2509 // exploit the filter further by saying that any typeinfo that does not
2510 // occur in the filter can't be caught later (and thus can be dropped).
2511 // However this would be wrong, since typeinfos can match without being
2512 // equal (for example if one represents a C++ class, and the other some
2513 // class derived from it).
2514 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2515 Constant *FilterClause = LI.getClause(i);
2516 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2517 unsigned NumTypeInfos = FilterType->getNumElements();
2519 // An empty filter catches everything, so there is no point in keeping any
2520 // following clauses or marking the landingpad as having a cleanup. By
2521 // dealing with this case here the following code is made a bit simpler.
2522 if (!NumTypeInfos) {
2523 NewClauses.push_back(FilterClause);
2525 MakeNewInstruction = true;
2526 CleanupFlag = false;
2530 bool MakeNewFilter = false; // If true, make a new filter.
2531 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2532 if (isa<ConstantAggregateZero>(FilterClause)) {
2533 // Not an empty filter - it contains at least one null typeinfo.
2534 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2535 Constant *TypeInfo =
2536 Constant::getNullValue(FilterType->getElementType());
2537 // If this typeinfo is a catch-all then the filter can never match.
2538 if (isCatchAll(Personality, TypeInfo)) {
2539 // Throw the filter away.
2540 MakeNewInstruction = true;
2544 // There is no point in having multiple copies of this typeinfo, so
2545 // discard all but the first copy if there is more than one.
2546 NewFilterElts.push_back(TypeInfo);
2547 if (NumTypeInfos > 1)
2548 MakeNewFilter = true;
2550 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2551 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2552 NewFilterElts.reserve(NumTypeInfos);
2554 // Remove any filter elements that were already caught or that already
2555 // occurred in the filter. While there, see if any of the elements are
2556 // catch-alls. If so, the filter can be discarded.
2557 bool SawCatchAll = false;
2558 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2559 Constant *Elt = Filter->getOperand(j);
2560 Constant *TypeInfo = Elt->stripPointerCasts();
2561 if (isCatchAll(Personality, TypeInfo)) {
2562 // This element is a catch-all. Bail out, noting this fact.
2567 // Even if we've seen a type in a catch clause, we don't want to
2568 // remove it from the filter. An unexpected type handler may be
2569 // set up for a call site which throws an exception of the same
2570 // type caught. In order for the exception thrown by the unexpected
2571 // handler to propagate correctly, the filter must be correctly
2572 // described for the call site.
2576 // void unexpected() { throw 1;}
2577 // void foo() throw (int) {
2578 // std::set_unexpected(unexpected);
2581 // } catch (int i) {}
2584 // There is no point in having multiple copies of the same typeinfo in
2585 // a filter, so only add it if we didn't already.
2586 if (SeenInFilter.insert(TypeInfo).second)
2587 NewFilterElts.push_back(cast<Constant>(Elt));
2589 // A filter containing a catch-all cannot match anything by definition.
2591 // Throw the filter away.
2592 MakeNewInstruction = true;
2596 // If we dropped something from the filter, make a new one.
2597 if (NewFilterElts.size() < NumTypeInfos)
2598 MakeNewFilter = true;
2600 if (MakeNewFilter) {
2601 FilterType = ArrayType::get(FilterType->getElementType(),
2602 NewFilterElts.size());
2603 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2604 MakeNewInstruction = true;
2607 NewClauses.push_back(FilterClause);
2609 // If the new filter is empty then it will catch everything so there is
2610 // no point in keeping any following clauses or marking the landingpad
2611 // as having a cleanup. The case of the original filter being empty was
2612 // already handled above.
2613 if (MakeNewFilter && !NewFilterElts.size()) {
2614 assert(MakeNewInstruction && "New filter but not a new instruction!");
2615 CleanupFlag = false;
2621 // If several filters occur in a row then reorder them so that the shortest
2622 // filters come first (those with the smallest number of elements). This is
2623 // advantageous because shorter filters are more likely to match, speeding up
2624 // unwinding, but mostly because it increases the effectiveness of the other
2625 // filter optimizations below.
2626 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2628 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2629 for (j = i; j != e; ++j)
2630 if (!isa<ArrayType>(NewClauses[j]->getType()))
2633 // Check whether the filters are already sorted by length. We need to know
2634 // if sorting them is actually going to do anything so that we only make a
2635 // new landingpad instruction if it does.
2636 for (unsigned k = i; k + 1 < j; ++k)
2637 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2638 // Not sorted, so sort the filters now. Doing an unstable sort would be
2639 // correct too but reordering filters pointlessly might confuse users.
2640 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2642 MakeNewInstruction = true;
2646 // Look for the next batch of filters.
2650 // If typeinfos matched if and only if equal, then the elements of a filter L
2651 // that occurs later than a filter F could be replaced by the intersection of
2652 // the elements of F and L. In reality two typeinfos can match without being
2653 // equal (for example if one represents a C++ class, and the other some class
2654 // derived from it) so it would be wrong to perform this transform in general.
2655 // However the transform is correct and useful if F is a subset of L. In that
2656 // case L can be replaced by F, and thus removed altogether since repeating a
2657 // filter is pointless. So here we look at all pairs of filters F and L where
2658 // L follows F in the list of clauses, and remove L if every element of F is
2659 // an element of L. This can occur when inlining C++ functions with exception
2661 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2662 // Examine each filter in turn.
2663 Value *Filter = NewClauses[i];
2664 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2666 // Not a filter - skip it.
2668 unsigned FElts = FTy->getNumElements();
2669 // Examine each filter following this one. Doing this backwards means that
2670 // we don't have to worry about filters disappearing under us when removed.
2671 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2672 Value *LFilter = NewClauses[j];
2673 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2675 // Not a filter - skip it.
2677 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2678 // an element of LFilter, then discard LFilter.
2679 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2680 // If Filter is empty then it is a subset of LFilter.
2683 NewClauses.erase(J);
2684 MakeNewInstruction = true;
2685 // Move on to the next filter.
2688 unsigned LElts = LTy->getNumElements();
2689 // If Filter is longer than LFilter then it cannot be a subset of it.
2691 // Move on to the next filter.
2693 // At this point we know that LFilter has at least one element.
2694 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2695 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2696 // already know that Filter is not longer than LFilter).
2697 if (isa<ConstantAggregateZero>(Filter)) {
2698 assert(FElts <= LElts && "Should have handled this case earlier!");
2700 NewClauses.erase(J);
2701 MakeNewInstruction = true;
2703 // Move on to the next filter.
2706 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2707 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2708 // Since Filter is non-empty and contains only zeros, it is a subset of
2709 // LFilter iff LFilter contains a zero.
2710 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2711 for (unsigned l = 0; l != LElts; ++l)
2712 if (LArray->getOperand(l)->isNullValue()) {
2713 // LFilter contains a zero - discard it.
2714 NewClauses.erase(J);
2715 MakeNewInstruction = true;
2718 // Move on to the next filter.
2721 // At this point we know that both filters are ConstantArrays. Loop over
2722 // operands to see whether every element of Filter is also an element of
2723 // LFilter. Since filters tend to be short this is probably faster than
2724 // using a method that scales nicely.
2725 ConstantArray *FArray = cast<ConstantArray>(Filter);
2726 bool AllFound = true;
2727 for (unsigned f = 0; f != FElts; ++f) {
2728 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2730 for (unsigned l = 0; l != LElts; ++l) {
2731 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2732 if (LTypeInfo == FTypeInfo) {
2742 NewClauses.erase(J);
2743 MakeNewInstruction = true;
2745 // Move on to the next filter.
2749 // If we changed any of the clauses, replace the old landingpad instruction
2751 if (MakeNewInstruction) {
2752 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2754 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2755 NLI->addClause(NewClauses[i]);
2756 // A landing pad with no clauses must have the cleanup flag set. It is
2757 // theoretically possible, though highly unlikely, that we eliminated all
2758 // clauses. If so, force the cleanup flag to true.
2759 if (NewClauses.empty())
2761 NLI->setCleanup(CleanupFlag);
2765 // Even if none of the clauses changed, we may nonetheless have understood
2766 // that the cleanup flag is pointless. Clear it if so.
2767 if (LI.isCleanup() != CleanupFlag) {
2768 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2769 LI.setCleanup(CleanupFlag);
2776 /// Try to move the specified instruction from its current block into the
2777 /// beginning of DestBlock, which can only happen if it's safe to move the
2778 /// instruction past all of the instructions between it and the end of its
2780 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2781 assert(I->hasOneUse() && "Invariants didn't hold!");
2783 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2784 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2785 isa<TerminatorInst>(I))
2788 // Do not sink alloca instructions out of the entry block.
2789 if (isa<AllocaInst>(I) && I->getParent() ==
2790 &DestBlock->getParent()->getEntryBlock())
2793 // Do not sink into catchswitch blocks.
2794 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2797 // Do not sink convergent call instructions.
2798 if (auto *CI = dyn_cast<CallInst>(I)) {
2799 if (CI->isConvergent())
2802 // We can only sink load instructions if there is nothing between the load and
2803 // the end of block that could change the value.
2804 if (I->mayReadFromMemory()) {
2805 for (BasicBlock::iterator Scan = I->getIterator(),
2806 E = I->getParent()->end();
2808 if (Scan->mayWriteToMemory())
2812 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2813 I->moveBefore(&*InsertPos);
2818 bool InstCombiner::run() {
2819 while (!Worklist.isEmpty()) {
2820 Instruction *I = Worklist.RemoveOne();
2821 if (I == nullptr) continue; // skip null values.
2823 // Check to see if we can DCE the instruction.
2824 if (isInstructionTriviallyDead(I, &TLI)) {
2825 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2826 eraseInstFromFunction(*I);
2828 MadeIRChange = true;
2832 // Instruction isn't dead, see if we can constant propagate it.
2833 if (!I->use_empty() &&
2834 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2835 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2836 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2838 // Add operands to the worklist.
2839 replaceInstUsesWith(*I, C);
2841 if (isInstructionTriviallyDead(I, &TLI))
2842 eraseInstFromFunction(*I);
2843 MadeIRChange = true;
2848 // In general, it is possible for computeKnownBits to determine all bits in
2849 // a value even when the operands are not all constants.
2850 Type *Ty = I->getType();
2851 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2852 KnownBits Known = computeKnownBits(I, /*Depth*/0, I);
2853 if (Known.isConstant()) {
2854 Constant *C = ConstantInt::get(Ty, Known.getConstant());
2855 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2856 " from: " << *I << '\n');
2858 // Add operands to the worklist.
2859 replaceInstUsesWith(*I, C);
2861 if (isInstructionTriviallyDead(I, &TLI))
2862 eraseInstFromFunction(*I);
2863 MadeIRChange = true;
2868 // See if we can trivially sink this instruction to a successor basic block.
2869 if (I->hasOneUse()) {
2870 BasicBlock *BB = I->getParent();
2871 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2872 BasicBlock *UserParent;
2874 // Get the block the use occurs in.
2875 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2876 UserParent = PN->getIncomingBlock(*I->use_begin());
2878 UserParent = UserInst->getParent();
2880 if (UserParent != BB) {
2881 bool UserIsSuccessor = false;
2882 // See if the user is one of our successors.
2883 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2884 if (*SI == UserParent) {
2885 UserIsSuccessor = true;
2889 // If the user is one of our immediate successors, and if that successor
2890 // only has us as a predecessors (we'd have to split the critical edge
2891 // otherwise), we can keep going.
2892 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
2893 // Okay, the CFG is simple enough, try to sink this instruction.
2894 if (TryToSinkInstruction(I, UserParent)) {
2895 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
2896 MadeIRChange = true;
2897 // We'll add uses of the sunk instruction below, but since sinking
2898 // can expose opportunities for it's *operands* add them to the
2900 for (Use &U : I->operands())
2901 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2908 // Now that we have an instruction, try combining it to simplify it.
2909 Builder->SetInsertPoint(I);
2910 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2915 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2916 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2918 if (Instruction *Result = visit(*I)) {
2920 // Should we replace the old instruction with a new one?
2922 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2923 << " New = " << *Result << '\n');
2925 if (I->getDebugLoc())
2926 Result->setDebugLoc(I->getDebugLoc());
2927 // Everything uses the new instruction now.
2928 I->replaceAllUsesWith(Result);
2930 // Move the name to the new instruction first.
2931 Result->takeName(I);
2933 // Push the new instruction and any users onto the worklist.
2934 Worklist.AddUsersToWorkList(*Result);
2935 Worklist.Add(Result);
2937 // Insert the new instruction into the basic block...
2938 BasicBlock *InstParent = I->getParent();
2939 BasicBlock::iterator InsertPos = I->getIterator();
2941 // If we replace a PHI with something that isn't a PHI, fix up the
2943 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2944 InsertPos = InstParent->getFirstInsertionPt();
2946 InstParent->getInstList().insert(InsertPos, Result);
2948 eraseInstFromFunction(*I);
2950 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2951 << " New = " << *I << '\n');
2953 // If the instruction was modified, it's possible that it is now dead.
2954 // if so, remove it.
2955 if (isInstructionTriviallyDead(I, &TLI)) {
2956 eraseInstFromFunction(*I);
2958 Worklist.AddUsersToWorkList(*I);
2962 MadeIRChange = true;
2967 return MadeIRChange;
2970 /// Walk the function in depth-first order, adding all reachable code to the
2973 /// This has a couple of tricks to make the code faster and more powerful. In
2974 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2975 /// them to the worklist (this significantly speeds up instcombine on code where
2976 /// many instructions are dead or constant). Additionally, if we find a branch
2977 /// whose condition is a known constant, we only visit the reachable successors.
2979 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2980 SmallPtrSetImpl<BasicBlock *> &Visited,
2981 InstCombineWorklist &ICWorklist,
2982 const TargetLibraryInfo *TLI) {
2983 bool MadeIRChange = false;
2984 SmallVector<BasicBlock*, 256> Worklist;
2985 Worklist.push_back(BB);
2987 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2988 DenseMap<Constant *, Constant *> FoldedConstants;
2991 BB = Worklist.pop_back_val();
2993 // We have now visited this block! If we've already been here, ignore it.
2994 if (!Visited.insert(BB).second)
2997 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2998 Instruction *Inst = &*BBI++;
3000 // DCE instruction if trivially dead.
3001 if (isInstructionTriviallyDead(Inst, TLI)) {
3003 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3004 Inst->eraseFromParent();
3008 // ConstantProp instruction if trivially constant.
3009 if (!Inst->use_empty() &&
3010 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3011 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3012 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3014 Inst->replaceAllUsesWith(C);
3016 if (isInstructionTriviallyDead(Inst, TLI))
3017 Inst->eraseFromParent();
3021 // See if we can constant fold its operands.
3022 for (Use &U : Inst->operands()) {
3023 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3026 auto *C = cast<Constant>(U);
3027 Constant *&FoldRes = FoldedConstants[C];
3029 FoldRes = ConstantFoldConstant(C, DL, TLI);
3034 DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3035 << "\n Old = " << *C
3036 << "\n New = " << *FoldRes << '\n');
3038 MadeIRChange = true;
3042 // Skip processing debug intrinsics in InstCombine. Processing these call instructions
3043 // consumes non-trivial amount of time and provides no value for the optimization.
3044 if (!isa<DbgInfoIntrinsic>(Inst))
3045 InstrsForInstCombineWorklist.push_back(Inst);
3048 // Recursively visit successors. If this is a branch or switch on a
3049 // constant, only visit the reachable successor.
3050 TerminatorInst *TI = BB->getTerminator();
3051 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3052 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3053 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3054 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3055 Worklist.push_back(ReachableBB);
3058 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3059 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3060 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3065 for (BasicBlock *SuccBB : TI->successors())
3066 Worklist.push_back(SuccBB);
3067 } while (!Worklist.empty());
3069 // Once we've found all of the instructions to add to instcombine's worklist,
3070 // add them in reverse order. This way instcombine will visit from the top
3071 // of the function down. This jives well with the way that it adds all uses
3072 // of instructions to the worklist after doing a transformation, thus avoiding
3073 // some N^2 behavior in pathological cases.
3074 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3076 return MadeIRChange;
3079 /// \brief Populate the IC worklist from a function, and prune any dead basic
3080 /// blocks discovered in the process.
3082 /// This also does basic constant propagation and other forward fixing to make
3083 /// the combiner itself run much faster.
3084 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3085 TargetLibraryInfo *TLI,
3086 InstCombineWorklist &ICWorklist) {
3087 bool MadeIRChange = false;
3089 // Do a depth-first traversal of the function, populate the worklist with
3090 // the reachable instructions. Ignore blocks that are not reachable. Keep
3091 // track of which blocks we visit.
3092 SmallPtrSet<BasicBlock *, 32> Visited;
3094 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3096 // Do a quick scan over the function. If we find any blocks that are
3097 // unreachable, remove any instructions inside of them. This prevents
3098 // the instcombine code from having to deal with some bad special cases.
3099 for (BasicBlock &BB : F) {
3100 if (Visited.count(&BB))
3103 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3104 MadeIRChange |= NumDeadInstInBB > 0;
3105 NumDeadInst += NumDeadInstInBB;
3108 return MadeIRChange;
3112 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3113 AliasAnalysis *AA, AssumptionCache &AC,
3114 TargetLibraryInfo &TLI, DominatorTree &DT,
3115 bool ExpensiveCombines = true,
3116 LoopInfo *LI = nullptr) {
3117 auto &DL = F.getParent()->getDataLayout();
3118 ExpensiveCombines |= EnableExpensiveCombines;
3120 /// Builder - This is an IRBuilder that automatically inserts new
3121 /// instructions into the worklist when they are created.
3122 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3123 F.getContext(), TargetFolder(DL),
3124 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3127 using namespace llvm::PatternMatch;
3128 if (match(I, m_Intrinsic<Intrinsic::assume>()))
3129 AC.registerAssumption(cast<CallInst>(I));
3132 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3134 bool MadeIRChange = LowerDbgDeclare(F);
3136 // Iterate while there is work to do.
3140 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3141 << F.getName() << "\n");
3143 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3145 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
3146 AA, AC, TLI, DT, DL, LI);
3147 IC.MaxArraySizeForCombine = MaxArraySize;
3153 return MadeIRChange || Iteration > 1;
3156 PreservedAnalyses InstCombinePass::run(Function &F,
3157 FunctionAnalysisManager &AM) {
3158 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3159 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3160 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3162 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3164 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3165 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3166 ExpensiveCombines, LI))
3167 // No changes, all analyses are preserved.
3168 return PreservedAnalyses::all();
3170 // Mark all the analyses that instcombine updates as preserved.
3171 PreservedAnalyses PA;
3172 PA.preserveSet<CFGAnalyses>();
3173 PA.preserve<AAManager>();
3174 PA.preserve<GlobalsAA>();
3178 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3179 AU.setPreservesCFG();
3180 AU.addRequired<AAResultsWrapperPass>();
3181 AU.addRequired<AssumptionCacheTracker>();
3182 AU.addRequired<TargetLibraryInfoWrapperPass>();
3183 AU.addRequired<DominatorTreeWrapperPass>();
3184 AU.addPreserved<DominatorTreeWrapperPass>();
3185 AU.addPreserved<AAResultsWrapperPass>();
3186 AU.addPreserved<BasicAAWrapperPass>();
3187 AU.addPreserved<GlobalsAAWrapperPass>();
3190 bool InstructionCombiningPass::runOnFunction(Function &F) {
3191 if (skipFunction(F))
3194 // Required analyses.
3195 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3196 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3197 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3198 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3200 // Optional analyses.
3201 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3202 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3204 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3205 ExpensiveCombines, LI);
3208 char InstructionCombiningPass::ID = 0;
3209 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3210 "Combine redundant instructions", false, false)
3211 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3212 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3213 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3214 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3215 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3216 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3217 "Combine redundant instructions", false, false)
3219 // Initialization Routines
3220 void llvm::initializeInstCombine(PassRegistry &Registry) {
3221 initializeInstructionCombiningPassPass(Registry);
3224 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3225 initializeInstructionCombiningPassPass(*unwrap(R));
3228 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3229 return new InstructionCombiningPass(ExpensiveCombines);