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 "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "InstCombineInternal.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/AssumptionCache.h"
44 #include "llvm/Analysis/BasicAliasAnalysis.h"
45 #include "llvm/Analysis/CFG.h"
46 #include "llvm/Analysis/ConstantFolding.h"
47 #include "llvm/Analysis/EHPersonalities.h"
48 #include "llvm/Analysis/GlobalsModRef.h"
49 #include "llvm/Analysis/InstructionSimplify.h"
50 #include "llvm/Analysis/LoopInfo.h"
51 #include "llvm/Analysis/MemoryBuiltins.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/GetElementPtrTypeIterator.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/PatternMatch.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/raw_ostream.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, DL)) {
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, DL)) {
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, DL)) {
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, DL)) {
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 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
502 const DataLayout &DL, BinaryOperator &I,
503 Instruction::BinaryOps InnerOpcode, Value *A,
504 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, DL);
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, DL);
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, DL, 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))
620 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
624 // The instruction has the form "(B) op (C op' D)". Try to factorize common
627 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
628 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS, Ident,
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?
641 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
642 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
643 // They do! Return "L op' R".
645 C = Builder->CreateBinOp(InnerOpcode, L, R);
651 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
652 // The instruction has the form "A op (B op' C)". See if expanding it out
653 // to "(A op B) op' (A op C)" results in simplifications.
654 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
655 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
657 // Do "A op B" and "A op C" both simplify?
658 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
659 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
660 // They do! Return "L op' R".
662 A = Builder->CreateBinOp(InnerOpcode, L, R);
668 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
669 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
670 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
671 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
672 if (SI0->getCondition() == SI1->getCondition()) {
674 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
675 SI1->getFalseValue(), DL, &TLI, &DT, &AC))
676 SI = Builder->CreateSelect(SI0->getCondition(),
677 Builder->CreateBinOp(TopLevelOpcode,
679 SI1->getTrueValue()),
681 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
682 SI1->getTrueValue(), DL, &TLI, &DT, &AC))
683 SI = Builder->CreateSelect(
684 SI0->getCondition(), V,
685 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
686 SI1->getFalseValue()));
698 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
699 /// constant zero (which is the 'negate' form).
700 Value *InstCombiner::dyn_castNegVal(Value *V) const {
701 if (BinaryOperator::isNeg(V))
702 return BinaryOperator::getNegArgument(V);
704 // Constants can be considered to be negated values if they can be folded.
705 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
706 return ConstantExpr::getNeg(C);
708 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
709 if (C->getType()->getElementType()->isIntegerTy())
710 return ConstantExpr::getNeg(C);
712 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
713 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
714 Constant *Elt = CV->getAggregateElement(i);
718 if (isa<UndefValue>(Elt))
721 if (!isa<ConstantInt>(Elt))
724 return ConstantExpr::getNeg(CV);
730 /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
731 /// a constant negative zero (which is the 'negate' form).
732 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
733 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
734 return BinaryOperator::getFNegArgument(V);
736 // Constants can be considered to be negated values if they can be folded.
737 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
738 return ConstantExpr::getFNeg(C);
740 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
741 if (C->getType()->getElementType()->isFloatingPointTy())
742 return ConstantExpr::getFNeg(C);
747 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
749 if (auto *Cast = dyn_cast<CastInst>(&I))
750 return IC->Builder->CreateCast(Cast->getOpcode(), SO, I.getType());
752 assert(I.isBinaryOp() && "Unexpected opcode for select folding");
754 // Figure out if the constant is the left or the right argument.
755 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
756 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
758 if (auto *SOC = dyn_cast<Constant>(SO)) {
760 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
761 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
764 Value *Op0 = SO, *Op1 = ConstOperand;
768 auto *BO = cast<BinaryOperator>(&I);
769 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
770 SO->getName() + ".op");
771 auto *FPInst = dyn_cast<Instruction>(RI);
772 if (FPInst && isa<FPMathOperator>(FPInst))
773 FPInst->copyFastMathFlags(BO);
777 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
778 // Don't modify shared select instructions.
779 if (!SI->hasOneUse())
782 Value *TV = SI->getTrueValue();
783 Value *FV = SI->getFalseValue();
784 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
787 // Bool selects with constant operands can be folded to logical ops.
788 if (SI->getType()->getScalarType()->isIntegerTy(1))
791 // If it's a bitcast involving vectors, make sure it has the same number of
792 // elements on both sides.
793 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
794 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
795 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
797 // Verify that either both or neither are vectors.
798 if ((SrcTy == nullptr) != (DestTy == nullptr))
801 // If vectors, verify that they have the same number of elements.
802 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
806 // Test if a CmpInst instruction is used exclusively by a select as
807 // part of a minimum or maximum operation. If so, refrain from doing
808 // any other folding. This helps out other analyses which understand
809 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
810 // and CodeGen. And in this case, at least one of the comparison
811 // operands has at least one user besides the compare (the select),
812 // which would often largely negate the benefit of folding anyway.
813 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
814 if (CI->hasOneUse()) {
815 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
816 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
817 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
822 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, this);
823 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, this);
824 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
827 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
829 bool ConstIsRHS = isa<Constant>(I->getOperand(1));
830 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
832 if (auto *InC = dyn_cast<Constant>(InV)) {
834 return ConstantExpr::get(I->getOpcode(), InC, C);
835 return ConstantExpr::get(I->getOpcode(), C, InC);
838 Value *Op0 = InV, *Op1 = C;
842 Value *RI = IC->Builder->CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
843 auto *FPInst = dyn_cast<Instruction>(RI);
844 if (FPInst && isa<FPMathOperator>(FPInst))
845 FPInst->copyFastMathFlags(I);
849 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
850 unsigned NumPHIValues = PN->getNumIncomingValues();
851 if (NumPHIValues == 0)
854 // We normally only transform phis with a single use. However, if a PHI has
855 // multiple uses and they are all the same operation, we can fold *all* of the
856 // uses into the PHI.
857 if (!PN->hasOneUse()) {
858 // Walk the use list for the instruction, comparing them to I.
859 for (User *U : PN->users()) {
860 Instruction *UI = cast<Instruction>(U);
861 if (UI != &I && !I.isIdenticalTo(UI))
864 // Otherwise, we can replace *all* users with the new PHI we form.
867 // Check to see if all of the operands of the PHI are simple constants
868 // (constantint/constantfp/undef). If there is one non-constant value,
869 // remember the BB it is in. If there is more than one or if *it* is a PHI,
870 // bail out. We don't do arbitrary constant expressions here because moving
871 // their computation can be expensive without a cost model.
872 BasicBlock *NonConstBB = nullptr;
873 for (unsigned i = 0; i != NumPHIValues; ++i) {
874 Value *InVal = PN->getIncomingValue(i);
875 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
878 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
879 if (NonConstBB) return nullptr; // More than one non-const value.
881 NonConstBB = PN->getIncomingBlock(i);
883 // If the InVal is an invoke at the end of the pred block, then we can't
884 // insert a computation after it without breaking the edge.
885 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
886 if (II->getParent() == NonConstBB)
889 // If the incoming non-constant value is in I's block, we will remove one
890 // instruction, but insert another equivalent one, leading to infinite
892 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
896 // If there is exactly one non-constant value, we can insert a copy of the
897 // operation in that block. However, if this is a critical edge, we would be
898 // inserting the computation on some other paths (e.g. inside a loop). Only
899 // do this if the pred block is unconditionally branching into the phi block.
900 if (NonConstBB != nullptr) {
901 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
902 if (!BI || !BI->isUnconditional()) return nullptr;
905 // Okay, we can do the transformation: create the new PHI node.
906 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
907 InsertNewInstBefore(NewPN, *PN);
910 // If we are going to have to insert a new computation, do so right before the
911 // predecessor's terminator.
913 Builder->SetInsertPoint(NonConstBB->getTerminator());
915 // Next, add all of the operands to the PHI.
916 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
917 // We only currently try to fold the condition of a select when it is a phi,
918 // not the true/false values.
919 Value *TrueV = SI->getTrueValue();
920 Value *FalseV = SI->getFalseValue();
921 BasicBlock *PhiTransBB = PN->getParent();
922 for (unsigned i = 0; i != NumPHIValues; ++i) {
923 BasicBlock *ThisBB = PN->getIncomingBlock(i);
924 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
925 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
926 Value *InV = nullptr;
927 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
928 // even if currently isNullValue gives false.
929 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
930 // For vector constants, we cannot use isNullValue to fold into
931 // FalseVInPred versus TrueVInPred. When we have individual nonzero
932 // elements in the vector, we will incorrectly fold InC to
934 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
935 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
937 InV = Builder->CreateSelect(PN->getIncomingValue(i),
938 TrueVInPred, FalseVInPred, "phitmp");
939 NewPN->addIncoming(InV, ThisBB);
941 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
942 Constant *C = cast<Constant>(I.getOperand(1));
943 for (unsigned i = 0; i != NumPHIValues; ++i) {
944 Value *InV = nullptr;
945 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
946 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
947 else if (isa<ICmpInst>(CI))
948 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
951 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
953 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
955 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
956 for (unsigned i = 0; i != NumPHIValues; ++i) {
957 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), this);
958 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
961 CastInst *CI = cast<CastInst>(&I);
962 Type *RetTy = CI->getType();
963 for (unsigned i = 0; i != NumPHIValues; ++i) {
965 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
966 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
968 InV = Builder->CreateCast(CI->getOpcode(),
969 PN->getIncomingValue(i), I.getType(), "phitmp");
970 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
974 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
975 Instruction *User = cast<Instruction>(*UI++);
976 if (User == &I) continue;
977 replaceInstUsesWith(*User, NewPN);
978 eraseInstFromFunction(*User);
980 return replaceInstUsesWith(I, NewPN);
983 Instruction *InstCombiner::foldOpWithConstantIntoOperand(BinaryOperator &I) {
984 assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
986 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
987 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
989 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
990 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
996 /// Given a pointer type and a constant offset, determine whether or not there
997 /// is a sequence of GEP indices into the pointed type that will land us at the
998 /// specified offset. If so, fill them into NewIndices and return the resultant
999 /// element type, otherwise return null.
1000 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1001 SmallVectorImpl<Value *> &NewIndices) {
1002 Type *Ty = PtrTy->getElementType();
1006 // Start with the index over the outer type. Note that the type size
1007 // might be zero (even if the offset isn't zero) if the indexed type
1008 // is something like [0 x {int, int}]
1009 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
1010 int64_t FirstIdx = 0;
1011 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1012 FirstIdx = Offset/TySize;
1013 Offset -= FirstIdx*TySize;
1015 // Handle hosts where % returns negative instead of values [0..TySize).
1019 assert(Offset >= 0);
1021 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1024 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
1026 // Index into the types. If we fail, set OrigBase to null.
1028 // Indexing into tail padding between struct/array elements.
1029 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1032 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1033 const StructLayout *SL = DL.getStructLayout(STy);
1034 assert(Offset < (int64_t)SL->getSizeInBytes() &&
1035 "Offset must stay within the indexed type");
1037 unsigned Elt = SL->getElementContainingOffset(Offset);
1038 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1041 Offset -= SL->getElementOffset(Elt);
1042 Ty = STy->getElementType(Elt);
1043 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1044 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1045 assert(EltSize && "Cannot index into a zero-sized array");
1046 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
1048 Ty = AT->getElementType();
1050 // Otherwise, we can't index into the middle of this atomic type, bail.
1058 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1059 // If this GEP has only 0 indices, it is the same pointer as
1060 // Src. If Src is not a trivial GEP too, don't combine
1062 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1068 /// Return a value X such that Val = X * Scale, or null if none.
1069 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1070 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1071 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1072 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1073 Scale.getBitWidth() && "Scale not compatible with value!");
1075 // If Val is zero or Scale is one then Val = Val * Scale.
1076 if (match(Val, m_Zero()) || Scale == 1) {
1077 NoSignedWrap = true;
1081 // If Scale is zero then it does not divide Val.
1082 if (Scale.isMinValue())
1085 // Look through chains of multiplications, searching for a constant that is
1086 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1087 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1088 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1091 // Val = M1 * X || Analysis starts here and works down
1092 // M1 = M2 * Y || Doesn't descend into terms with more
1093 // M2 = Z * 4 \/ than one use
1095 // Then to modify a term at the bottom:
1098 // M1 = Z * Y || Replaced M2 with Z
1100 // Then to work back up correcting nsw flags.
1102 // Op - the term we are currently analyzing. Starts at Val then drills down.
1103 // Replaced with its descaled value before exiting from the drill down loop.
1106 // Parent - initially null, but after drilling down notes where Op came from.
1107 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1108 // 0'th operand of Val.
1109 std::pair<Instruction*, unsigned> Parent;
1111 // Set if the transform requires a descaling at deeper levels that doesn't
1113 bool RequireNoSignedWrap = false;
1115 // Log base 2 of the scale. Negative if not a power of 2.
1116 int32_t logScale = Scale.exactLogBase2();
1118 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1120 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1121 // If Op is a constant divisible by Scale then descale to the quotient.
1122 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1123 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1124 if (!Remainder.isMinValue())
1125 // Not divisible by Scale.
1127 // Replace with the quotient in the parent.
1128 Op = ConstantInt::get(CI->getType(), Quotient);
1129 NoSignedWrap = true;
1133 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1135 if (BO->getOpcode() == Instruction::Mul) {
1137 NoSignedWrap = BO->hasNoSignedWrap();
1138 if (RequireNoSignedWrap && !NoSignedWrap)
1141 // There are three cases for multiplication: multiplication by exactly
1142 // the scale, multiplication by a constant different to the scale, and
1143 // multiplication by something else.
1144 Value *LHS = BO->getOperand(0);
1145 Value *RHS = BO->getOperand(1);
1147 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1148 // Multiplication by a constant.
1149 if (CI->getValue() == Scale) {
1150 // Multiplication by exactly the scale, replace the multiplication
1151 // by its left-hand side in the parent.
1156 // Otherwise drill down into the constant.
1157 if (!Op->hasOneUse())
1160 Parent = std::make_pair(BO, 1);
1164 // Multiplication by something else. Drill down into the left-hand side
1165 // since that's where the reassociate pass puts the good stuff.
1166 if (!Op->hasOneUse())
1169 Parent = std::make_pair(BO, 0);
1173 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1174 isa<ConstantInt>(BO->getOperand(1))) {
1175 // Multiplication by a power of 2.
1176 NoSignedWrap = BO->hasNoSignedWrap();
1177 if (RequireNoSignedWrap && !NoSignedWrap)
1180 Value *LHS = BO->getOperand(0);
1181 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1182 getLimitedValue(Scale.getBitWidth());
1185 if (Amt == logScale) {
1186 // Multiplication by exactly the scale, replace the multiplication
1187 // by its left-hand side in the parent.
1191 if (Amt < logScale || !Op->hasOneUse())
1194 // Multiplication by more than the scale. Reduce the multiplying amount
1195 // by the scale in the parent.
1196 Parent = std::make_pair(BO, 1);
1197 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1202 if (!Op->hasOneUse())
1205 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1206 if (Cast->getOpcode() == Instruction::SExt) {
1207 // Op is sign-extended from a smaller type, descale in the smaller type.
1208 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1209 APInt SmallScale = Scale.trunc(SmallSize);
1210 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1211 // descale Op as (sext Y) * Scale. In order to have
1212 // sext (Y * SmallScale) = (sext Y) * Scale
1213 // some conditions need to hold however: SmallScale must sign-extend to
1214 // Scale and the multiplication Y * SmallScale should not overflow.
1215 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1216 // SmallScale does not sign-extend to Scale.
1218 assert(SmallScale.exactLogBase2() == logScale);
1219 // Require that Y * SmallScale must not overflow.
1220 RequireNoSignedWrap = true;
1222 // Drill down through the cast.
1223 Parent = std::make_pair(Cast, 0);
1228 if (Cast->getOpcode() == Instruction::Trunc) {
1229 // Op is truncated from a larger type, descale in the larger type.
1230 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1231 // trunc (Y * sext Scale) = (trunc Y) * Scale
1232 // always holds. However (trunc Y) * Scale may overflow even if
1233 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1234 // from this point up in the expression (see later).
1235 if (RequireNoSignedWrap)
1238 // Drill down through the cast.
1239 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1240 Parent = std::make_pair(Cast, 0);
1241 Scale = Scale.sext(LargeSize);
1242 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1244 assert(Scale.exactLogBase2() == logScale);
1249 // Unsupported expression, bail out.
1253 // If Op is zero then Val = Op * Scale.
1254 if (match(Op, m_Zero())) {
1255 NoSignedWrap = true;
1259 // We know that we can successfully descale, so from here on we can safely
1260 // modify the IR. Op holds the descaled version of the deepest term in the
1261 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1265 // The expression only had one term.
1268 // Rewrite the parent using the descaled version of its operand.
1269 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1270 assert(Op != Parent.first->getOperand(Parent.second) &&
1271 "Descaling was a no-op?");
1272 Parent.first->setOperand(Parent.second, Op);
1273 Worklist.Add(Parent.first);
1275 // Now work back up the expression correcting nsw flags. The logic is based
1276 // on the following observation: if X * Y is known not to overflow as a signed
1277 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1278 // then X * Z will not overflow as a signed multiplication either. As we work
1279 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1280 // current level has strictly smaller absolute value than the original.
1281 Instruction *Ancestor = Parent.first;
1283 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1284 // If the multiplication wasn't nsw then we can't say anything about the
1285 // value of the descaled multiplication, and we have to clear nsw flags
1286 // from this point on up.
1287 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1288 NoSignedWrap &= OpNoSignedWrap;
1289 if (NoSignedWrap != OpNoSignedWrap) {
1290 BO->setHasNoSignedWrap(NoSignedWrap);
1291 Worklist.Add(Ancestor);
1293 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1294 // The fact that the descaled input to the trunc has smaller absolute
1295 // value than the original input doesn't tell us anything useful about
1296 // the absolute values of the truncations.
1297 NoSignedWrap = false;
1299 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1300 "Failed to keep proper track of nsw flags while drilling down?");
1302 if (Ancestor == Val)
1303 // Got to the top, all done!
1306 // Move up one level in the expression.
1307 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1308 Ancestor = Ancestor->user_back();
1312 /// \brief Creates node of binary operation with the same attributes as the
1313 /// specified one but with other operands.
1314 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1315 InstCombiner::BuilderTy *B) {
1316 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1317 // If LHS and RHS are constant, BO won't be a binary operator.
1318 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1319 NewBO->copyIRFlags(&Inst);
1323 /// \brief Makes transformation of binary operation specific for vector types.
1324 /// \param Inst Binary operator to transform.
1325 /// \return Pointer to node that must replace the original binary operator, or
1326 /// null pointer if no transformation was made.
1327 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1328 if (!Inst.getType()->isVectorTy()) return nullptr;
1330 // It may not be safe to reorder shuffles and things like div, urem, etc.
1331 // because we may trap when executing those ops on unknown vector elements.
1333 if (!isSafeToSpeculativelyExecute(&Inst))
1336 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1337 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1338 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1339 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1341 // If both arguments of the binary operation are shuffles that use the same
1342 // mask and shuffle within a single vector, move the shuffle after the binop:
1343 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1344 auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1345 auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1346 if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1347 isa<UndefValue>(LShuf->getOperand(1)) &&
1348 isa<UndefValue>(RShuf->getOperand(1)) &&
1349 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1350 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1351 RShuf->getOperand(0), Builder);
1352 return Builder->CreateShuffleVector(
1353 NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
1356 // If one argument is a shuffle within one vector, the other is a constant,
1357 // try moving the shuffle after the binary operation.
1358 ShuffleVectorInst *Shuffle = nullptr;
1359 Constant *C1 = nullptr;
1360 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1361 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1362 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1363 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1364 if (Shuffle && C1 &&
1365 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1366 isa<UndefValue>(Shuffle->getOperand(1)) &&
1367 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1368 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1369 // Find constant C2 that has property:
1370 // shuffle(C2, ShMask) = C1
1371 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1372 // reorder is not possible.
1373 SmallVector<Constant*, 16> C2M(VWidth,
1374 UndefValue::get(C1->getType()->getScalarType()));
1375 bool MayChange = true;
1376 for (unsigned I = 0; I < VWidth; ++I) {
1377 if (ShMask[I] >= 0) {
1378 assert(ShMask[I] < (int)VWidth);
1379 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1383 C2M[ShMask[I]] = C1->getAggregateElement(I);
1387 Constant *C2 = ConstantVector::get(C2M);
1388 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1389 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1390 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1391 return Builder->CreateShuffleVector(NewBO,
1392 UndefValue::get(Inst.getType()), Shuffle->getMask());
1399 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1400 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1403 SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, &TLI, &DT, &AC))
1404 return replaceInstUsesWith(GEP, V);
1406 Value *PtrOp = GEP.getOperand(0);
1408 // Eliminate unneeded casts for indices, and replace indices which displace
1409 // by multiples of a zero size type with zero.
1410 bool MadeChange = false;
1412 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1414 gep_type_iterator GTI = gep_type_begin(GEP);
1415 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1417 // Skip indices into struct types.
1421 // Index type should have the same width as IntPtr
1422 Type *IndexTy = (*I)->getType();
1423 Type *NewIndexType = IndexTy->isVectorTy() ?
1424 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1426 // If the element type has zero size then any index over it is equivalent
1427 // to an index of zero, so replace it with zero if it is not zero already.
1428 Type *EltTy = GTI.getIndexedType();
1429 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1430 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1431 *I = Constant::getNullValue(NewIndexType);
1435 if (IndexTy != NewIndexType) {
1436 // If we are using a wider index than needed for this platform, shrink
1437 // it to what we need. If narrower, sign-extend it to what we need.
1438 // This explicit cast can make subsequent optimizations more obvious.
1439 *I = Builder->CreateIntCast(*I, NewIndexType, true);
1446 // Check to see if the inputs to the PHI node are getelementptr instructions.
1447 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1448 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1452 // Don't fold a GEP into itself through a PHI node. This can only happen
1453 // through the back-edge of a loop. Folding a GEP into itself means that
1454 // the value of the previous iteration needs to be stored in the meantime,
1455 // thus requiring an additional register variable to be live, but not
1456 // actually achieving anything (the GEP still needs to be executed once per
1463 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1464 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1465 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1468 // As for Op1 above, don't try to fold a GEP into itself.
1472 // Keep track of the type as we walk the GEP.
1473 Type *CurTy = nullptr;
1475 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1476 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1479 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1481 // We have not seen any differences yet in the GEPs feeding the
1482 // PHI yet, so we record this one if it is allowed to be a
1485 // The first two arguments can vary for any GEP, the rest have to be
1486 // static for struct slots
1487 if (J > 1 && CurTy->isStructTy())
1492 // The GEP is different by more than one input. While this could be
1493 // extended to support GEPs that vary by more than one variable it
1494 // doesn't make sense since it greatly increases the complexity and
1495 // would result in an R+R+R addressing mode which no backend
1496 // directly supports and would need to be broken into several
1497 // simpler instructions anyway.
1502 // Sink down a layer of the type for the next iteration.
1505 CurTy = Op1->getSourceElementType();
1506 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1507 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1515 // If not all GEPs are identical we'll have to create a new PHI node.
1516 // Check that the old PHI node has only one use so that it will get
1518 if (DI != -1 && !PN->hasOneUse())
1521 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1523 // All the GEPs feeding the PHI are identical. Clone one down into our
1524 // BB so that it can be merged with the current GEP.
1525 GEP.getParent()->getInstList().insert(
1526 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1528 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1529 // into the current block so it can be merged, and create a new PHI to
1533 IRBuilderBase::InsertPointGuard Guard(*Builder);
1534 Builder->SetInsertPoint(PN);
1535 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1536 PN->getNumOperands());
1539 for (auto &I : PN->operands())
1540 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1541 PN->getIncomingBlock(I));
1543 NewGEP->setOperand(DI, NewPN);
1544 GEP.getParent()->getInstList().insert(
1545 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1546 NewGEP->setOperand(DI, NewPN);
1549 GEP.setOperand(0, NewGEP);
1553 // Combine Indices - If the source pointer to this getelementptr instruction
1554 // is a getelementptr instruction, combine the indices of the two
1555 // getelementptr instructions into a single instruction.
1557 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1558 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1561 // Note that if our source is a gep chain itself then we wait for that
1562 // chain to be resolved before we perform this transformation. This
1563 // avoids us creating a TON of code in some cases.
1564 if (GEPOperator *SrcGEP =
1565 dyn_cast<GEPOperator>(Src->getOperand(0)))
1566 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1567 return nullptr; // Wait until our source is folded to completion.
1569 SmallVector<Value*, 8> Indices;
1571 // Find out whether the last index in the source GEP is a sequential idx.
1572 bool EndsWithSequential = false;
1573 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1575 EndsWithSequential = I.isSequential();
1577 // Can we combine the two pointer arithmetics offsets?
1578 if (EndsWithSequential) {
1579 // Replace: gep (gep %P, long B), long A, ...
1580 // With: T = long A+B; gep %P, T, ...
1582 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1583 Value *GO1 = GEP.getOperand(1);
1585 // If they aren't the same type, then the input hasn't been processed
1586 // by the loop above yet (which canonicalizes sequential index types to
1587 // intptr_t). Just avoid transforming this until the input has been
1589 if (SO1->getType() != GO1->getType())
1592 Value* Sum = SimplifyAddInst(GO1, SO1, false, false, DL, &TLI, &DT, &AC);
1593 // Only do the combine when we are sure the cost after the
1594 // merge is never more than that before the merge.
1598 // Update the GEP in place if possible.
1599 if (Src->getNumOperands() == 2) {
1600 GEP.setOperand(0, Src->getOperand(0));
1601 GEP.setOperand(1, Sum);
1604 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1605 Indices.push_back(Sum);
1606 Indices.append(GEP.op_begin()+2, GEP.op_end());
1607 } else if (isa<Constant>(*GEP.idx_begin()) &&
1608 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1609 Src->getNumOperands() != 1) {
1610 // Otherwise we can do the fold if the first index of the GEP is a zero
1611 Indices.append(Src->op_begin()+1, Src->op_end());
1612 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1615 if (!Indices.empty())
1616 return GEP.isInBounds() && Src->isInBounds()
1617 ? GetElementPtrInst::CreateInBounds(
1618 Src->getSourceElementType(), Src->getOperand(0), Indices,
1620 : GetElementPtrInst::Create(Src->getSourceElementType(),
1621 Src->getOperand(0), Indices,
1625 if (GEP.getNumIndices() == 1) {
1626 unsigned AS = GEP.getPointerAddressSpace();
1627 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1628 DL.getPointerSizeInBits(AS)) {
1629 Type *Ty = GEP.getSourceElementType();
1630 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1632 bool Matched = false;
1635 if (TyAllocSize == 1) {
1636 V = GEP.getOperand(1);
1638 } else if (match(GEP.getOperand(1),
1639 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1640 if (TyAllocSize == 1ULL << C)
1642 } else if (match(GEP.getOperand(1),
1643 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1644 if (TyAllocSize == C)
1649 // Canonicalize (gep i8* X, -(ptrtoint Y))
1650 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1651 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1652 // pointer arithmetic.
1653 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1654 Operator *Index = cast<Operator>(V);
1655 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1656 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1657 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1659 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1662 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1663 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1664 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1671 // We do not handle pointer-vector geps here.
1672 if (GEP.getType()->isVectorTy())
1675 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1676 Value *StrippedPtr = PtrOp->stripPointerCasts();
1677 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1679 if (StrippedPtr != PtrOp) {
1680 bool HasZeroPointerIndex = false;
1681 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1682 HasZeroPointerIndex = C->isZero();
1684 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1685 // into : GEP [10 x i8]* X, i32 0, ...
1687 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1688 // into : GEP i8* X, ...
1690 // This occurs when the program declares an array extern like "int X[];"
1691 if (HasZeroPointerIndex) {
1692 if (ArrayType *CATy =
1693 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1694 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1695 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1696 // -> GEP i8* X, ...
1697 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1698 GetElementPtrInst *Res = GetElementPtrInst::Create(
1699 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1700 Res->setIsInBounds(GEP.isInBounds());
1701 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1703 // Insert Res, and create an addrspacecast.
1705 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1707 // %0 = GEP i8 addrspace(1)* X, ...
1708 // addrspacecast i8 addrspace(1)* %0 to i8*
1709 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1712 if (ArrayType *XATy =
1713 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1714 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1715 if (CATy->getElementType() == XATy->getElementType()) {
1716 // -> GEP [10 x i8]* X, i32 0, ...
1717 // At this point, we know that the cast source type is a pointer
1718 // to an array of the same type as the destination pointer
1719 // array. Because the array type is never stepped over (there
1720 // is a leading zero) we can fold the cast into this GEP.
1721 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1722 GEP.setOperand(0, StrippedPtr);
1723 GEP.setSourceElementType(XATy);
1726 // Cannot replace the base pointer directly because StrippedPtr's
1727 // address space is different. Instead, create a new GEP followed by
1728 // an addrspacecast.
1730 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1733 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1734 // addrspacecast i8 addrspace(1)* %0 to i8*
1735 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1736 Value *NewGEP = GEP.isInBounds()
1737 ? Builder->CreateInBoundsGEP(
1738 nullptr, StrippedPtr, Idx, GEP.getName())
1739 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1741 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1745 } else if (GEP.getNumOperands() == 2) {
1746 // Transform things like:
1747 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1748 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1749 Type *SrcElTy = StrippedPtrTy->getElementType();
1750 Type *ResElTy = GEP.getSourceElementType();
1751 if (SrcElTy->isArrayTy() &&
1752 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1753 DL.getTypeAllocSize(ResElTy)) {
1754 Type *IdxType = DL.getIntPtrType(GEP.getType());
1755 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1758 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1760 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1762 // V and GEP are both pointer types --> BitCast
1763 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1767 // Transform things like:
1768 // %V = mul i64 %N, 4
1769 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1770 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1771 if (ResElTy->isSized() && SrcElTy->isSized()) {
1772 // Check that changing the type amounts to dividing the index by a scale
1774 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1775 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1776 if (ResSize && SrcSize % ResSize == 0) {
1777 Value *Idx = GEP.getOperand(1);
1778 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1779 uint64_t Scale = SrcSize / ResSize;
1781 // Earlier transforms ensure that the index has type IntPtrType, which
1782 // considerably simplifies the logic by eliminating implicit casts.
1783 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1784 "Index not cast to pointer width?");
1787 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1788 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1789 // If the multiplication NewIdx * Scale may overflow then the new
1790 // GEP may not be "inbounds".
1792 GEP.isInBounds() && NSW
1793 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1795 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1798 // The NewGEP must be pointer typed, so must the old one -> BitCast
1799 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1805 // Similarly, transform things like:
1806 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1807 // (where tmp = 8*tmp2) into:
1808 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1809 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1810 // Check that changing to the array element type amounts to dividing the
1811 // index by a scale factor.
1812 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1813 uint64_t ArrayEltSize =
1814 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1815 if (ResSize && ArrayEltSize % ResSize == 0) {
1816 Value *Idx = GEP.getOperand(1);
1817 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1818 uint64_t Scale = ArrayEltSize / ResSize;
1820 // Earlier transforms ensure that the index has type IntPtrType, which
1821 // considerably simplifies the logic by eliminating implicit casts.
1822 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1823 "Index not cast to pointer width?");
1826 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1827 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1828 // If the multiplication NewIdx * Scale may overflow then the new
1829 // GEP may not be "inbounds".
1831 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1834 Value *NewGEP = GEP.isInBounds() && NSW
1835 ? Builder->CreateInBoundsGEP(
1836 SrcElTy, StrippedPtr, Off, GEP.getName())
1837 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1839 // The NewGEP must be pointer typed, so must the old one -> BitCast
1840 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1848 // addrspacecast between types is canonicalized as a bitcast, then an
1849 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1850 // through the addrspacecast.
1851 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1852 // X = bitcast A addrspace(1)* to B addrspace(1)*
1853 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1854 // Z = gep Y, <...constant indices...>
1855 // Into an addrspacecasted GEP of the struct.
1856 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1860 /// See if we can simplify:
1861 /// X = bitcast A* to B*
1862 /// Y = gep X, <...constant indices...>
1863 /// into a gep of the original struct. This is important for SROA and alias
1864 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1865 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1866 Value *Operand = BCI->getOperand(0);
1867 PointerType *OpType = cast<PointerType>(Operand->getType());
1868 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1869 APInt Offset(OffsetBits, 0);
1870 if (!isa<BitCastInst>(Operand) &&
1871 GEP.accumulateConstantOffset(DL, Offset)) {
1873 // If this GEP instruction doesn't move the pointer, just replace the GEP
1874 // with a bitcast of the real input to the dest type.
1876 // If the bitcast is of an allocation, and the allocation will be
1877 // converted to match the type of the cast, don't touch this.
1878 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
1879 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1880 if (Instruction *I = visitBitCast(*BCI)) {
1883 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1884 replaceInstUsesWith(*BCI, I);
1890 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1891 return new AddrSpaceCastInst(Operand, GEP.getType());
1892 return new BitCastInst(Operand, GEP.getType());
1895 // Otherwise, if the offset is non-zero, we need to find out if there is a
1896 // field at Offset in 'A's type. If so, we can pull the cast through the
1898 SmallVector<Value*, 8> NewIndices;
1899 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1902 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1903 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1905 if (NGEP->getType() == GEP.getType())
1906 return replaceInstUsesWith(GEP, NGEP);
1907 NGEP->takeName(&GEP);
1909 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1910 return new AddrSpaceCastInst(NGEP, GEP.getType());
1911 return new BitCastInst(NGEP, GEP.getType());
1916 if (!GEP.isInBounds()) {
1918 DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1919 APInt BasePtrOffset(PtrWidth, 0);
1920 Value *UnderlyingPtrOp =
1921 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1923 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1924 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1925 BasePtrOffset.isNonNegative()) {
1926 APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1927 if (BasePtrOffset.ule(AllocSize)) {
1928 return GetElementPtrInst::CreateInBounds(
1929 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1938 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1940 if (isa<ConstantPointerNull>(V))
1942 if (auto *LI = dyn_cast<LoadInst>(V))
1943 return isa<GlobalVariable>(LI->getPointerOperand());
1944 // Two distinct allocations will never be equal.
1945 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1946 // through bitcasts of V can cause
1947 // the result statement below to be true, even when AI and V (ex:
1948 // i8* ->i32* ->i8* of AI) are the same allocations.
1949 return isAllocLikeFn(V, TLI) && V != AI;
1953 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1954 const TargetLibraryInfo *TLI) {
1955 SmallVector<Instruction*, 4> Worklist;
1956 Worklist.push_back(AI);
1959 Instruction *PI = Worklist.pop_back_val();
1960 for (User *U : PI->users()) {
1961 Instruction *I = cast<Instruction>(U);
1962 switch (I->getOpcode()) {
1964 // Give up the moment we see something we can't handle.
1967 case Instruction::BitCast:
1968 case Instruction::GetElementPtr:
1969 Users.emplace_back(I);
1970 Worklist.push_back(I);
1973 case Instruction::ICmp: {
1974 ICmpInst *ICI = cast<ICmpInst>(I);
1975 // We can fold eq/ne comparisons with null to false/true, respectively.
1976 // We also fold comparisons in some conditions provided the alloc has
1977 // not escaped (see isNeverEqualToUnescapedAlloc).
1978 if (!ICI->isEquality())
1980 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
1981 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
1983 Users.emplace_back(I);
1987 case Instruction::Call:
1988 // Ignore no-op and store intrinsics.
1989 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1990 switch (II->getIntrinsicID()) {
1994 case Intrinsic::memmove:
1995 case Intrinsic::memcpy:
1996 case Intrinsic::memset: {
1997 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1998 if (MI->isVolatile() || MI->getRawDest() != PI)
2002 case Intrinsic::dbg_declare:
2003 case Intrinsic::dbg_value:
2004 case Intrinsic::invariant_start:
2005 case Intrinsic::invariant_end:
2006 case Intrinsic::lifetime_start:
2007 case Intrinsic::lifetime_end:
2008 case Intrinsic::objectsize:
2009 Users.emplace_back(I);
2014 if (isFreeCall(I, TLI)) {
2015 Users.emplace_back(I);
2020 case Instruction::Store: {
2021 StoreInst *SI = cast<StoreInst>(I);
2022 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2024 Users.emplace_back(I);
2028 llvm_unreachable("missing a return?");
2030 } while (!Worklist.empty());
2034 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2035 // If we have a malloc call which is only used in any amount of comparisons
2036 // to null and free calls, delete the calls and replace the comparisons with
2037 // true or false as appropriate.
2038 SmallVector<WeakVH, 64> Users;
2039 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2040 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2041 // Lowering all @llvm.objectsize calls first because they may
2042 // use a bitcast/GEP of the alloca we are removing.
2046 Instruction *I = cast<Instruction>(&*Users[i]);
2048 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2049 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2050 ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2051 /*MustSucceed=*/true);
2052 replaceInstUsesWith(*I, Result);
2053 eraseInstFromFunction(*I);
2054 Users[i] = nullptr; // Skip examining in the next loop.
2058 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2062 Instruction *I = cast<Instruction>(&*Users[i]);
2064 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2065 replaceInstUsesWith(*C,
2066 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2067 C->isFalseWhenEqual()));
2068 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2069 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2071 eraseInstFromFunction(*I);
2074 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2075 // Replace invoke with a NOP intrinsic to maintain the original CFG
2076 Module *M = II->getModule();
2077 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2078 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2079 None, "", II->getParent());
2081 return eraseInstFromFunction(MI);
2086 /// \brief Move the call to free before a NULL test.
2088 /// Check if this free is accessed after its argument has been test
2089 /// against NULL (property 0).
2090 /// If yes, it is legal to move this call in its predecessor block.
2092 /// The move is performed only if the block containing the call to free
2093 /// will be removed, i.e.:
2094 /// 1. it has only one predecessor P, and P has two successors
2095 /// 2. it contains the call and an unconditional branch
2096 /// 3. its successor is the same as its predecessor's successor
2098 /// The profitability is out-of concern here and this function should
2099 /// be called only if the caller knows this transformation would be
2100 /// profitable (e.g., for code size).
2101 static Instruction *
2102 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2103 Value *Op = FI.getArgOperand(0);
2104 BasicBlock *FreeInstrBB = FI.getParent();
2105 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2107 // Validate part of constraint #1: Only one predecessor
2108 // FIXME: We can extend the number of predecessor, but in that case, we
2109 // would duplicate the call to free in each predecessor and it may
2110 // not be profitable even for code size.
2114 // Validate constraint #2: Does this block contains only the call to
2115 // free and an unconditional branch?
2116 // FIXME: We could check if we can speculate everything in the
2117 // predecessor block
2118 if (FreeInstrBB->size() != 2)
2121 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2124 // Validate the rest of constraint #1 by matching on the pred branch.
2125 TerminatorInst *TI = PredBB->getTerminator();
2126 BasicBlock *TrueBB, *FalseBB;
2127 ICmpInst::Predicate Pred;
2128 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2130 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2133 // Validate constraint #3: Ensure the null case just falls through.
2134 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2136 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2137 "Broken CFG: missing edge from predecessor to successor");
2144 Instruction *InstCombiner::visitFree(CallInst &FI) {
2145 Value *Op = FI.getArgOperand(0);
2147 // free undef -> unreachable.
2148 if (isa<UndefValue>(Op)) {
2149 // Insert a new store to null because we cannot modify the CFG here.
2150 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2151 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2152 return eraseInstFromFunction(FI);
2155 // If we have 'free null' delete the instruction. This can happen in stl code
2156 // when lots of inlining happens.
2157 if (isa<ConstantPointerNull>(Op))
2158 return eraseInstFromFunction(FI);
2160 // If we optimize for code size, try to move the call to free before the null
2161 // test so that simplify cfg can remove the empty block and dead code
2162 // elimination the branch. I.e., helps to turn something like:
2163 // if (foo) free(foo);
2167 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2173 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2174 if (RI.getNumOperands() == 0) // ret void
2177 Value *ResultOp = RI.getOperand(0);
2178 Type *VTy = ResultOp->getType();
2179 if (!VTy->isIntegerTy())
2182 // There might be assume intrinsics dominating this return that completely
2183 // determine the value. If so, constant fold it.
2184 KnownBits Known(VTy->getPrimitiveSizeInBits());
2185 computeKnownBits(ResultOp, Known, 0, &RI);
2186 if ((Known.Zero|Known.One).isAllOnesValue())
2187 RI.setOperand(0, Constant::getIntegerValue(VTy, Known.One));
2192 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2193 // Change br (not X), label True, label False to: br X, label False, True
2195 BasicBlock *TrueDest;
2196 BasicBlock *FalseDest;
2197 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2198 !isa<Constant>(X)) {
2199 // Swap Destinations and condition...
2201 BI.swapSuccessors();
2205 // If the condition is irrelevant, remove the use so that other
2206 // transforms on the condition become more effective.
2207 if (BI.isConditional() &&
2208 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2209 !isa<UndefValue>(BI.getCondition())) {
2210 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2214 // Canonicalize fcmp_one -> fcmp_oeq
2215 FCmpInst::Predicate FPred; Value *Y;
2216 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2217 TrueDest, FalseDest)) &&
2218 BI.getCondition()->hasOneUse())
2219 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2220 FPred == FCmpInst::FCMP_OGE) {
2221 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2222 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2224 // Swap Destinations and condition.
2225 BI.swapSuccessors();
2230 // Canonicalize icmp_ne -> icmp_eq
2231 ICmpInst::Predicate IPred;
2232 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2233 TrueDest, FalseDest)) &&
2234 BI.getCondition()->hasOneUse())
2235 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2236 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2237 IPred == ICmpInst::ICMP_SGE) {
2238 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2239 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2240 // Swap Destinations and condition.
2241 BI.swapSuccessors();
2249 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2250 Value *Cond = SI.getCondition();
2252 ConstantInt *AddRHS;
2253 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2254 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2255 for (auto Case : SI.cases()) {
2256 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2257 assert(isa<ConstantInt>(NewCase) &&
2258 "Result of expression should be constant");
2259 Case.setValue(cast<ConstantInt>(NewCase));
2261 SI.setCondition(Op0);
2265 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2266 KnownBits Known(BitWidth);
2267 computeKnownBits(Cond, Known, 0, &SI);
2268 unsigned LeadingKnownZeros = Known.Zero.countLeadingOnes();
2269 unsigned LeadingKnownOnes = Known.One.countLeadingOnes();
2271 // Compute the number of leading bits we can ignore.
2272 // TODO: A better way to determine this would use ComputeNumSignBits().
2273 for (auto &C : SI.cases()) {
2274 LeadingKnownZeros = std::min(
2275 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2276 LeadingKnownOnes = std::min(
2277 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2280 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2282 // Shrink the condition operand if the new type is smaller than the old type.
2283 // This may produce a non-standard type for the switch, but that's ok because
2284 // the backend should extend back to a legal type for the target.
2285 if (NewWidth > 0 && NewWidth < BitWidth) {
2286 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2287 Builder->SetInsertPoint(&SI);
2288 Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
2289 SI.setCondition(NewCond);
2291 for (auto Case : SI.cases()) {
2292 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2293 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2301 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2302 Value *Agg = EV.getAggregateOperand();
2304 if (!EV.hasIndices())
2305 return replaceInstUsesWith(EV, Agg);
2308 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, &TLI, &DT, &AC))
2309 return replaceInstUsesWith(EV, V);
2311 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2312 // We're extracting from an insertvalue instruction, compare the indices
2313 const unsigned *exti, *exte, *insi, *inse;
2314 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2315 exte = EV.idx_end(), inse = IV->idx_end();
2316 exti != exte && insi != inse;
2319 // The insert and extract both reference distinctly different elements.
2320 // This means the extract is not influenced by the insert, and we can
2321 // replace the aggregate operand of the extract with the aggregate
2322 // operand of the insert. i.e., replace
2323 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2324 // %E = extractvalue { i32, { i32 } } %I, 0
2326 // %E = extractvalue { i32, { i32 } } %A, 0
2327 return ExtractValueInst::Create(IV->getAggregateOperand(),
2330 if (exti == exte && insi == inse)
2331 // Both iterators are at the end: Index lists are identical. Replace
2332 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2333 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2335 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2337 // The extract list is a prefix of the insert list. i.e. replace
2338 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2339 // %E = extractvalue { i32, { i32 } } %I, 1
2341 // %X = extractvalue { i32, { i32 } } %A, 1
2342 // %E = insertvalue { i32 } %X, i32 42, 0
2343 // by switching the order of the insert and extract (though the
2344 // insertvalue should be left in, since it may have other uses).
2345 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2347 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2348 makeArrayRef(insi, inse));
2351 // The insert list is a prefix of the extract list
2352 // We can simply remove the common indices from the extract and make it
2353 // operate on the inserted value instead of the insertvalue result.
2355 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2356 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2358 // %E extractvalue { i32 } { i32 42 }, 0
2359 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2360 makeArrayRef(exti, exte));
2362 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2363 // We're extracting from an intrinsic, see if we're the only user, which
2364 // allows us to simplify multiple result intrinsics to simpler things that
2365 // just get one value.
2366 if (II->hasOneUse()) {
2367 // Check if we're grabbing the overflow bit or the result of a 'with
2368 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2369 // and replace it with a traditional binary instruction.
2370 switch (II->getIntrinsicID()) {
2371 case Intrinsic::uadd_with_overflow:
2372 case Intrinsic::sadd_with_overflow:
2373 if (*EV.idx_begin() == 0) { // Normal result.
2374 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2375 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2376 eraseInstFromFunction(*II);
2377 return BinaryOperator::CreateAdd(LHS, RHS);
2380 // If the normal result of the add is dead, and the RHS is a constant,
2381 // we can transform this into a range comparison.
2382 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2383 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2384 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2385 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2386 ConstantExpr::getNot(CI));
2388 case Intrinsic::usub_with_overflow:
2389 case Intrinsic::ssub_with_overflow:
2390 if (*EV.idx_begin() == 0) { // Normal result.
2391 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2392 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2393 eraseInstFromFunction(*II);
2394 return BinaryOperator::CreateSub(LHS, RHS);
2397 case Intrinsic::umul_with_overflow:
2398 case Intrinsic::smul_with_overflow:
2399 if (*EV.idx_begin() == 0) { // Normal result.
2400 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2401 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2402 eraseInstFromFunction(*II);
2403 return BinaryOperator::CreateMul(LHS, RHS);
2411 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2412 // If the (non-volatile) load only has one use, we can rewrite this to a
2413 // load from a GEP. This reduces the size of the load. If a load is used
2414 // only by extractvalue instructions then this either must have been
2415 // optimized before, or it is a struct with padding, in which case we
2416 // don't want to do the transformation as it loses padding knowledge.
2417 if (L->isSimple() && L->hasOneUse()) {
2418 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2419 SmallVector<Value*, 4> Indices;
2420 // Prefix an i32 0 since we need the first element.
2421 Indices.push_back(Builder->getInt32(0));
2422 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2424 Indices.push_back(Builder->getInt32(*I));
2426 // We need to insert these at the location of the old load, not at that of
2427 // the extractvalue.
2428 Builder->SetInsertPoint(L);
2429 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2430 L->getPointerOperand(), Indices);
2431 // Returning the load directly will cause the main loop to insert it in
2432 // the wrong spot, so use replaceInstUsesWith().
2433 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2435 // We could simplify extracts from other values. Note that nested extracts may
2436 // already be simplified implicitly by the above: extract (extract (insert) )
2437 // will be translated into extract ( insert ( extract ) ) first and then just
2438 // the value inserted, if appropriate. Similarly for extracts from single-use
2439 // loads: extract (extract (load)) will be translated to extract (load (gep))
2440 // and if again single-use then via load (gep (gep)) to load (gep).
2441 // However, double extracts from e.g. function arguments or return values
2442 // aren't handled yet.
2446 /// Return 'true' if the given typeinfo will match anything.
2447 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2448 switch (Personality) {
2449 case EHPersonality::GNU_C:
2450 case EHPersonality::GNU_C_SjLj:
2451 case EHPersonality::Rust:
2452 // The GCC C EH and Rust personality only exists to support cleanups, so
2453 // it's not clear what the semantics of catch clauses are.
2455 case EHPersonality::Unknown:
2457 case EHPersonality::GNU_Ada:
2458 // While __gnat_all_others_value will match any Ada exception, it doesn't
2459 // match foreign exceptions (or didn't, before gcc-4.7).
2461 case EHPersonality::GNU_CXX:
2462 case EHPersonality::GNU_CXX_SjLj:
2463 case EHPersonality::GNU_ObjC:
2464 case EHPersonality::MSVC_X86SEH:
2465 case EHPersonality::MSVC_Win64SEH:
2466 case EHPersonality::MSVC_CXX:
2467 case EHPersonality::CoreCLR:
2468 return TypeInfo->isNullValue();
2470 llvm_unreachable("invalid enum");
2473 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2475 cast<ArrayType>(LHS->getType())->getNumElements()
2477 cast<ArrayType>(RHS->getType())->getNumElements();
2480 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2481 // The logic here should be correct for any real-world personality function.
2482 // However if that turns out not to be true, the offending logic can always
2483 // be conditioned on the personality function, like the catch-all logic is.
2484 EHPersonality Personality =
2485 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2487 // Simplify the list of clauses, eg by removing repeated catch clauses
2488 // (these are often created by inlining).
2489 bool MakeNewInstruction = false; // If true, recreate using the following:
2490 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2491 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2493 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2494 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2495 bool isLastClause = i + 1 == e;
2496 if (LI.isCatch(i)) {
2498 Constant *CatchClause = LI.getClause(i);
2499 Constant *TypeInfo = CatchClause->stripPointerCasts();
2501 // If we already saw this clause, there is no point in having a second
2503 if (AlreadyCaught.insert(TypeInfo).second) {
2504 // This catch clause was not already seen.
2505 NewClauses.push_back(CatchClause);
2507 // Repeated catch clause - drop the redundant copy.
2508 MakeNewInstruction = true;
2511 // If this is a catch-all then there is no point in keeping any following
2512 // clauses or marking the landingpad as having a cleanup.
2513 if (isCatchAll(Personality, TypeInfo)) {
2515 MakeNewInstruction = true;
2516 CleanupFlag = false;
2520 // A filter clause. If any of the filter elements were already caught
2521 // then they can be dropped from the filter. It is tempting to try to
2522 // exploit the filter further by saying that any typeinfo that does not
2523 // occur in the filter can't be caught later (and thus can be dropped).
2524 // However this would be wrong, since typeinfos can match without being
2525 // equal (for example if one represents a C++ class, and the other some
2526 // class derived from it).
2527 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2528 Constant *FilterClause = LI.getClause(i);
2529 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2530 unsigned NumTypeInfos = FilterType->getNumElements();
2532 // An empty filter catches everything, so there is no point in keeping any
2533 // following clauses or marking the landingpad as having a cleanup. By
2534 // dealing with this case here the following code is made a bit simpler.
2535 if (!NumTypeInfos) {
2536 NewClauses.push_back(FilterClause);
2538 MakeNewInstruction = true;
2539 CleanupFlag = false;
2543 bool MakeNewFilter = false; // If true, make a new filter.
2544 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2545 if (isa<ConstantAggregateZero>(FilterClause)) {
2546 // Not an empty filter - it contains at least one null typeinfo.
2547 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2548 Constant *TypeInfo =
2549 Constant::getNullValue(FilterType->getElementType());
2550 // If this typeinfo is a catch-all then the filter can never match.
2551 if (isCatchAll(Personality, TypeInfo)) {
2552 // Throw the filter away.
2553 MakeNewInstruction = true;
2557 // There is no point in having multiple copies of this typeinfo, so
2558 // discard all but the first copy if there is more than one.
2559 NewFilterElts.push_back(TypeInfo);
2560 if (NumTypeInfos > 1)
2561 MakeNewFilter = true;
2563 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2564 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2565 NewFilterElts.reserve(NumTypeInfos);
2567 // Remove any filter elements that were already caught or that already
2568 // occurred in the filter. While there, see if any of the elements are
2569 // catch-alls. If so, the filter can be discarded.
2570 bool SawCatchAll = false;
2571 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2572 Constant *Elt = Filter->getOperand(j);
2573 Constant *TypeInfo = Elt->stripPointerCasts();
2574 if (isCatchAll(Personality, TypeInfo)) {
2575 // This element is a catch-all. Bail out, noting this fact.
2580 // Even if we've seen a type in a catch clause, we don't want to
2581 // remove it from the filter. An unexpected type handler may be
2582 // set up for a call site which throws an exception of the same
2583 // type caught. In order for the exception thrown by the unexpected
2584 // handler to propagate correctly, the filter must be correctly
2585 // described for the call site.
2589 // void unexpected() { throw 1;}
2590 // void foo() throw (int) {
2591 // std::set_unexpected(unexpected);
2594 // } catch (int i) {}
2597 // There is no point in having multiple copies of the same typeinfo in
2598 // a filter, so only add it if we didn't already.
2599 if (SeenInFilter.insert(TypeInfo).second)
2600 NewFilterElts.push_back(cast<Constant>(Elt));
2602 // A filter containing a catch-all cannot match anything by definition.
2604 // Throw the filter away.
2605 MakeNewInstruction = true;
2609 // If we dropped something from the filter, make a new one.
2610 if (NewFilterElts.size() < NumTypeInfos)
2611 MakeNewFilter = true;
2613 if (MakeNewFilter) {
2614 FilterType = ArrayType::get(FilterType->getElementType(),
2615 NewFilterElts.size());
2616 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2617 MakeNewInstruction = true;
2620 NewClauses.push_back(FilterClause);
2622 // If the new filter is empty then it will catch everything so there is
2623 // no point in keeping any following clauses or marking the landingpad
2624 // as having a cleanup. The case of the original filter being empty was
2625 // already handled above.
2626 if (MakeNewFilter && !NewFilterElts.size()) {
2627 assert(MakeNewInstruction && "New filter but not a new instruction!");
2628 CleanupFlag = false;
2634 // If several filters occur in a row then reorder them so that the shortest
2635 // filters come first (those with the smallest number of elements). This is
2636 // advantageous because shorter filters are more likely to match, speeding up
2637 // unwinding, but mostly because it increases the effectiveness of the other
2638 // filter optimizations below.
2639 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2641 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2642 for (j = i; j != e; ++j)
2643 if (!isa<ArrayType>(NewClauses[j]->getType()))
2646 // Check whether the filters are already sorted by length. We need to know
2647 // if sorting them is actually going to do anything so that we only make a
2648 // new landingpad instruction if it does.
2649 for (unsigned k = i; k + 1 < j; ++k)
2650 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2651 // Not sorted, so sort the filters now. Doing an unstable sort would be
2652 // correct too but reordering filters pointlessly might confuse users.
2653 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2655 MakeNewInstruction = true;
2659 // Look for the next batch of filters.
2663 // If typeinfos matched if and only if equal, then the elements of a filter L
2664 // that occurs later than a filter F could be replaced by the intersection of
2665 // the elements of F and L. In reality two typeinfos can match without being
2666 // equal (for example if one represents a C++ class, and the other some class
2667 // derived from it) so it would be wrong to perform this transform in general.
2668 // However the transform is correct and useful if F is a subset of L. In that
2669 // case L can be replaced by F, and thus removed altogether since repeating a
2670 // filter is pointless. So here we look at all pairs of filters F and L where
2671 // L follows F in the list of clauses, and remove L if every element of F is
2672 // an element of L. This can occur when inlining C++ functions with exception
2674 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2675 // Examine each filter in turn.
2676 Value *Filter = NewClauses[i];
2677 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2679 // Not a filter - skip it.
2681 unsigned FElts = FTy->getNumElements();
2682 // Examine each filter following this one. Doing this backwards means that
2683 // we don't have to worry about filters disappearing under us when removed.
2684 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2685 Value *LFilter = NewClauses[j];
2686 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2688 // Not a filter - skip it.
2690 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2691 // an element of LFilter, then discard LFilter.
2692 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2693 // If Filter is empty then it is a subset of LFilter.
2696 NewClauses.erase(J);
2697 MakeNewInstruction = true;
2698 // Move on to the next filter.
2701 unsigned LElts = LTy->getNumElements();
2702 // If Filter is longer than LFilter then it cannot be a subset of it.
2704 // Move on to the next filter.
2706 // At this point we know that LFilter has at least one element.
2707 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2708 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2709 // already know that Filter is not longer than LFilter).
2710 if (isa<ConstantAggregateZero>(Filter)) {
2711 assert(FElts <= LElts && "Should have handled this case earlier!");
2713 NewClauses.erase(J);
2714 MakeNewInstruction = true;
2716 // Move on to the next filter.
2719 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2720 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2721 // Since Filter is non-empty and contains only zeros, it is a subset of
2722 // LFilter iff LFilter contains a zero.
2723 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2724 for (unsigned l = 0; l != LElts; ++l)
2725 if (LArray->getOperand(l)->isNullValue()) {
2726 // LFilter contains a zero - discard it.
2727 NewClauses.erase(J);
2728 MakeNewInstruction = true;
2731 // Move on to the next filter.
2734 // At this point we know that both filters are ConstantArrays. Loop over
2735 // operands to see whether every element of Filter is also an element of
2736 // LFilter. Since filters tend to be short this is probably faster than
2737 // using a method that scales nicely.
2738 ConstantArray *FArray = cast<ConstantArray>(Filter);
2739 bool AllFound = true;
2740 for (unsigned f = 0; f != FElts; ++f) {
2741 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2743 for (unsigned l = 0; l != LElts; ++l) {
2744 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2745 if (LTypeInfo == FTypeInfo) {
2755 NewClauses.erase(J);
2756 MakeNewInstruction = true;
2758 // Move on to the next filter.
2762 // If we changed any of the clauses, replace the old landingpad instruction
2764 if (MakeNewInstruction) {
2765 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2767 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2768 NLI->addClause(NewClauses[i]);
2769 // A landing pad with no clauses must have the cleanup flag set. It is
2770 // theoretically possible, though highly unlikely, that we eliminated all
2771 // clauses. If so, force the cleanup flag to true.
2772 if (NewClauses.empty())
2774 NLI->setCleanup(CleanupFlag);
2778 // Even if none of the clauses changed, we may nonetheless have understood
2779 // that the cleanup flag is pointless. Clear it if so.
2780 if (LI.isCleanup() != CleanupFlag) {
2781 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2782 LI.setCleanup(CleanupFlag);
2789 /// Try to move the specified instruction from its current block into the
2790 /// beginning of DestBlock, which can only happen if it's safe to move the
2791 /// instruction past all of the instructions between it and the end of its
2793 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2794 assert(I->hasOneUse() && "Invariants didn't hold!");
2796 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2797 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2798 isa<TerminatorInst>(I))
2801 // Do not sink alloca instructions out of the entry block.
2802 if (isa<AllocaInst>(I) && I->getParent() ==
2803 &DestBlock->getParent()->getEntryBlock())
2806 // Do not sink into catchswitch blocks.
2807 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2810 // Do not sink convergent call instructions.
2811 if (auto *CI = dyn_cast<CallInst>(I)) {
2812 if (CI->isConvergent())
2815 // We can only sink load instructions if there is nothing between the load and
2816 // the end of block that could change the value.
2817 if (I->mayReadFromMemory()) {
2818 for (BasicBlock::iterator Scan = I->getIterator(),
2819 E = I->getParent()->end();
2821 if (Scan->mayWriteToMemory())
2825 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2826 I->moveBefore(&*InsertPos);
2831 bool InstCombiner::run() {
2832 while (!Worklist.isEmpty()) {
2833 Instruction *I = Worklist.RemoveOne();
2834 if (I == nullptr) continue; // skip null values.
2836 // Check to see if we can DCE the instruction.
2837 if (isInstructionTriviallyDead(I, &TLI)) {
2838 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2839 eraseInstFromFunction(*I);
2841 MadeIRChange = true;
2845 // Instruction isn't dead, see if we can constant propagate it.
2846 if (!I->use_empty() &&
2847 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2848 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2849 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2851 // Add operands to the worklist.
2852 replaceInstUsesWith(*I, C);
2854 if (isInstructionTriviallyDead(I, &TLI))
2855 eraseInstFromFunction(*I);
2856 MadeIRChange = true;
2861 // In general, it is possible for computeKnownBits to determine all bits in
2862 // a value even when the operands are not all constants.
2863 Type *Ty = I->getType();
2864 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2865 unsigned BitWidth = Ty->getScalarSizeInBits();
2866 KnownBits Known(BitWidth);
2867 computeKnownBits(I, Known, /*Depth*/0, I);
2868 if ((Known.Zero | Known.One).isAllOnesValue()) {
2869 Constant *C = ConstantInt::get(Ty, Known.One);
2870 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2871 " from: " << *I << '\n');
2873 // Add operands to the worklist.
2874 replaceInstUsesWith(*I, C);
2876 if (isInstructionTriviallyDead(I, &TLI))
2877 eraseInstFromFunction(*I);
2878 MadeIRChange = true;
2883 // See if we can trivially sink this instruction to a successor basic block.
2884 if (I->hasOneUse()) {
2885 BasicBlock *BB = I->getParent();
2886 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2887 BasicBlock *UserParent;
2889 // Get the block the use occurs in.
2890 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2891 UserParent = PN->getIncomingBlock(*I->use_begin());
2893 UserParent = UserInst->getParent();
2895 if (UserParent != BB) {
2896 bool UserIsSuccessor = false;
2897 // See if the user is one of our successors.
2898 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2899 if (*SI == UserParent) {
2900 UserIsSuccessor = true;
2904 // If the user is one of our immediate successors, and if that successor
2905 // only has us as a predecessors (we'd have to split the critical edge
2906 // otherwise), we can keep going.
2907 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
2908 // Okay, the CFG is simple enough, try to sink this instruction.
2909 if (TryToSinkInstruction(I, UserParent)) {
2910 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
2911 MadeIRChange = true;
2912 // We'll add uses of the sunk instruction below, but since sinking
2913 // can expose opportunities for it's *operands* add them to the
2915 for (Use &U : I->operands())
2916 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2923 // Now that we have an instruction, try combining it to simplify it.
2924 Builder->SetInsertPoint(I);
2925 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2930 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2931 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2933 if (Instruction *Result = visit(*I)) {
2935 // Should we replace the old instruction with a new one?
2937 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2938 << " New = " << *Result << '\n');
2940 if (I->getDebugLoc())
2941 Result->setDebugLoc(I->getDebugLoc());
2942 // Everything uses the new instruction now.
2943 I->replaceAllUsesWith(Result);
2945 // Move the name to the new instruction first.
2946 Result->takeName(I);
2948 // Push the new instruction and any users onto the worklist.
2949 Worklist.AddUsersToWorkList(*Result);
2950 Worklist.Add(Result);
2952 // Insert the new instruction into the basic block...
2953 BasicBlock *InstParent = I->getParent();
2954 BasicBlock::iterator InsertPos = I->getIterator();
2956 // If we replace a PHI with something that isn't a PHI, fix up the
2958 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2959 InsertPos = InstParent->getFirstInsertionPt();
2961 InstParent->getInstList().insert(InsertPos, Result);
2963 eraseInstFromFunction(*I);
2965 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2966 << " New = " << *I << '\n');
2968 // If the instruction was modified, it's possible that it is now dead.
2969 // if so, remove it.
2970 if (isInstructionTriviallyDead(I, &TLI)) {
2971 eraseInstFromFunction(*I);
2973 Worklist.AddUsersToWorkList(*I);
2977 MadeIRChange = true;
2982 return MadeIRChange;
2985 /// Walk the function in depth-first order, adding all reachable code to the
2988 /// This has a couple of tricks to make the code faster and more powerful. In
2989 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2990 /// them to the worklist (this significantly speeds up instcombine on code where
2991 /// many instructions are dead or constant). Additionally, if we find a branch
2992 /// whose condition is a known constant, we only visit the reachable successors.
2994 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2995 SmallPtrSetImpl<BasicBlock *> &Visited,
2996 InstCombineWorklist &ICWorklist,
2997 const TargetLibraryInfo *TLI) {
2998 bool MadeIRChange = false;
2999 SmallVector<BasicBlock*, 256> Worklist;
3000 Worklist.push_back(BB);
3002 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3003 DenseMap<Constant *, Constant *> FoldedConstants;
3006 BB = Worklist.pop_back_val();
3008 // We have now visited this block! If we've already been here, ignore it.
3009 if (!Visited.insert(BB).second)
3012 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3013 Instruction *Inst = &*BBI++;
3015 // DCE instruction if trivially dead.
3016 if (isInstructionTriviallyDead(Inst, TLI)) {
3018 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3019 Inst->eraseFromParent();
3023 // ConstantProp instruction if trivially constant.
3024 if (!Inst->use_empty() &&
3025 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3026 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3027 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3029 Inst->replaceAllUsesWith(C);
3031 if (isInstructionTriviallyDead(Inst, TLI))
3032 Inst->eraseFromParent();
3036 // See if we can constant fold its operands.
3037 for (Use &U : Inst->operands()) {
3038 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3041 auto *C = cast<Constant>(U);
3042 Constant *&FoldRes = FoldedConstants[C];
3044 FoldRes = ConstantFoldConstant(C, DL, TLI);
3049 DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3050 << "\n Old = " << *C
3051 << "\n New = " << *FoldRes << '\n');
3053 MadeIRChange = true;
3057 InstrsForInstCombineWorklist.push_back(Inst);
3060 // Recursively visit successors. If this is a branch or switch on a
3061 // constant, only visit the reachable successor.
3062 TerminatorInst *TI = BB->getTerminator();
3063 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3064 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3065 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3066 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3067 Worklist.push_back(ReachableBB);
3070 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3071 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3072 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3077 for (BasicBlock *SuccBB : TI->successors())
3078 Worklist.push_back(SuccBB);
3079 } while (!Worklist.empty());
3081 // Once we've found all of the instructions to add to instcombine's worklist,
3082 // add them in reverse order. This way instcombine will visit from the top
3083 // of the function down. This jives well with the way that it adds all uses
3084 // of instructions to the worklist after doing a transformation, thus avoiding
3085 // some N^2 behavior in pathological cases.
3086 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3088 return MadeIRChange;
3091 /// \brief Populate the IC worklist from a function, and prune any dead basic
3092 /// blocks discovered in the process.
3094 /// This also does basic constant propagation and other forward fixing to make
3095 /// the combiner itself run much faster.
3096 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3097 TargetLibraryInfo *TLI,
3098 InstCombineWorklist &ICWorklist) {
3099 bool MadeIRChange = false;
3101 // Do a depth-first traversal of the function, populate the worklist with
3102 // the reachable instructions. Ignore blocks that are not reachable. Keep
3103 // track of which blocks we visit.
3104 SmallPtrSet<BasicBlock *, 32> Visited;
3106 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3108 // Do a quick scan over the function. If we find any blocks that are
3109 // unreachable, remove any instructions inside of them. This prevents
3110 // the instcombine code from having to deal with some bad special cases.
3111 for (BasicBlock &BB : F) {
3112 if (Visited.count(&BB))
3115 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3116 MadeIRChange |= NumDeadInstInBB > 0;
3117 NumDeadInst += NumDeadInstInBB;
3120 return MadeIRChange;
3124 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3125 AliasAnalysis *AA, AssumptionCache &AC,
3126 TargetLibraryInfo &TLI, DominatorTree &DT,
3127 bool ExpensiveCombines = true,
3128 LoopInfo *LI = nullptr) {
3129 auto &DL = F.getParent()->getDataLayout();
3130 ExpensiveCombines |= EnableExpensiveCombines;
3132 /// Builder - This is an IRBuilder that automatically inserts new
3133 /// instructions into the worklist when they are created.
3134 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3135 F.getContext(), TargetFolder(DL),
3136 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3139 using namespace llvm::PatternMatch;
3140 if (match(I, m_Intrinsic<Intrinsic::assume>()))
3141 AC.registerAssumption(cast<CallInst>(I));
3144 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3146 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3148 // Iterate while there is work to do.
3152 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3153 << F.getName() << "\n");
3155 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3157 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
3158 AA, AC, TLI, DT, DL, LI);
3159 IC.MaxArraySizeForCombine = MaxArraySize;
3160 Changed |= IC.run();
3166 return DbgDeclaresChanged || Iteration > 1;
3169 PreservedAnalyses InstCombinePass::run(Function &F,
3170 FunctionAnalysisManager &AM) {
3171 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3172 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3173 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3175 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3177 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3178 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3179 ExpensiveCombines, LI))
3180 // No changes, all analyses are preserved.
3181 return PreservedAnalyses::all();
3183 // Mark all the analyses that instcombine updates as preserved.
3184 PreservedAnalyses PA;
3185 PA.preserveSet<CFGAnalyses>();
3186 PA.preserve<AAManager>();
3187 PA.preserve<GlobalsAA>();
3191 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3192 AU.setPreservesCFG();
3193 AU.addRequired<AAResultsWrapperPass>();
3194 AU.addRequired<AssumptionCacheTracker>();
3195 AU.addRequired<TargetLibraryInfoWrapperPass>();
3196 AU.addRequired<DominatorTreeWrapperPass>();
3197 AU.addPreserved<DominatorTreeWrapperPass>();
3198 AU.addPreserved<AAResultsWrapperPass>();
3199 AU.addPreserved<BasicAAWrapperPass>();
3200 AU.addPreserved<GlobalsAAWrapperPass>();
3203 bool InstructionCombiningPass::runOnFunction(Function &F) {
3204 if (skipFunction(F))
3207 // Required analyses.
3208 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3209 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3210 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3211 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3213 // Optional analyses.
3214 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3215 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3217 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3218 ExpensiveCombines, LI);
3221 char InstructionCombiningPass::ID = 0;
3222 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3223 "Combine redundant instructions", false, false)
3224 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3225 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3226 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3227 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3228 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3229 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3230 "Combine redundant instructions", false, false)
3232 // Initialization Routines
3233 void llvm::initializeInstCombine(PassRegistry &Registry) {
3234 initializeInstructionCombiningPassPass(Registry);
3237 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3238 initializeInstructionCombiningPassPass(*unwrap(R));
3241 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3242 return new InstructionCombiningPass(ExpensiveCombines);