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/Scalar.h"
37 #include "InstCombine.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/AssumptionTracker.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/IR/CFG.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/GetElementPtrTypeIterator.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/PatternMatch.h"
52 #include "llvm/IR/ValueHandle.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Target/TargetLibraryInfo.h"
56 #include "llvm/Transforms/Utils/Local.h"
60 using namespace llvm::PatternMatch;
62 #define DEBUG_TYPE "instcombine"
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68 STATISTIC(NumExpand, "Number of expansions");
69 STATISTIC(NumFactor , "Number of factorizations");
70 STATISTIC(NumReassoc , "Number of reassociations");
72 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
74 cl::desc("Enable unsafe double to float "
75 "shrinking for math lib calls"));
77 // Initialization Routines
78 void llvm::initializeInstCombine(PassRegistry &Registry) {
79 initializeInstCombinerPass(Registry);
82 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
83 initializeInstCombine(*unwrap(R));
86 char InstCombiner::ID = 0;
87 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
88 "Combine redundant instructions", false, false)
89 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
90 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
91 INITIALIZE_PASS_END(InstCombiner, "instcombine",
92 "Combine redundant instructions", false, false)
94 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<AssumptionTracker>();
97 AU.addRequired<TargetLibraryInfo>();
101 Value *InstCombiner::EmitGEPOffset(User *GEP) {
102 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
105 /// ShouldChangeType - Return true if it is desirable to convert a computation
106 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
107 /// type for example, or from a smaller to a larger illegal type.
108 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
109 assert(From->isIntegerTy() && To->isIntegerTy());
111 // If we don't have DL, we don't know if the source/dest are legal.
112 if (!DL) return false;
114 unsigned FromWidth = From->getPrimitiveSizeInBits();
115 unsigned ToWidth = To->getPrimitiveSizeInBits();
116 bool FromLegal = DL->isLegalInteger(FromWidth);
117 bool ToLegal = DL->isLegalInteger(ToWidth);
119 // If this is a legal integer from type, and the result would be an illegal
120 // type, don't do the transformation.
121 if (FromLegal && !ToLegal)
124 // Otherwise, if both are illegal, do not increase the size of the result. We
125 // do allow things like i160 -> i64, but not i64 -> i160.
126 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
132 // Return true, if No Signed Wrap should be maintained for I.
133 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
134 // where both B and C should be ConstantInts, results in a constant that does
135 // not overflow. This function only handles the Add and Sub opcodes. For
136 // all other opcodes, the function conservatively returns false.
137 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
138 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
139 if (!OBO || !OBO->hasNoSignedWrap()) {
143 // We reason about Add and Sub Only.
144 Instruction::BinaryOps Opcode = I.getOpcode();
145 if (Opcode != Instruction::Add &&
146 Opcode != Instruction::Sub) {
150 ConstantInt *CB = dyn_cast<ConstantInt>(B);
151 ConstantInt *CC = dyn_cast<ConstantInt>(C);
157 const APInt &BVal = CB->getValue();
158 const APInt &CVal = CC->getValue();
159 bool Overflow = false;
161 if (Opcode == Instruction::Add) {
162 BVal.sadd_ov(CVal, Overflow);
164 BVal.ssub_ov(CVal, Overflow);
170 /// Conservatively clears subclassOptionalData after a reassociation or
171 /// commutation. We preserve fast-math flags when applicable as they can be
173 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
174 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
176 I.clearSubclassOptionalData();
180 FastMathFlags FMF = I.getFastMathFlags();
181 I.clearSubclassOptionalData();
182 I.setFastMathFlags(FMF);
185 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
186 /// operators which are associative or commutative:
188 // Commutative operators:
190 // 1. Order operands such that they are listed from right (least complex) to
191 // left (most complex). This puts constants before unary operators before
194 // Associative operators:
196 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
197 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
199 // Associative and commutative operators:
201 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
202 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
203 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
204 // if C1 and C2 are constants.
206 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
207 Instruction::BinaryOps Opcode = I.getOpcode();
208 bool Changed = false;
211 // Order operands such that they are listed from right (least complex) to
212 // left (most complex). This puts constants before unary operators before
214 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
215 getComplexity(I.getOperand(1)))
216 Changed = !I.swapOperands();
218 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
219 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
221 if (I.isAssociative()) {
222 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
223 if (Op0 && Op0->getOpcode() == Opcode) {
224 Value *A = Op0->getOperand(0);
225 Value *B = Op0->getOperand(1);
226 Value *C = I.getOperand(1);
228 // Does "B op C" simplify?
229 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
230 // It simplifies to V. Form "A op V".
233 // Conservatively clear the optional flags, since they may not be
234 // preserved by the reassociation.
235 if (MaintainNoSignedWrap(I, B, C) &&
236 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
237 // Note: this is only valid because SimplifyBinOp doesn't look at
238 // the operands to Op0.
239 I.clearSubclassOptionalData();
240 I.setHasNoSignedWrap(true);
242 ClearSubclassDataAfterReassociation(I);
251 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
252 if (Op1 && Op1->getOpcode() == Opcode) {
253 Value *A = I.getOperand(0);
254 Value *B = Op1->getOperand(0);
255 Value *C = Op1->getOperand(1);
257 // Does "A op B" simplify?
258 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
259 // It simplifies to V. Form "V op C".
262 // Conservatively clear the optional flags, since they may not be
263 // preserved by the reassociation.
264 ClearSubclassDataAfterReassociation(I);
272 if (I.isAssociative() && I.isCommutative()) {
273 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
274 if (Op0 && Op0->getOpcode() == Opcode) {
275 Value *A = Op0->getOperand(0);
276 Value *B = Op0->getOperand(1);
277 Value *C = I.getOperand(1);
279 // Does "C op A" simplify?
280 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
281 // It simplifies to V. Form "V op B".
284 // Conservatively clear the optional flags, since they may not be
285 // preserved by the reassociation.
286 ClearSubclassDataAfterReassociation(I);
293 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
294 if (Op1 && Op1->getOpcode() == Opcode) {
295 Value *A = I.getOperand(0);
296 Value *B = Op1->getOperand(0);
297 Value *C = Op1->getOperand(1);
299 // Does "C op A" simplify?
300 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
301 // It simplifies to V. Form "B op V".
304 // Conservatively clear the optional flags, since they may not be
305 // preserved by the reassociation.
306 ClearSubclassDataAfterReassociation(I);
313 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
314 // if C1 and C2 are constants.
316 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
317 isa<Constant>(Op0->getOperand(1)) &&
318 isa<Constant>(Op1->getOperand(1)) &&
319 Op0->hasOneUse() && Op1->hasOneUse()) {
320 Value *A = Op0->getOperand(0);
321 Constant *C1 = cast<Constant>(Op0->getOperand(1));
322 Value *B = Op1->getOperand(0);
323 Constant *C2 = cast<Constant>(Op1->getOperand(1));
325 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
326 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
327 if (isa<FPMathOperator>(New)) {
328 FastMathFlags Flags = I.getFastMathFlags();
329 Flags &= Op0->getFastMathFlags();
330 Flags &= Op1->getFastMathFlags();
331 New->setFastMathFlags(Flags);
333 InsertNewInstWith(New, I);
335 I.setOperand(0, New);
336 I.setOperand(1, Folded);
337 // Conservatively clear the optional flags, since they may not be
338 // preserved by the reassociation.
339 ClearSubclassDataAfterReassociation(I);
346 // No further simplifications.
351 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
352 /// "(X LOp Y) ROp (X LOp Z)".
353 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
354 Instruction::BinaryOps ROp) {
359 case Instruction::And:
360 // And distributes over Or and Xor.
364 case Instruction::Or:
365 case Instruction::Xor:
369 case Instruction::Mul:
370 // Multiplication distributes over addition and subtraction.
374 case Instruction::Add:
375 case Instruction::Sub:
379 case Instruction::Or:
380 // Or distributes over And.
384 case Instruction::And:
390 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
391 /// "(X ROp Z) LOp (Y ROp Z)".
392 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
393 Instruction::BinaryOps ROp) {
394 if (Instruction::isCommutative(ROp))
395 return LeftDistributesOverRight(ROp, LOp);
400 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
401 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
402 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
403 case Instruction::And:
404 case Instruction::Or:
405 case Instruction::Xor:
409 case Instruction::Shl:
410 case Instruction::LShr:
411 case Instruction::AShr:
415 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
416 // but this requires knowing that the addition does not overflow and other
421 /// This function returns identity value for given opcode, which can be used to
422 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
423 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
424 if (isa<Constant>(V))
427 if (OpCode == Instruction::Mul)
428 return ConstantInt::get(V->getType(), 1);
430 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
435 /// This function factors binary ops which can be combined using distributive
436 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
437 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
438 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
439 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
441 static Instruction::BinaryOps
442 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
443 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
445 return Instruction::BinaryOpsEnd;
447 LHS = Op->getOperand(0);
448 RHS = Op->getOperand(1);
450 switch (TopLevelOpcode) {
452 return Op->getOpcode();
454 case Instruction::Add:
455 case Instruction::Sub:
456 if (Op->getOpcode() == Instruction::Shl) {
457 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
458 // The multiplier is really 1 << CST.
459 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
460 return Instruction::Mul;
463 return Op->getOpcode();
466 // TODO: We can add other conversions e.g. shr => div etc.
469 /// This tries to simplify binary operations by factorizing out common terms
470 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
471 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
472 const DataLayout *DL, BinaryOperator &I,
473 Instruction::BinaryOps InnerOpcode, Value *A,
474 Value *B, Value *C, Value *D) {
476 // If any of A, B, C, D are null, we can not factor I, return early.
477 // Checking A and C should be enough.
478 if (!A || !C || !B || !D)
481 Value *SimplifiedInst = nullptr;
482 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
483 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
485 // Does "X op' Y" always equal "Y op' X"?
486 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
488 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
489 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
490 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
491 // commutative case, "(A op' B) op (C op' A)"?
492 if (A == C || (InnerCommutative && A == D)) {
495 // Consider forming "A op' (B op D)".
496 // If "B op D" simplifies then it can be formed with no cost.
497 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
498 // If "B op D" doesn't simplify then only go on if both of the existing
499 // operations "A op' B" and "C op' D" will be zapped as no longer used.
500 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
501 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
503 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
507 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
508 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
509 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
510 // commutative case, "(A op' B) op (B op' D)"?
511 if (B == D || (InnerCommutative && B == C)) {
514 // Consider forming "(A op C) op' B".
515 // If "A op C" simplifies then it can be formed with no cost.
516 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
518 // If "A op C" doesn't simplify then only go on if both of the existing
519 // operations "A op' B" and "C op' D" will be zapped as no longer used.
520 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
521 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
523 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
527 if (SimplifiedInst) {
529 SimplifiedInst->takeName(&I);
531 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
532 // TODO: Check for NUW.
533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
534 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
536 if (isa<OverflowingBinaryOperator>(&I))
537 HasNSW = I.hasNoSignedWrap();
539 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
540 if (isa<OverflowingBinaryOperator>(Op0))
541 HasNSW &= Op0->hasNoSignedWrap();
543 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
544 if (isa<OverflowingBinaryOperator>(Op1))
545 HasNSW &= Op1->hasNoSignedWrap();
546 BO->setHasNoSignedWrap(HasNSW);
550 return SimplifiedInst;
553 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
554 /// which some other binary operation distributes over either by factorizing
555 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
556 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
557 /// a win). Returns the simplified value, or null if it didn't simplify.
558 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
560 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
561 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
564 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
565 auto TopLevelOpcode = I.getOpcode();
566 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
567 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
569 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
571 if (LHSOpcode == RHSOpcode) {
572 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
576 // The instruction has the form "(A op' B) op (C)". Try to factorize common
578 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
579 getIdentityValue(LHSOpcode, RHS)))
582 // The instruction has the form "(B) op (C op' D)". Try to factorize common
584 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
585 getIdentityValue(RHSOpcode, LHS), C, D))
589 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
590 // The instruction has the form "(A op' B) op C". See if expanding it out
591 // to "(A op C) op' (B op C)" results in simplifications.
592 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
593 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
595 // Do "A op C" and "B op C" both simplify?
596 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
597 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
598 // They do! Return "L op' R".
600 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
601 if ((L == A && R == B) ||
602 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
604 // Otherwise return "L op' R" if it simplifies.
605 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
607 // Otherwise, create a new instruction.
608 C = Builder->CreateBinOp(InnerOpcode, L, R);
614 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
615 // The instruction has the form "A op (B op' C)". See if expanding it out
616 // to "(A op B) op' (A op C)" results in simplifications.
617 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
618 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
620 // Do "A op B" and "A op C" both simplify?
621 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
622 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
623 // They do! Return "L op' R".
625 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
626 if ((L == B && R == C) ||
627 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
629 // Otherwise return "L op' R" if it simplifies.
630 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
632 // Otherwise, create a new instruction.
633 A = Builder->CreateBinOp(InnerOpcode, L, R);
642 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
643 // if the LHS is a constant zero (which is the 'negate' form).
645 Value *InstCombiner::dyn_castNegVal(Value *V) const {
646 if (BinaryOperator::isNeg(V))
647 return BinaryOperator::getNegArgument(V);
649 // Constants can be considered to be negated values if they can be folded.
650 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
651 return ConstantExpr::getNeg(C);
653 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
654 if (C->getType()->getElementType()->isIntegerTy())
655 return ConstantExpr::getNeg(C);
660 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
661 // instruction if the LHS is a constant negative zero (which is the 'negate'
664 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
665 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
666 return BinaryOperator::getFNegArgument(V);
668 // Constants can be considered to be negated values if they can be folded.
669 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
670 return ConstantExpr::getFNeg(C);
672 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
673 if (C->getType()->getElementType()->isFloatingPointTy())
674 return ConstantExpr::getFNeg(C);
679 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
681 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
682 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
685 // Figure out if the constant is the left or the right argument.
686 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
687 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
689 if (Constant *SOC = dyn_cast<Constant>(SO)) {
691 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
692 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
695 Value *Op0 = SO, *Op1 = ConstOperand;
699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
700 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
701 SO->getName()+".op");
702 Instruction *FPInst = dyn_cast<Instruction>(RI);
703 if (FPInst && isa<FPMathOperator>(FPInst))
704 FPInst->copyFastMathFlags(BO);
707 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
708 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
709 SO->getName()+".cmp");
710 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
711 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
712 SO->getName()+".cmp");
713 llvm_unreachable("Unknown binary instruction type!");
716 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
717 // constant as the other operand, try to fold the binary operator into the
718 // select arguments. This also works for Cast instructions, which obviously do
719 // not have a second operand.
720 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
721 // Don't modify shared select instructions
722 if (!SI->hasOneUse()) return nullptr;
723 Value *TV = SI->getOperand(1);
724 Value *FV = SI->getOperand(2);
726 if (isa<Constant>(TV) || isa<Constant>(FV)) {
727 // Bool selects with constant operands can be folded to logical ops.
728 if (SI->getType()->isIntegerTy(1)) return nullptr;
730 // If it's a bitcast involving vectors, make sure it has the same number of
731 // elements on both sides.
732 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
733 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
734 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
736 // Verify that either both or neither are vectors.
737 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
738 // If vectors, verify that they have the same number of elements.
739 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
743 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
744 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
746 return SelectInst::Create(SI->getCondition(),
747 SelectTrueVal, SelectFalseVal);
753 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
754 /// has a PHI node as operand #0, see if we can fold the instruction into the
755 /// PHI (which is only possible if all operands to the PHI are constants).
757 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
758 PHINode *PN = cast<PHINode>(I.getOperand(0));
759 unsigned NumPHIValues = PN->getNumIncomingValues();
760 if (NumPHIValues == 0)
763 // We normally only transform phis with a single use. However, if a PHI has
764 // multiple uses and they are all the same operation, we can fold *all* of the
765 // uses into the PHI.
766 if (!PN->hasOneUse()) {
767 // Walk the use list for the instruction, comparing them to I.
768 for (User *U : PN->users()) {
769 Instruction *UI = cast<Instruction>(U);
770 if (UI != &I && !I.isIdenticalTo(UI))
773 // Otherwise, we can replace *all* users with the new PHI we form.
776 // Check to see if all of the operands of the PHI are simple constants
777 // (constantint/constantfp/undef). If there is one non-constant value,
778 // remember the BB it is in. If there is more than one or if *it* is a PHI,
779 // bail out. We don't do arbitrary constant expressions here because moving
780 // their computation can be expensive without a cost model.
781 BasicBlock *NonConstBB = nullptr;
782 for (unsigned i = 0; i != NumPHIValues; ++i) {
783 Value *InVal = PN->getIncomingValue(i);
784 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
787 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
788 if (NonConstBB) return nullptr; // More than one non-const value.
790 NonConstBB = PN->getIncomingBlock(i);
792 // If the InVal is an invoke at the end of the pred block, then we can't
793 // insert a computation after it without breaking the edge.
794 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
795 if (II->getParent() == NonConstBB)
798 // If the incoming non-constant value is in I's block, we will remove one
799 // instruction, but insert another equivalent one, leading to infinite
801 if (NonConstBB == I.getParent())
805 // If there is exactly one non-constant value, we can insert a copy of the
806 // operation in that block. However, if this is a critical edge, we would be
807 // inserting the computation one some other paths (e.g. inside a loop). Only
808 // do this if the pred block is unconditionally branching into the phi block.
809 if (NonConstBB != nullptr) {
810 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
811 if (!BI || !BI->isUnconditional()) return nullptr;
814 // Okay, we can do the transformation: create the new PHI node.
815 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
816 InsertNewInstBefore(NewPN, *PN);
819 // If we are going to have to insert a new computation, do so right before the
820 // predecessors terminator.
822 Builder->SetInsertPoint(NonConstBB->getTerminator());
824 // Next, add all of the operands to the PHI.
825 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
826 // We only currently try to fold the condition of a select when it is a phi,
827 // not the true/false values.
828 Value *TrueV = SI->getTrueValue();
829 Value *FalseV = SI->getFalseValue();
830 BasicBlock *PhiTransBB = PN->getParent();
831 for (unsigned i = 0; i != NumPHIValues; ++i) {
832 BasicBlock *ThisBB = PN->getIncomingBlock(i);
833 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
834 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
835 Value *InV = nullptr;
836 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
837 // even if currently isNullValue gives false.
838 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
839 if (InC && !isa<ConstantExpr>(InC))
840 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
842 InV = Builder->CreateSelect(PN->getIncomingValue(i),
843 TrueVInPred, FalseVInPred, "phitmp");
844 NewPN->addIncoming(InV, ThisBB);
846 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
847 Constant *C = cast<Constant>(I.getOperand(1));
848 for (unsigned i = 0; i != NumPHIValues; ++i) {
849 Value *InV = nullptr;
850 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
851 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
852 else if (isa<ICmpInst>(CI))
853 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
856 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
858 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
860 } else if (I.getNumOperands() == 2) {
861 Constant *C = cast<Constant>(I.getOperand(1));
862 for (unsigned i = 0; i != NumPHIValues; ++i) {
863 Value *InV = nullptr;
864 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
865 InV = ConstantExpr::get(I.getOpcode(), InC, C);
867 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
868 PN->getIncomingValue(i), C, "phitmp");
869 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
872 CastInst *CI = cast<CastInst>(&I);
873 Type *RetTy = CI->getType();
874 for (unsigned i = 0; i != NumPHIValues; ++i) {
876 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
877 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
879 InV = Builder->CreateCast(CI->getOpcode(),
880 PN->getIncomingValue(i), I.getType(), "phitmp");
881 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
885 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
886 Instruction *User = cast<Instruction>(*UI++);
887 if (User == &I) continue;
888 ReplaceInstUsesWith(*User, NewPN);
889 EraseInstFromFunction(*User);
891 return ReplaceInstUsesWith(I, NewPN);
894 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
895 /// whether or not there is a sequence of GEP indices into the pointed type that
896 /// will land us at the specified offset. If so, fill them into NewIndices and
897 /// return the resultant element type, otherwise return null.
898 Type *InstCombiner::FindElementAtOffset(Type *PtrTy, int64_t Offset,
899 SmallVectorImpl<Value*> &NewIndices) {
900 assert(PtrTy->isPtrOrPtrVectorTy());
905 Type *Ty = PtrTy->getPointerElementType();
909 // Start with the index over the outer type. Note that the type size
910 // might be zero (even if the offset isn't zero) if the indexed type
911 // is something like [0 x {int, int}]
912 Type *IntPtrTy = DL->getIntPtrType(PtrTy);
913 int64_t FirstIdx = 0;
914 if (int64_t TySize = DL->getTypeAllocSize(Ty)) {
915 FirstIdx = Offset/TySize;
916 Offset -= FirstIdx*TySize;
918 // Handle hosts where % returns negative instead of values [0..TySize).
924 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
927 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
929 // Index into the types. If we fail, set OrigBase to null.
931 // Indexing into tail padding between struct/array elements.
932 if (uint64_t(Offset*8) >= DL->getTypeSizeInBits(Ty))
935 if (StructType *STy = dyn_cast<StructType>(Ty)) {
936 const StructLayout *SL = DL->getStructLayout(STy);
937 assert(Offset < (int64_t)SL->getSizeInBytes() &&
938 "Offset must stay within the indexed type");
940 unsigned Elt = SL->getElementContainingOffset(Offset);
941 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
944 Offset -= SL->getElementOffset(Elt);
945 Ty = STy->getElementType(Elt);
946 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
947 uint64_t EltSize = DL->getTypeAllocSize(AT->getElementType());
948 assert(EltSize && "Cannot index into a zero-sized array");
949 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
951 Ty = AT->getElementType();
953 // Otherwise, we can't index into the middle of this atomic type, bail.
961 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
962 // If this GEP has only 0 indices, it is the same pointer as
963 // Src. If Src is not a trivial GEP too, don't combine
965 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
971 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
972 /// the multiplication is known not to overflow then NoSignedWrap is set.
973 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
974 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
975 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
976 Scale.getBitWidth() && "Scale not compatible with value!");
978 // If Val is zero or Scale is one then Val = Val * Scale.
979 if (match(Val, m_Zero()) || Scale == 1) {
984 // If Scale is zero then it does not divide Val.
985 if (Scale.isMinValue())
988 // Look through chains of multiplications, searching for a constant that is
989 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
990 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
991 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
994 // Val = M1 * X || Analysis starts here and works down
995 // M1 = M2 * Y || Doesn't descend into terms with more
996 // M2 = Z * 4 \/ than one use
998 // Then to modify a term at the bottom:
1001 // M1 = Z * Y || Replaced M2 with Z
1003 // Then to work back up correcting nsw flags.
1005 // Op - the term we are currently analyzing. Starts at Val then drills down.
1006 // Replaced with its descaled value before exiting from the drill down loop.
1009 // Parent - initially null, but after drilling down notes where Op came from.
1010 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1011 // 0'th operand of Val.
1012 std::pair<Instruction*, unsigned> Parent;
1014 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1015 // levels that doesn't overflow.
1016 bool RequireNoSignedWrap = false;
1018 // logScale - log base 2 of the scale. Negative if not a power of 2.
1019 int32_t logScale = Scale.exactLogBase2();
1021 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1023 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1024 // If Op is a constant divisible by Scale then descale to the quotient.
1025 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1026 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1027 if (!Remainder.isMinValue())
1028 // Not divisible by Scale.
1030 // Replace with the quotient in the parent.
1031 Op = ConstantInt::get(CI->getType(), Quotient);
1032 NoSignedWrap = true;
1036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1038 if (BO->getOpcode() == Instruction::Mul) {
1040 NoSignedWrap = BO->hasNoSignedWrap();
1041 if (RequireNoSignedWrap && !NoSignedWrap)
1044 // There are three cases for multiplication: multiplication by exactly
1045 // the scale, multiplication by a constant different to the scale, and
1046 // multiplication by something else.
1047 Value *LHS = BO->getOperand(0);
1048 Value *RHS = BO->getOperand(1);
1050 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1051 // Multiplication by a constant.
1052 if (CI->getValue() == Scale) {
1053 // Multiplication by exactly the scale, replace the multiplication
1054 // by its left-hand side in the parent.
1059 // Otherwise drill down into the constant.
1060 if (!Op->hasOneUse())
1063 Parent = std::make_pair(BO, 1);
1067 // Multiplication by something else. Drill down into the left-hand side
1068 // since that's where the reassociate pass puts the good stuff.
1069 if (!Op->hasOneUse())
1072 Parent = std::make_pair(BO, 0);
1076 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1077 isa<ConstantInt>(BO->getOperand(1))) {
1078 // Multiplication by a power of 2.
1079 NoSignedWrap = BO->hasNoSignedWrap();
1080 if (RequireNoSignedWrap && !NoSignedWrap)
1083 Value *LHS = BO->getOperand(0);
1084 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1085 getLimitedValue(Scale.getBitWidth());
1088 if (Amt == logScale) {
1089 // Multiplication by exactly the scale, replace the multiplication
1090 // by its left-hand side in the parent.
1094 if (Amt < logScale || !Op->hasOneUse())
1097 // Multiplication by more than the scale. Reduce the multiplying amount
1098 // by the scale in the parent.
1099 Parent = std::make_pair(BO, 1);
1100 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1105 if (!Op->hasOneUse())
1108 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1109 if (Cast->getOpcode() == Instruction::SExt) {
1110 // Op is sign-extended from a smaller type, descale in the smaller type.
1111 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1112 APInt SmallScale = Scale.trunc(SmallSize);
1113 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1114 // descale Op as (sext Y) * Scale. In order to have
1115 // sext (Y * SmallScale) = (sext Y) * Scale
1116 // some conditions need to hold however: SmallScale must sign-extend to
1117 // Scale and the multiplication Y * SmallScale should not overflow.
1118 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1119 // SmallScale does not sign-extend to Scale.
1121 assert(SmallScale.exactLogBase2() == logScale);
1122 // Require that Y * SmallScale must not overflow.
1123 RequireNoSignedWrap = true;
1125 // Drill down through the cast.
1126 Parent = std::make_pair(Cast, 0);
1131 if (Cast->getOpcode() == Instruction::Trunc) {
1132 // Op is truncated from a larger type, descale in the larger type.
1133 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1134 // trunc (Y * sext Scale) = (trunc Y) * Scale
1135 // always holds. However (trunc Y) * Scale may overflow even if
1136 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1137 // from this point up in the expression (see later).
1138 if (RequireNoSignedWrap)
1141 // Drill down through the cast.
1142 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1143 Parent = std::make_pair(Cast, 0);
1144 Scale = Scale.sext(LargeSize);
1145 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1147 assert(Scale.exactLogBase2() == logScale);
1152 // Unsupported expression, bail out.
1156 // If Op is zero then Val = Op * Scale.
1157 if (match(Op, m_Zero())) {
1158 NoSignedWrap = true;
1162 // We know that we can successfully descale, so from here on we can safely
1163 // modify the IR. Op holds the descaled version of the deepest term in the
1164 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1168 // The expression only had one term.
1171 // Rewrite the parent using the descaled version of its operand.
1172 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1173 assert(Op != Parent.first->getOperand(Parent.second) &&
1174 "Descaling was a no-op?");
1175 Parent.first->setOperand(Parent.second, Op);
1176 Worklist.Add(Parent.first);
1178 // Now work back up the expression correcting nsw flags. The logic is based
1179 // on the following observation: if X * Y is known not to overflow as a signed
1180 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1181 // then X * Z will not overflow as a signed multiplication either. As we work
1182 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1183 // current level has strictly smaller absolute value than the original.
1184 Instruction *Ancestor = Parent.first;
1186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1187 // If the multiplication wasn't nsw then we can't say anything about the
1188 // value of the descaled multiplication, and we have to clear nsw flags
1189 // from this point on up.
1190 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1191 NoSignedWrap &= OpNoSignedWrap;
1192 if (NoSignedWrap != OpNoSignedWrap) {
1193 BO->setHasNoSignedWrap(NoSignedWrap);
1194 Worklist.Add(Ancestor);
1196 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1197 // The fact that the descaled input to the trunc has smaller absolute
1198 // value than the original input doesn't tell us anything useful about
1199 // the absolute values of the truncations.
1200 NoSignedWrap = false;
1202 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1203 "Failed to keep proper track of nsw flags while drilling down?");
1205 if (Ancestor == Val)
1206 // Got to the top, all done!
1209 // Move up one level in the expression.
1210 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1211 Ancestor = Ancestor->user_back();
1215 /// \brief Creates node of binary operation with the same attributes as the
1216 /// specified one but with other operands.
1217 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1218 InstCombiner::BuilderTy *B) {
1219 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1220 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1221 if (isa<OverflowingBinaryOperator>(NewBO)) {
1222 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1223 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1225 if (isa<PossiblyExactOperator>(NewBO))
1226 NewBO->setIsExact(Inst.isExact());
1231 /// \brief Makes transformation of binary operation specific for vector types.
1232 /// \param Inst Binary operator to transform.
1233 /// \return Pointer to node that must replace the original binary operator, or
1234 /// null pointer if no transformation was made.
1235 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1236 if (!Inst.getType()->isVectorTy()) return nullptr;
1238 // It may not be safe to reorder shuffles and things like div, urem, etc.
1239 // because we may trap when executing those ops on unknown vector elements.
1241 if (!isSafeToSpeculativelyExecute(&Inst, DL)) return nullptr;
1243 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1244 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1245 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1246 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1248 // If both arguments of binary operation are shuffles, which use the same
1249 // mask and shuffle within a single vector, it is worthwhile to move the
1250 // shuffle after binary operation:
1251 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1252 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1253 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1254 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1255 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1256 isa<UndefValue>(RShuf->getOperand(1)) &&
1257 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1258 LShuf->getMask() == RShuf->getMask()) {
1259 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1260 RShuf->getOperand(0), Builder);
1261 Value *Res = Builder->CreateShuffleVector(NewBO,
1262 UndefValue::get(NewBO->getType()), LShuf->getMask());
1267 // If one argument is a shuffle within one vector, the other is a constant,
1268 // try moving the shuffle after the binary operation.
1269 ShuffleVectorInst *Shuffle = nullptr;
1270 Constant *C1 = nullptr;
1271 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1272 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1273 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1274 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1275 if (Shuffle && C1 &&
1276 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1277 isa<UndefValue>(Shuffle->getOperand(1)) &&
1278 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1279 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1280 // Find constant C2 that has property:
1281 // shuffle(C2, ShMask) = C1
1282 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1283 // reorder is not possible.
1284 SmallVector<Constant*, 16> C2M(VWidth,
1285 UndefValue::get(C1->getType()->getScalarType()));
1286 bool MayChange = true;
1287 for (unsigned I = 0; I < VWidth; ++I) {
1288 if (ShMask[I] >= 0) {
1289 assert(ShMask[I] < (int)VWidth);
1290 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1294 C2M[ShMask[I]] = C1->getAggregateElement(I);
1298 Constant *C2 = ConstantVector::get(C2M);
1299 Value *NewLHS, *NewRHS;
1300 if (isa<Constant>(LHS)) {
1302 NewRHS = Shuffle->getOperand(0);
1304 NewLHS = Shuffle->getOperand(0);
1307 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1308 Value *Res = Builder->CreateShuffleVector(NewBO,
1309 UndefValue::get(Inst.getType()), Shuffle->getMask());
1317 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1318 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1320 if (Value *V = SimplifyGEPInst(Ops, DL))
1321 return ReplaceInstUsesWith(GEP, V);
1323 Value *PtrOp = GEP.getOperand(0);
1325 // Eliminate unneeded casts for indices, and replace indices which displace
1326 // by multiples of a zero size type with zero.
1328 bool MadeChange = false;
1329 Type *IntPtrTy = DL->getIntPtrType(GEP.getPointerOperandType());
1331 gep_type_iterator GTI = gep_type_begin(GEP);
1332 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1333 I != E; ++I, ++GTI) {
1334 // Skip indices into struct types.
1335 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1336 if (!SeqTy) continue;
1338 // If the element type has zero size then any index over it is equivalent
1339 // to an index of zero, so replace it with zero if it is not zero already.
1340 if (SeqTy->getElementType()->isSized() &&
1341 DL->getTypeAllocSize(SeqTy->getElementType()) == 0)
1342 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1343 *I = Constant::getNullValue(IntPtrTy);
1347 Type *IndexTy = (*I)->getType();
1348 if (IndexTy != IntPtrTy) {
1349 // If we are using a wider index than needed for this platform, shrink
1350 // it to what we need. If narrower, sign-extend it to what we need.
1351 // This explicit cast can make subsequent optimizations more obvious.
1352 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1356 if (MadeChange) return &GEP;
1359 // Check to see if the inputs to the PHI node are getelementptr instructions.
1360 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1361 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1367 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1368 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1369 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1372 // Keep track of the type as we walk the GEP.
1373 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1375 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1376 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1379 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1381 // We have not seen any differences yet in the GEPs feeding the
1382 // PHI yet, so we record this one if it is allowed to be a
1385 // The first two arguments can vary for any GEP, the rest have to be
1386 // static for struct slots
1387 if (J > 1 && CurTy->isStructTy())
1392 // The GEP is different by more than one input. While this could be
1393 // extended to support GEPs that vary by more than one variable it
1394 // doesn't make sense since it greatly increases the complexity and
1395 // would result in an R+R+R addressing mode which no backend
1396 // directly supports and would need to be broken into several
1397 // simpler instructions anyway.
1402 // Sink down a layer of the type for the next iteration.
1404 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1405 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1413 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1416 // All the GEPs feeding the PHI are identical. Clone one down into our
1417 // BB so that it can be merged with the current GEP.
1418 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1421 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1422 // into the current block so it can be merged, and create a new PHI to
1424 Instruction *InsertPt = Builder->GetInsertPoint();
1425 Builder->SetInsertPoint(PN);
1426 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1427 PN->getNumOperands());
1428 Builder->SetInsertPoint(InsertPt);
1430 for (auto &I : PN->operands())
1431 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1432 PN->getIncomingBlock(I));
1434 NewGEP->setOperand(DI, NewPN);
1435 GEP.getParent()->getInstList().insert(GEP.getParent()->getFirstNonPHI(),
1437 NewGEP->setOperand(DI, NewPN);
1440 GEP.setOperand(0, NewGEP);
1444 // Combine Indices - If the source pointer to this getelementptr instruction
1445 // is a getelementptr instruction, combine the indices of the two
1446 // getelementptr instructions into a single instruction.
1448 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1449 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1452 // Note that if our source is a gep chain itself then we wait for that
1453 // chain to be resolved before we perform this transformation. This
1454 // avoids us creating a TON of code in some cases.
1455 if (GEPOperator *SrcGEP =
1456 dyn_cast<GEPOperator>(Src->getOperand(0)))
1457 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1458 return nullptr; // Wait until our source is folded to completion.
1460 SmallVector<Value*, 8> Indices;
1462 // Find out whether the last index in the source GEP is a sequential idx.
1463 bool EndsWithSequential = false;
1464 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1466 EndsWithSequential = !(*I)->isStructTy();
1468 // Can we combine the two pointer arithmetics offsets?
1469 if (EndsWithSequential) {
1470 // Replace: gep (gep %P, long B), long A, ...
1471 // With: T = long A+B; gep %P, T, ...
1474 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1475 Value *GO1 = GEP.getOperand(1);
1476 if (SO1 == Constant::getNullValue(SO1->getType())) {
1478 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1481 // If they aren't the same type, then the input hasn't been processed
1482 // by the loop above yet (which canonicalizes sequential index types to
1483 // intptr_t). Just avoid transforming this until the input has been
1485 if (SO1->getType() != GO1->getType())
1487 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1490 // Update the GEP in place if possible.
1491 if (Src->getNumOperands() == 2) {
1492 GEP.setOperand(0, Src->getOperand(0));
1493 GEP.setOperand(1, Sum);
1496 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1497 Indices.push_back(Sum);
1498 Indices.append(GEP.op_begin()+2, GEP.op_end());
1499 } else if (isa<Constant>(*GEP.idx_begin()) &&
1500 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1501 Src->getNumOperands() != 1) {
1502 // Otherwise we can do the fold if the first index of the GEP is a zero
1503 Indices.append(Src->op_begin()+1, Src->op_end());
1504 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1507 if (!Indices.empty())
1508 return (GEP.isInBounds() && Src->isInBounds()) ?
1509 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1511 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1514 if (DL && GEP.getNumIndices() == 1) {
1515 unsigned AS = GEP.getPointerAddressSpace();
1516 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1517 DL->getPointerSizeInBits(AS)) {
1518 Type *PtrTy = GEP.getPointerOperandType();
1519 Type *Ty = PtrTy->getPointerElementType();
1520 uint64_t TyAllocSize = DL->getTypeAllocSize(Ty);
1522 bool Matched = false;
1525 if (TyAllocSize == 1) {
1526 V = GEP.getOperand(1);
1528 } else if (match(GEP.getOperand(1),
1529 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1530 if (TyAllocSize == 1ULL << C)
1532 } else if (match(GEP.getOperand(1),
1533 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1534 if (TyAllocSize == C)
1539 // Canonicalize (gep i8* X, -(ptrtoint Y))
1540 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1541 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1542 // pointer arithmetic.
1543 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1544 Operator *Index = cast<Operator>(V);
1545 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1546 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1547 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1549 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1552 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1553 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1554 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1561 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1562 Value *StrippedPtr = PtrOp->stripPointerCasts();
1563 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1565 // We do not handle pointer-vector geps here.
1569 if (StrippedPtr != PtrOp) {
1570 bool HasZeroPointerIndex = false;
1571 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1572 HasZeroPointerIndex = C->isZero();
1574 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1575 // into : GEP [10 x i8]* X, i32 0, ...
1577 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1578 // into : GEP i8* X, ...
1580 // This occurs when the program declares an array extern like "int X[];"
1581 if (HasZeroPointerIndex) {
1582 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1583 if (ArrayType *CATy =
1584 dyn_cast<ArrayType>(CPTy->getElementType())) {
1585 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1586 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1587 // -> GEP i8* X, ...
1588 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1589 GetElementPtrInst *Res =
1590 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1591 Res->setIsInBounds(GEP.isInBounds());
1592 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1594 // Insert Res, and create an addrspacecast.
1596 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1598 // %0 = GEP i8 addrspace(1)* X, ...
1599 // addrspacecast i8 addrspace(1)* %0 to i8*
1600 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1603 if (ArrayType *XATy =
1604 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1605 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1606 if (CATy->getElementType() == XATy->getElementType()) {
1607 // -> GEP [10 x i8]* X, i32 0, ...
1608 // At this point, we know that the cast source type is a pointer
1609 // to an array of the same type as the destination pointer
1610 // array. Because the array type is never stepped over (there
1611 // is a leading zero) we can fold the cast into this GEP.
1612 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1613 GEP.setOperand(0, StrippedPtr);
1616 // Cannot replace the base pointer directly because StrippedPtr's
1617 // address space is different. Instead, create a new GEP followed by
1618 // an addrspacecast.
1620 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1623 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1624 // addrspacecast i8 addrspace(1)* %0 to i8*
1625 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1626 Value *NewGEP = GEP.isInBounds() ?
1627 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1628 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1629 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1633 } else if (GEP.getNumOperands() == 2) {
1634 // Transform things like:
1635 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1636 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1637 Type *SrcElTy = StrippedPtrTy->getElementType();
1638 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1639 if (DL && SrcElTy->isArrayTy() &&
1640 DL->getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1641 DL->getTypeAllocSize(ResElTy)) {
1642 Type *IdxType = DL->getIntPtrType(GEP.getType());
1643 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1644 Value *NewGEP = GEP.isInBounds() ?
1645 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1646 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1648 // V and GEP are both pointer types --> BitCast
1649 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1653 // Transform things like:
1654 // %V = mul i64 %N, 4
1655 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1656 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1657 if (DL && ResElTy->isSized() && SrcElTy->isSized()) {
1658 // Check that changing the type amounts to dividing the index by a scale
1660 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1661 uint64_t SrcSize = DL->getTypeAllocSize(SrcElTy);
1662 if (ResSize && SrcSize % ResSize == 0) {
1663 Value *Idx = GEP.getOperand(1);
1664 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1665 uint64_t Scale = SrcSize / ResSize;
1667 // Earlier transforms ensure that the index has type IntPtrType, which
1668 // considerably simplifies the logic by eliminating implicit casts.
1669 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1670 "Index not cast to pointer width?");
1673 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1674 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1675 // If the multiplication NewIdx * Scale may overflow then the new
1676 // GEP may not be "inbounds".
1677 Value *NewGEP = GEP.isInBounds() && NSW ?
1678 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1679 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1681 // The NewGEP must be pointer typed, so must the old one -> BitCast
1682 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1688 // Similarly, transform things like:
1689 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1690 // (where tmp = 8*tmp2) into:
1691 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1692 if (DL && ResElTy->isSized() && SrcElTy->isSized() &&
1693 SrcElTy->isArrayTy()) {
1694 // Check that changing to the array element type amounts to dividing the
1695 // index by a scale factor.
1696 uint64_t ResSize = DL->getTypeAllocSize(ResElTy);
1697 uint64_t ArrayEltSize
1698 = DL->getTypeAllocSize(SrcElTy->getArrayElementType());
1699 if (ResSize && ArrayEltSize % ResSize == 0) {
1700 Value *Idx = GEP.getOperand(1);
1701 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1702 uint64_t Scale = ArrayEltSize / ResSize;
1704 // Earlier transforms ensure that the index has type IntPtrType, which
1705 // considerably simplifies the logic by eliminating implicit casts.
1706 assert(Idx->getType() == DL->getIntPtrType(GEP.getType()) &&
1707 "Index not cast to pointer width?");
1710 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1711 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1712 // If the multiplication NewIdx * Scale may overflow then the new
1713 // GEP may not be "inbounds".
1715 Constant::getNullValue(DL->getIntPtrType(GEP.getType())),
1719 Value *NewGEP = GEP.isInBounds() && NSW ?
1720 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1721 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1722 // The NewGEP must be pointer typed, so must the old one -> BitCast
1723 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1734 // addrspacecast between types is canonicalized as a bitcast, then an
1735 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1736 // through the addrspacecast.
1737 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1738 // X = bitcast A addrspace(1)* to B addrspace(1)*
1739 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1740 // Z = gep Y, <...constant indices...>
1741 // Into an addrspacecasted GEP of the struct.
1742 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1746 /// See if we can simplify:
1747 /// X = bitcast A* to B*
1748 /// Y = gep X, <...constant indices...>
1749 /// into a gep of the original struct. This is important for SROA and alias
1750 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1751 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1752 Value *Operand = BCI->getOperand(0);
1753 PointerType *OpType = cast<PointerType>(Operand->getType());
1754 unsigned OffsetBits = DL->getPointerTypeSizeInBits(GEP.getType());
1755 APInt Offset(OffsetBits, 0);
1756 if (!isa<BitCastInst>(Operand) &&
1757 GEP.accumulateConstantOffset(*DL, Offset)) {
1759 // If this GEP instruction doesn't move the pointer, just replace the GEP
1760 // with a bitcast of the real input to the dest type.
1762 // If the bitcast is of an allocation, and the allocation will be
1763 // converted to match the type of the cast, don't touch this.
1764 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1765 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1766 if (Instruction *I = visitBitCast(*BCI)) {
1769 BCI->getParent()->getInstList().insert(BCI, I);
1770 ReplaceInstUsesWith(*BCI, I);
1776 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1777 return new AddrSpaceCastInst(Operand, GEP.getType());
1778 return new BitCastInst(Operand, GEP.getType());
1781 // Otherwise, if the offset is non-zero, we need to find out if there is a
1782 // field at Offset in 'A's type. If so, we can pull the cast through the
1784 SmallVector<Value*, 8> NewIndices;
1785 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1786 Value *NGEP = GEP.isInBounds() ?
1787 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1788 Builder->CreateGEP(Operand, NewIndices);
1790 if (NGEP->getType() == GEP.getType())
1791 return ReplaceInstUsesWith(GEP, NGEP);
1792 NGEP->takeName(&GEP);
1794 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1795 return new AddrSpaceCastInst(NGEP, GEP.getType());
1796 return new BitCastInst(NGEP, GEP.getType());
1805 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1806 const TargetLibraryInfo *TLI) {
1807 SmallVector<Instruction*, 4> Worklist;
1808 Worklist.push_back(AI);
1811 Instruction *PI = Worklist.pop_back_val();
1812 for (User *U : PI->users()) {
1813 Instruction *I = cast<Instruction>(U);
1814 switch (I->getOpcode()) {
1816 // Give up the moment we see something we can't handle.
1819 case Instruction::BitCast:
1820 case Instruction::GetElementPtr:
1822 Worklist.push_back(I);
1825 case Instruction::ICmp: {
1826 ICmpInst *ICI = cast<ICmpInst>(I);
1827 // We can fold eq/ne comparisons with null to false/true, respectively.
1828 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1834 case Instruction::Call:
1835 // Ignore no-op and store intrinsics.
1836 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1837 switch (II->getIntrinsicID()) {
1841 case Intrinsic::memmove:
1842 case Intrinsic::memcpy:
1843 case Intrinsic::memset: {
1844 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1845 if (MI->isVolatile() || MI->getRawDest() != PI)
1849 case Intrinsic::dbg_declare:
1850 case Intrinsic::dbg_value:
1851 case Intrinsic::invariant_start:
1852 case Intrinsic::invariant_end:
1853 case Intrinsic::lifetime_start:
1854 case Intrinsic::lifetime_end:
1855 case Intrinsic::objectsize:
1861 if (isFreeCall(I, TLI)) {
1867 case Instruction::Store: {
1868 StoreInst *SI = cast<StoreInst>(I);
1869 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1875 llvm_unreachable("missing a return?");
1877 } while (!Worklist.empty());
1881 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1882 // If we have a malloc call which is only used in any amount of comparisons
1883 // to null and free calls, delete the calls and replace the comparisons with
1884 // true or false as appropriate.
1885 SmallVector<WeakVH, 64> Users;
1886 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1887 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1888 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1891 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1892 ReplaceInstUsesWith(*C,
1893 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1894 C->isFalseWhenEqual()));
1895 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1896 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1897 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1898 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1899 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1900 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1901 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1904 EraseInstFromFunction(*I);
1907 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1908 // Replace invoke with a NOP intrinsic to maintain the original CFG
1909 Module *M = II->getParent()->getParent()->getParent();
1910 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1911 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1912 None, "", II->getParent());
1914 return EraseInstFromFunction(MI);
1919 /// \brief Move the call to free before a NULL test.
1921 /// Check if this free is accessed after its argument has been test
1922 /// against NULL (property 0).
1923 /// If yes, it is legal to move this call in its predecessor block.
1925 /// The move is performed only if the block containing the call to free
1926 /// will be removed, i.e.:
1927 /// 1. it has only one predecessor P, and P has two successors
1928 /// 2. it contains the call and an unconditional branch
1929 /// 3. its successor is the same as its predecessor's successor
1931 /// The profitability is out-of concern here and this function should
1932 /// be called only if the caller knows this transformation would be
1933 /// profitable (e.g., for code size).
1934 static Instruction *
1935 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1936 Value *Op = FI.getArgOperand(0);
1937 BasicBlock *FreeInstrBB = FI.getParent();
1938 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1940 // Validate part of constraint #1: Only one predecessor
1941 // FIXME: We can extend the number of predecessor, but in that case, we
1942 // would duplicate the call to free in each predecessor and it may
1943 // not be profitable even for code size.
1947 // Validate constraint #2: Does this block contains only the call to
1948 // free and an unconditional branch?
1949 // FIXME: We could check if we can speculate everything in the
1950 // predecessor block
1951 if (FreeInstrBB->size() != 2)
1954 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1957 // Validate the rest of constraint #1 by matching on the pred branch.
1958 TerminatorInst *TI = PredBB->getTerminator();
1959 BasicBlock *TrueBB, *FalseBB;
1960 ICmpInst::Predicate Pred;
1961 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1963 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1966 // Validate constraint #3: Ensure the null case just falls through.
1967 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1969 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1970 "Broken CFG: missing edge from predecessor to successor");
1977 Instruction *InstCombiner::visitFree(CallInst &FI) {
1978 Value *Op = FI.getArgOperand(0);
1980 // free undef -> unreachable.
1981 if (isa<UndefValue>(Op)) {
1982 // Insert a new store to null because we cannot modify the CFG here.
1983 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1984 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1985 return EraseInstFromFunction(FI);
1988 // If we have 'free null' delete the instruction. This can happen in stl code
1989 // when lots of inlining happens.
1990 if (isa<ConstantPointerNull>(Op))
1991 return EraseInstFromFunction(FI);
1993 // If we optimize for code size, try to move the call to free before the null
1994 // test so that simplify cfg can remove the empty block and dead code
1995 // elimination the branch. I.e., helps to turn something like:
1996 // if (foo) free(foo);
2000 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2008 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2009 // Change br (not X), label True, label False to: br X, label False, True
2011 BasicBlock *TrueDest;
2012 BasicBlock *FalseDest;
2013 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2014 !isa<Constant>(X)) {
2015 // Swap Destinations and condition...
2017 BI.swapSuccessors();
2021 // Canonicalize fcmp_one -> fcmp_oeq
2022 FCmpInst::Predicate FPred; Value *Y;
2023 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2024 TrueDest, FalseDest)) &&
2025 BI.getCondition()->hasOneUse())
2026 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2027 FPred == FCmpInst::FCMP_OGE) {
2028 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2029 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2031 // Swap Destinations and condition.
2032 BI.swapSuccessors();
2037 // Canonicalize icmp_ne -> icmp_eq
2038 ICmpInst::Predicate IPred;
2039 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2040 TrueDest, FalseDest)) &&
2041 BI.getCondition()->hasOneUse())
2042 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2043 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2044 IPred == ICmpInst::ICMP_SGE) {
2045 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2046 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2047 // Swap Destinations and condition.
2048 BI.swapSuccessors();
2056 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2057 Value *Cond = SI.getCondition();
2058 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2059 if (I->getOpcode() == Instruction::Add)
2060 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2061 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2062 // Skip the first item since that's the default case.
2063 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2065 ConstantInt* CaseVal = i.getCaseValue();
2066 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
2068 assert(isa<ConstantInt>(NewCaseVal) &&
2069 "Result of expression should be constant");
2070 i.setValue(cast<ConstantInt>(NewCaseVal));
2072 SI.setCondition(I->getOperand(0));
2080 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2081 Value *Agg = EV.getAggregateOperand();
2083 if (!EV.hasIndices())
2084 return ReplaceInstUsesWith(EV, Agg);
2086 if (Constant *C = dyn_cast<Constant>(Agg)) {
2087 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2088 if (EV.getNumIndices() == 0)
2089 return ReplaceInstUsesWith(EV, C2);
2090 // Extract the remaining indices out of the constant indexed by the
2092 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2094 return nullptr; // Can't handle other constants
2097 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2098 // We're extracting from an insertvalue instruction, compare the indices
2099 const unsigned *exti, *exte, *insi, *inse;
2100 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2101 exte = EV.idx_end(), inse = IV->idx_end();
2102 exti != exte && insi != inse;
2105 // The insert and extract both reference distinctly different elements.
2106 // This means the extract is not influenced by the insert, and we can
2107 // replace the aggregate operand of the extract with the aggregate
2108 // operand of the insert. i.e., replace
2109 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2110 // %E = extractvalue { i32, { i32 } } %I, 0
2112 // %E = extractvalue { i32, { i32 } } %A, 0
2113 return ExtractValueInst::Create(IV->getAggregateOperand(),
2116 if (exti == exte && insi == inse)
2117 // Both iterators are at the end: Index lists are identical. Replace
2118 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2119 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2121 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2123 // The extract list is a prefix of the insert list. i.e. replace
2124 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2125 // %E = extractvalue { i32, { i32 } } %I, 1
2127 // %X = extractvalue { i32, { i32 } } %A, 1
2128 // %E = insertvalue { i32 } %X, i32 42, 0
2129 // by switching the order of the insert and extract (though the
2130 // insertvalue should be left in, since it may have other uses).
2131 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2133 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2134 makeArrayRef(insi, inse));
2137 // The insert list is a prefix of the extract list
2138 // We can simply remove the common indices from the extract and make it
2139 // operate on the inserted value instead of the insertvalue result.
2141 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2142 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2144 // %E extractvalue { i32 } { i32 42 }, 0
2145 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2146 makeArrayRef(exti, exte));
2148 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2149 // We're extracting from an intrinsic, see if we're the only user, which
2150 // allows us to simplify multiple result intrinsics to simpler things that
2151 // just get one value.
2152 if (II->hasOneUse()) {
2153 // Check if we're grabbing the overflow bit or the result of a 'with
2154 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2155 // and replace it with a traditional binary instruction.
2156 switch (II->getIntrinsicID()) {
2157 case Intrinsic::uadd_with_overflow:
2158 case Intrinsic::sadd_with_overflow:
2159 if (*EV.idx_begin() == 0) { // Normal result.
2160 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2161 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2162 EraseInstFromFunction(*II);
2163 return BinaryOperator::CreateAdd(LHS, RHS);
2166 // If the normal result of the add is dead, and the RHS is a constant,
2167 // we can transform this into a range comparison.
2168 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2169 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2170 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2171 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2172 ConstantExpr::getNot(CI));
2174 case Intrinsic::usub_with_overflow:
2175 case Intrinsic::ssub_with_overflow:
2176 if (*EV.idx_begin() == 0) { // Normal result.
2177 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2178 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2179 EraseInstFromFunction(*II);
2180 return BinaryOperator::CreateSub(LHS, RHS);
2183 case Intrinsic::umul_with_overflow:
2184 case Intrinsic::smul_with_overflow:
2185 if (*EV.idx_begin() == 0) { // Normal result.
2186 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2187 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2188 EraseInstFromFunction(*II);
2189 return BinaryOperator::CreateMul(LHS, RHS);
2197 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2198 // If the (non-volatile) load only has one use, we can rewrite this to a
2199 // load from a GEP. This reduces the size of the load.
2200 // FIXME: If a load is used only by extractvalue instructions then this
2201 // could be done regardless of having multiple uses.
2202 if (L->isSimple() && L->hasOneUse()) {
2203 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2204 SmallVector<Value*, 4> Indices;
2205 // Prefix an i32 0 since we need the first element.
2206 Indices.push_back(Builder->getInt32(0));
2207 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2209 Indices.push_back(Builder->getInt32(*I));
2211 // We need to insert these at the location of the old load, not at that of
2212 // the extractvalue.
2213 Builder->SetInsertPoint(L->getParent(), L);
2214 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
2215 // Returning the load directly will cause the main loop to insert it in
2216 // the wrong spot, so use ReplaceInstUsesWith().
2217 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2219 // We could simplify extracts from other values. Note that nested extracts may
2220 // already be simplified implicitly by the above: extract (extract (insert) )
2221 // will be translated into extract ( insert ( extract ) ) first and then just
2222 // the value inserted, if appropriate. Similarly for extracts from single-use
2223 // loads: extract (extract (load)) will be translated to extract (load (gep))
2224 // and if again single-use then via load (gep (gep)) to load (gep).
2225 // However, double extracts from e.g. function arguments or return values
2226 // aren't handled yet.
2230 enum Personality_Type {
2231 Unknown_Personality,
2232 GNU_Ada_Personality,
2233 GNU_CXX_Personality,
2234 GNU_ObjC_Personality
2237 /// RecognizePersonality - See if the given exception handling personality
2238 /// function is one that we understand. If so, return a description of it;
2239 /// otherwise return Unknown_Personality.
2240 static Personality_Type RecognizePersonality(Value *Pers) {
2241 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
2243 return Unknown_Personality;
2244 return StringSwitch<Personality_Type>(F->getName())
2245 .Case("__gnat_eh_personality", GNU_Ada_Personality)
2246 .Case("__gxx_personality_v0", GNU_CXX_Personality)
2247 .Case("__objc_personality_v0", GNU_ObjC_Personality)
2248 .Default(Unknown_Personality);
2251 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2252 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
2253 switch (Personality) {
2254 case Unknown_Personality:
2256 case GNU_Ada_Personality:
2257 // While __gnat_all_others_value will match any Ada exception, it doesn't
2258 // match foreign exceptions (or didn't, before gcc-4.7).
2260 case GNU_CXX_Personality:
2261 case GNU_ObjC_Personality:
2262 return TypeInfo->isNullValue();
2264 llvm_unreachable("Unknown personality!");
2267 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2269 cast<ArrayType>(LHS->getType())->getNumElements()
2271 cast<ArrayType>(RHS->getType())->getNumElements();
2274 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2275 // The logic here should be correct for any real-world personality function.
2276 // However if that turns out not to be true, the offending logic can always
2277 // be conditioned on the personality function, like the catch-all logic is.
2278 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
2280 // Simplify the list of clauses, eg by removing repeated catch clauses
2281 // (these are often created by inlining).
2282 bool MakeNewInstruction = false; // If true, recreate using the following:
2283 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2284 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2286 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2287 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2288 bool isLastClause = i + 1 == e;
2289 if (LI.isCatch(i)) {
2291 Constant *CatchClause = LI.getClause(i);
2292 Constant *TypeInfo = CatchClause->stripPointerCasts();
2294 // If we already saw this clause, there is no point in having a second
2296 if (AlreadyCaught.insert(TypeInfo)) {
2297 // This catch clause was not already seen.
2298 NewClauses.push_back(CatchClause);
2300 // Repeated catch clause - drop the redundant copy.
2301 MakeNewInstruction = true;
2304 // If this is a catch-all then there is no point in keeping any following
2305 // clauses or marking the landingpad as having a cleanup.
2306 if (isCatchAll(Personality, TypeInfo)) {
2308 MakeNewInstruction = true;
2309 CleanupFlag = false;
2313 // A filter clause. If any of the filter elements were already caught
2314 // then they can be dropped from the filter. It is tempting to try to
2315 // exploit the filter further by saying that any typeinfo that does not
2316 // occur in the filter can't be caught later (and thus can be dropped).
2317 // However this would be wrong, since typeinfos can match without being
2318 // equal (for example if one represents a C++ class, and the other some
2319 // class derived from it).
2320 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2321 Constant *FilterClause = LI.getClause(i);
2322 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2323 unsigned NumTypeInfos = FilterType->getNumElements();
2325 // An empty filter catches everything, so there is no point in keeping any
2326 // following clauses or marking the landingpad as having a cleanup. By
2327 // dealing with this case here the following code is made a bit simpler.
2328 if (!NumTypeInfos) {
2329 NewClauses.push_back(FilterClause);
2331 MakeNewInstruction = true;
2332 CleanupFlag = false;
2336 bool MakeNewFilter = false; // If true, make a new filter.
2337 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2338 if (isa<ConstantAggregateZero>(FilterClause)) {
2339 // Not an empty filter - it contains at least one null typeinfo.
2340 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2341 Constant *TypeInfo =
2342 Constant::getNullValue(FilterType->getElementType());
2343 // If this typeinfo is a catch-all then the filter can never match.
2344 if (isCatchAll(Personality, TypeInfo)) {
2345 // Throw the filter away.
2346 MakeNewInstruction = true;
2350 // There is no point in having multiple copies of this typeinfo, so
2351 // discard all but the first copy if there is more than one.
2352 NewFilterElts.push_back(TypeInfo);
2353 if (NumTypeInfos > 1)
2354 MakeNewFilter = true;
2356 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2357 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2358 NewFilterElts.reserve(NumTypeInfos);
2360 // Remove any filter elements that were already caught or that already
2361 // occurred in the filter. While there, see if any of the elements are
2362 // catch-alls. If so, the filter can be discarded.
2363 bool SawCatchAll = false;
2364 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2365 Constant *Elt = Filter->getOperand(j);
2366 Constant *TypeInfo = Elt->stripPointerCasts();
2367 if (isCatchAll(Personality, TypeInfo)) {
2368 // This element is a catch-all. Bail out, noting this fact.
2372 if (AlreadyCaught.count(TypeInfo))
2373 // Already caught by an earlier clause, so having it in the filter
2376 // There is no point in having multiple copies of the same typeinfo in
2377 // a filter, so only add it if we didn't already.
2378 if (SeenInFilter.insert(TypeInfo))
2379 NewFilterElts.push_back(cast<Constant>(Elt));
2381 // A filter containing a catch-all cannot match anything by definition.
2383 // Throw the filter away.
2384 MakeNewInstruction = true;
2388 // If we dropped something from the filter, make a new one.
2389 if (NewFilterElts.size() < NumTypeInfos)
2390 MakeNewFilter = true;
2392 if (MakeNewFilter) {
2393 FilterType = ArrayType::get(FilterType->getElementType(),
2394 NewFilterElts.size());
2395 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2396 MakeNewInstruction = true;
2399 NewClauses.push_back(FilterClause);
2401 // If the new filter is empty then it will catch everything so there is
2402 // no point in keeping any following clauses or marking the landingpad
2403 // as having a cleanup. The case of the original filter being empty was
2404 // already handled above.
2405 if (MakeNewFilter && !NewFilterElts.size()) {
2406 assert(MakeNewInstruction && "New filter but not a new instruction!");
2407 CleanupFlag = false;
2413 // If several filters occur in a row then reorder them so that the shortest
2414 // filters come first (those with the smallest number of elements). This is
2415 // advantageous because shorter filters are more likely to match, speeding up
2416 // unwinding, but mostly because it increases the effectiveness of the other
2417 // filter optimizations below.
2418 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2420 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2421 for (j = i; j != e; ++j)
2422 if (!isa<ArrayType>(NewClauses[j]->getType()))
2425 // Check whether the filters are already sorted by length. We need to know
2426 // if sorting them is actually going to do anything so that we only make a
2427 // new landingpad instruction if it does.
2428 for (unsigned k = i; k + 1 < j; ++k)
2429 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2430 // Not sorted, so sort the filters now. Doing an unstable sort would be
2431 // correct too but reordering filters pointlessly might confuse users.
2432 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2434 MakeNewInstruction = true;
2438 // Look for the next batch of filters.
2442 // If typeinfos matched if and only if equal, then the elements of a filter L
2443 // that occurs later than a filter F could be replaced by the intersection of
2444 // the elements of F and L. In reality two typeinfos can match without being
2445 // equal (for example if one represents a C++ class, and the other some class
2446 // derived from it) so it would be wrong to perform this transform in general.
2447 // However the transform is correct and useful if F is a subset of L. In that
2448 // case L can be replaced by F, and thus removed altogether since repeating a
2449 // filter is pointless. So here we look at all pairs of filters F and L where
2450 // L follows F in the list of clauses, and remove L if every element of F is
2451 // an element of L. This can occur when inlining C++ functions with exception
2453 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2454 // Examine each filter in turn.
2455 Value *Filter = NewClauses[i];
2456 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2458 // Not a filter - skip it.
2460 unsigned FElts = FTy->getNumElements();
2461 // Examine each filter following this one. Doing this backwards means that
2462 // we don't have to worry about filters disappearing under us when removed.
2463 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2464 Value *LFilter = NewClauses[j];
2465 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2467 // Not a filter - skip it.
2469 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2470 // an element of LFilter, then discard LFilter.
2471 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2472 // If Filter is empty then it is a subset of LFilter.
2475 NewClauses.erase(J);
2476 MakeNewInstruction = true;
2477 // Move on to the next filter.
2480 unsigned LElts = LTy->getNumElements();
2481 // If Filter is longer than LFilter then it cannot be a subset of it.
2483 // Move on to the next filter.
2485 // At this point we know that LFilter has at least one element.
2486 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2487 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2488 // already know that Filter is not longer than LFilter).
2489 if (isa<ConstantAggregateZero>(Filter)) {
2490 assert(FElts <= LElts && "Should have handled this case earlier!");
2492 NewClauses.erase(J);
2493 MakeNewInstruction = true;
2495 // Move on to the next filter.
2498 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2499 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2500 // Since Filter is non-empty and contains only zeros, it is a subset of
2501 // LFilter iff LFilter contains a zero.
2502 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2503 for (unsigned l = 0; l != LElts; ++l)
2504 if (LArray->getOperand(l)->isNullValue()) {
2505 // LFilter contains a zero - discard it.
2506 NewClauses.erase(J);
2507 MakeNewInstruction = true;
2510 // Move on to the next filter.
2513 // At this point we know that both filters are ConstantArrays. Loop over
2514 // operands to see whether every element of Filter is also an element of
2515 // LFilter. Since filters tend to be short this is probably faster than
2516 // using a method that scales nicely.
2517 ConstantArray *FArray = cast<ConstantArray>(Filter);
2518 bool AllFound = true;
2519 for (unsigned f = 0; f != FElts; ++f) {
2520 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2522 for (unsigned l = 0; l != LElts; ++l) {
2523 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2524 if (LTypeInfo == FTypeInfo) {
2534 NewClauses.erase(J);
2535 MakeNewInstruction = true;
2537 // Move on to the next filter.
2541 // If we changed any of the clauses, replace the old landingpad instruction
2543 if (MakeNewInstruction) {
2544 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2545 LI.getPersonalityFn(),
2547 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2548 NLI->addClause(NewClauses[i]);
2549 // A landing pad with no clauses must have the cleanup flag set. It is
2550 // theoretically possible, though highly unlikely, that we eliminated all
2551 // clauses. If so, force the cleanup flag to true.
2552 if (NewClauses.empty())
2554 NLI->setCleanup(CleanupFlag);
2558 // Even if none of the clauses changed, we may nonetheless have understood
2559 // that the cleanup flag is pointless. Clear it if so.
2560 if (LI.isCleanup() != CleanupFlag) {
2561 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2562 LI.setCleanup(CleanupFlag);
2572 /// TryToSinkInstruction - Try to move the specified instruction from its
2573 /// current block into the beginning of DestBlock, which can only happen if it's
2574 /// safe to move the instruction past all of the instructions between it and the
2575 /// end of its block.
2576 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2577 assert(I->hasOneUse() && "Invariants didn't hold!");
2579 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2580 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2581 isa<TerminatorInst>(I))
2584 // Do not sink alloca instructions out of the entry block.
2585 if (isa<AllocaInst>(I) && I->getParent() ==
2586 &DestBlock->getParent()->getEntryBlock())
2589 // We can only sink load instructions if there is nothing between the load and
2590 // the end of block that could change the value.
2591 if (I->mayReadFromMemory()) {
2592 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2594 if (Scan->mayWriteToMemory())
2598 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2599 I->moveBefore(InsertPos);
2605 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2606 /// all reachable code to the worklist.
2608 /// This has a couple of tricks to make the code faster and more powerful. In
2609 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2610 /// them to the worklist (this significantly speeds up instcombine on code where
2611 /// many instructions are dead or constant). Additionally, if we find a branch
2612 /// whose condition is a known constant, we only visit the reachable successors.
2614 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2615 SmallPtrSetImpl<BasicBlock*> &Visited,
2617 const DataLayout *DL,
2618 const TargetLibraryInfo *TLI) {
2619 bool MadeIRChange = false;
2620 SmallVector<BasicBlock*, 256> Worklist;
2621 Worklist.push_back(BB);
2623 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2624 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2627 BB = Worklist.pop_back_val();
2629 // We have now visited this block! If we've already been here, ignore it.
2630 if (!Visited.insert(BB)) continue;
2632 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2633 Instruction *Inst = BBI++;
2635 // DCE instruction if trivially dead.
2636 if (isInstructionTriviallyDead(Inst, TLI)) {
2638 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2639 Inst->eraseFromParent();
2643 // ConstantProp instruction if trivially constant.
2644 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2645 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2646 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2648 Inst->replaceAllUsesWith(C);
2650 Inst->eraseFromParent();
2655 // See if we can constant fold its operands.
2656 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2658 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2659 if (CE == nullptr) continue;
2661 Constant*& FoldRes = FoldedConstants[CE];
2663 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2667 if (FoldRes != CE) {
2669 MadeIRChange = true;
2674 InstrsForInstCombineWorklist.push_back(Inst);
2677 // Recursively visit successors. If this is a branch or switch on a
2678 // constant, only visit the reachable successor.
2679 TerminatorInst *TI = BB->getTerminator();
2680 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2681 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2682 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2683 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2684 Worklist.push_back(ReachableBB);
2687 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2688 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2689 // See if this is an explicit destination.
2690 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2692 if (i.getCaseValue() == Cond) {
2693 BasicBlock *ReachableBB = i.getCaseSuccessor();
2694 Worklist.push_back(ReachableBB);
2698 // Otherwise it is the default destination.
2699 Worklist.push_back(SI->getDefaultDest());
2704 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2705 Worklist.push_back(TI->getSuccessor(i));
2706 } while (!Worklist.empty());
2708 // Once we've found all of the instructions to add to instcombine's worklist,
2709 // add them in reverse order. This way instcombine will visit from the top
2710 // of the function down. This jives well with the way that it adds all uses
2711 // of instructions to the worklist after doing a transformation, thus avoiding
2712 // some N^2 behavior in pathological cases.
2713 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2714 InstrsForInstCombineWorklist.size());
2716 return MadeIRChange;
2719 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2720 MadeIRChange = false;
2722 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2723 << F.getName() << "\n");
2726 // Do a depth-first traversal of the function, populate the worklist with
2727 // the reachable instructions. Ignore blocks that are not reachable. Keep
2728 // track of which blocks we visit.
2729 SmallPtrSet<BasicBlock*, 64> Visited;
2730 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, DL,
2733 // Do a quick scan over the function. If we find any blocks that are
2734 // unreachable, remove any instructions inside of them. This prevents
2735 // the instcombine code from having to deal with some bad special cases.
2736 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2737 if (Visited.count(BB)) continue;
2739 // Delete the instructions backwards, as it has a reduced likelihood of
2740 // having to update as many def-use and use-def chains.
2741 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2742 while (EndInst != BB->begin()) {
2743 // Delete the next to last instruction.
2744 BasicBlock::iterator I = EndInst;
2745 Instruction *Inst = --I;
2746 if (!Inst->use_empty())
2747 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2748 if (isa<LandingPadInst>(Inst)) {
2752 if (!isa<DbgInfoIntrinsic>(Inst)) {
2754 MadeIRChange = true;
2756 Inst->eraseFromParent();
2761 while (!Worklist.isEmpty()) {
2762 Instruction *I = Worklist.RemoveOne();
2763 if (I == nullptr) continue; // skip null values.
2765 // Check to see if we can DCE the instruction.
2766 if (isInstructionTriviallyDead(I, TLI)) {
2767 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2768 EraseInstFromFunction(*I);
2770 MadeIRChange = true;
2774 // Instruction isn't dead, see if we can constant propagate it.
2775 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2776 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2777 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2779 // Add operands to the worklist.
2780 ReplaceInstUsesWith(*I, C);
2782 EraseInstFromFunction(*I);
2783 MadeIRChange = true;
2787 // See if we can trivially sink this instruction to a successor basic block.
2788 if (I->hasOneUse()) {
2789 BasicBlock *BB = I->getParent();
2790 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2791 BasicBlock *UserParent;
2793 // Get the block the use occurs in.
2794 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2795 UserParent = PN->getIncomingBlock(*I->use_begin());
2797 UserParent = UserInst->getParent();
2799 if (UserParent != BB) {
2800 bool UserIsSuccessor = false;
2801 // See if the user is one of our successors.
2802 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2803 if (*SI == UserParent) {
2804 UserIsSuccessor = true;
2808 // If the user is one of our immediate successors, and if that successor
2809 // only has us as a predecessors (we'd have to split the critical edge
2810 // otherwise), we can keep going.
2811 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2812 // Okay, the CFG is simple enough, try to sink this instruction.
2813 if (TryToSinkInstruction(I, UserParent)) {
2814 MadeIRChange = true;
2815 // We'll add uses of the sunk instruction below, but since sinking
2816 // can expose opportunities for it's *operands* add them to the
2818 for (Use &U : I->operands())
2819 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2826 // Now that we have an instruction, try combining it to simplify it.
2827 Builder->SetInsertPoint(I->getParent(), I);
2828 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2833 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2834 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2836 if (Instruction *Result = visit(*I)) {
2838 // Should we replace the old instruction with a new one?
2840 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2841 << " New = " << *Result << '\n');
2843 if (!I->getDebugLoc().isUnknown())
2844 Result->setDebugLoc(I->getDebugLoc());
2845 // Everything uses the new instruction now.
2846 I->replaceAllUsesWith(Result);
2848 // Move the name to the new instruction first.
2849 Result->takeName(I);
2851 // Push the new instruction and any users onto the worklist.
2852 Worklist.Add(Result);
2853 Worklist.AddUsersToWorkList(*Result);
2855 // Insert the new instruction into the basic block...
2856 BasicBlock *InstParent = I->getParent();
2857 BasicBlock::iterator InsertPos = I;
2859 // If we replace a PHI with something that isn't a PHI, fix up the
2861 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2862 InsertPos = InstParent->getFirstInsertionPt();
2864 InstParent->getInstList().insert(InsertPos, Result);
2866 EraseInstFromFunction(*I);
2869 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2870 << " New = " << *I << '\n');
2873 // If the instruction was modified, it's possible that it is now dead.
2874 // if so, remove it.
2875 if (isInstructionTriviallyDead(I, TLI)) {
2876 EraseInstFromFunction(*I);
2879 Worklist.AddUsersToWorkList(*I);
2882 MadeIRChange = true;
2887 return MadeIRChange;
2891 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
2894 InstCombinerLibCallSimplifier(const DataLayout *DL,
2895 const TargetLibraryInfo *TLI,
2897 : LibCallSimplifier(DL, TLI, UnsafeFPShrink) {
2901 /// replaceAllUsesWith - override so that instruction replacement
2902 /// can be defined in terms of the instruction combiner framework.
2903 void replaceAllUsesWith(Instruction *I, Value *With) const override {
2904 IC->ReplaceInstUsesWith(*I, With);
2909 bool InstCombiner::runOnFunction(Function &F) {
2910 if (skipOptnoneFunction(F))
2913 AT = &getAnalysis<AssumptionTracker>();
2914 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2915 DL = DLP ? &DLP->getDataLayout() : nullptr;
2916 TLI = &getAnalysis<TargetLibraryInfo>();
2918 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2919 Attribute::MinSize);
2921 /// Builder - This is an IRBuilder that automatically inserts new
2922 /// instructions into the worklist when they are created.
2923 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2924 TheBuilder(F.getContext(), TargetFolder(DL),
2925 InstCombineIRInserter(Worklist, AT));
2926 Builder = &TheBuilder;
2928 InstCombinerLibCallSimplifier TheSimplifier(DL, TLI, this);
2929 Simplifier = &TheSimplifier;
2931 bool EverMadeChange = false;
2933 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2935 EverMadeChange = LowerDbgDeclare(F);
2937 // Iterate while there is work to do.
2938 unsigned Iteration = 0;
2939 while (DoOneIteration(F, Iteration++))
2940 EverMadeChange = true;
2943 return EverMadeChange;
2946 FunctionPass *llvm::createInstructionCombiningPass() {
2947 return new InstCombiner();