1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "InstCombineInternal.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AssumptionCache.h"
43 #include "llvm/Analysis/CFG.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/InstructionSimplify.h"
46 #include "llvm/Analysis/LibCallSemantics.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/MemoryBuiltins.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/IR/CFG.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/IR/ValueHandle.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Transforms/Utils/Local.h"
66 using namespace llvm::PatternMatch;
68 #define DEBUG_TYPE "instcombine"
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
74 STATISTIC(NumExpand, "Number of expansions");
75 STATISTIC(NumFactor , "Number of factorizations");
76 STATISTIC(NumReassoc , "Number of reassociations");
78 Value *InstCombiner::EmitGEPOffset(User *GEP) {
79 return llvm::EmitGEPOffset(Builder, DL, GEP);
82 /// ShouldChangeType - Return true if it is desirable to convert a computation
83 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
84 /// type for example, or from a smaller to a larger illegal type.
85 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
86 assert(From->isIntegerTy() && To->isIntegerTy());
88 unsigned FromWidth = From->getPrimitiveSizeInBits();
89 unsigned ToWidth = To->getPrimitiveSizeInBits();
90 bool FromLegal = DL.isLegalInteger(FromWidth);
91 bool ToLegal = DL.isLegalInteger(ToWidth);
93 // If this is a legal integer from type, and the result would be an illegal
94 // type, don't do the transformation.
95 if (FromLegal && !ToLegal)
98 // Otherwise, if both are illegal, do not increase the size of the result. We
99 // do allow things like i160 -> i64, but not i64 -> i160.
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106 // Return true, if No Signed Wrap should be maintained for I.
107 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
108 // where both B and C should be ConstantInts, results in a constant that does
109 // not overflow. This function only handles the Add and Sub opcodes. For
110 // all other opcodes, the function conservatively returns false.
111 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
112 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
113 if (!OBO || !OBO->hasNoSignedWrap()) {
117 // We reason about Add and Sub Only.
118 Instruction::BinaryOps Opcode = I.getOpcode();
119 if (Opcode != Instruction::Add &&
120 Opcode != Instruction::Sub) {
124 ConstantInt *CB = dyn_cast<ConstantInt>(B);
125 ConstantInt *CC = dyn_cast<ConstantInt>(C);
131 const APInt &BVal = CB->getValue();
132 const APInt &CVal = CC->getValue();
133 bool Overflow = false;
135 if (Opcode == Instruction::Add) {
136 BVal.sadd_ov(CVal, Overflow);
138 BVal.ssub_ov(CVal, Overflow);
144 /// Conservatively clears subclassOptionalData after a reassociation or
145 /// commutation. We preserve fast-math flags when applicable as they can be
147 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
148 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
150 I.clearSubclassOptionalData();
154 FastMathFlags FMF = I.getFastMathFlags();
155 I.clearSubclassOptionalData();
156 I.setFastMathFlags(FMF);
159 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
160 /// operators which are associative or commutative:
162 // Commutative operators:
164 // 1. Order operands such that they are listed from right (least complex) to
165 // left (most complex). This puts constants before unary operators before
168 // Associative operators:
170 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
171 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
173 // Associative and commutative operators:
175 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
176 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
177 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
178 // if C1 and C2 are constants.
180 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
181 Instruction::BinaryOps Opcode = I.getOpcode();
182 bool Changed = false;
185 // Order operands such that they are listed from right (least complex) to
186 // left (most complex). This puts constants before unary operators before
188 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
189 getComplexity(I.getOperand(1)))
190 Changed = !I.swapOperands();
192 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
193 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
195 if (I.isAssociative()) {
196 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
197 if (Op0 && Op0->getOpcode() == Opcode) {
198 Value *A = Op0->getOperand(0);
199 Value *B = Op0->getOperand(1);
200 Value *C = I.getOperand(1);
202 // Does "B op C" simplify?
203 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
204 // It simplifies to V. Form "A op V".
207 // Conservatively clear the optional flags, since they may not be
208 // preserved by the reassociation.
209 if (MaintainNoSignedWrap(I, B, C) &&
210 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
211 // Note: this is only valid because SimplifyBinOp doesn't look at
212 // the operands to Op0.
213 I.clearSubclassOptionalData();
214 I.setHasNoSignedWrap(true);
216 ClearSubclassDataAfterReassociation(I);
225 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
226 if (Op1 && Op1->getOpcode() == Opcode) {
227 Value *A = I.getOperand(0);
228 Value *B = Op1->getOperand(0);
229 Value *C = Op1->getOperand(1);
231 // Does "A op B" simplify?
232 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
233 // It simplifies to V. Form "V op C".
236 // Conservatively clear the optional flags, since they may not be
237 // preserved by the reassociation.
238 ClearSubclassDataAfterReassociation(I);
246 if (I.isAssociative() && I.isCommutative()) {
247 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
248 if (Op0 && Op0->getOpcode() == Opcode) {
249 Value *A = Op0->getOperand(0);
250 Value *B = Op0->getOperand(1);
251 Value *C = I.getOperand(1);
253 // Does "C op A" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
255 // It simplifies to V. Form "V op B".
258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
260 ClearSubclassDataAfterReassociation(I);
267 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
268 if (Op1 && Op1->getOpcode() == Opcode) {
269 Value *A = I.getOperand(0);
270 Value *B = Op1->getOperand(0);
271 Value *C = Op1->getOperand(1);
273 // Does "C op A" simplify?
274 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
275 // It simplifies to V. Form "B op V".
278 // Conservatively clear the optional flags, since they may not be
279 // preserved by the reassociation.
280 ClearSubclassDataAfterReassociation(I);
287 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
288 // if C1 and C2 are constants.
290 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
291 isa<Constant>(Op0->getOperand(1)) &&
292 isa<Constant>(Op1->getOperand(1)) &&
293 Op0->hasOneUse() && Op1->hasOneUse()) {
294 Value *A = Op0->getOperand(0);
295 Constant *C1 = cast<Constant>(Op0->getOperand(1));
296 Value *B = Op1->getOperand(0);
297 Constant *C2 = cast<Constant>(Op1->getOperand(1));
299 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
300 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
301 if (isa<FPMathOperator>(New)) {
302 FastMathFlags Flags = I.getFastMathFlags();
303 Flags &= Op0->getFastMathFlags();
304 Flags &= Op1->getFastMathFlags();
305 New->setFastMathFlags(Flags);
307 InsertNewInstWith(New, I);
309 I.setOperand(0, New);
310 I.setOperand(1, Folded);
311 // Conservatively clear the optional flags, since they may not be
312 // preserved by the reassociation.
313 ClearSubclassDataAfterReassociation(I);
320 // No further simplifications.
325 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
326 /// "(X LOp Y) ROp (X LOp Z)".
327 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
328 Instruction::BinaryOps ROp) {
333 case Instruction::And:
334 // And distributes over Or and Xor.
338 case Instruction::Or:
339 case Instruction::Xor:
343 case Instruction::Mul:
344 // Multiplication distributes over addition and subtraction.
348 case Instruction::Add:
349 case Instruction::Sub:
353 case Instruction::Or:
354 // Or distributes over And.
358 case Instruction::And:
364 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
365 /// "(X ROp Z) LOp (Y ROp Z)".
366 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
367 Instruction::BinaryOps ROp) {
368 if (Instruction::isCommutative(ROp))
369 return LeftDistributesOverRight(ROp, LOp);
374 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
375 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
376 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
377 case Instruction::And:
378 case Instruction::Or:
379 case Instruction::Xor:
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
389 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
390 // but this requires knowing that the addition does not overflow and other
395 /// This function returns identity value for given opcode, which can be used to
396 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
397 static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
398 if (isa<Constant>(V))
401 if (OpCode == Instruction::Mul)
402 return ConstantInt::get(V->getType(), 1);
404 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
409 /// This function factors binary ops which can be combined using distributive
410 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
411 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
412 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
413 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
415 static Instruction::BinaryOps
416 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
417 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
419 return Instruction::BinaryOpsEnd;
421 LHS = Op->getOperand(0);
422 RHS = Op->getOperand(1);
424 switch (TopLevelOpcode) {
426 return Op->getOpcode();
428 case Instruction::Add:
429 case Instruction::Sub:
430 if (Op->getOpcode() == Instruction::Shl) {
431 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
432 // The multiplier is really 1 << CST.
433 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
434 return Instruction::Mul;
437 return Op->getOpcode();
440 // TODO: We can add other conversions e.g. shr => div etc.
443 /// This tries to simplify binary operations by factorizing out common terms
444 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
445 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
446 const DataLayout &DL, BinaryOperator &I,
447 Instruction::BinaryOps InnerOpcode, Value *A,
448 Value *B, Value *C, Value *D) {
450 // If any of A, B, C, D are null, we can not factor I, return early.
451 // Checking A and C should be enough.
452 if (!A || !C || !B || !D)
456 Value *SimplifiedInst = nullptr;
457 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
458 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
460 // Does "X op' Y" always equal "Y op' X"?
461 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
463 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
464 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
465 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
466 // commutative case, "(A op' B) op (C op' A)"?
467 if (A == C || (InnerCommutative && A == D)) {
470 // Consider forming "A op' (B op D)".
471 // If "B op D" simplifies then it can be formed with no cost.
472 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
473 // If "B op D" doesn't simplify then only go on if both of the existing
474 // operations "A op' B" and "C op' D" will be zapped as no longer used.
475 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
476 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
478 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
482 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
483 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
484 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
485 // commutative case, "(A op' B) op (B op' D)"?
486 if (B == D || (InnerCommutative && B == C)) {
489 // Consider forming "(A op C) op' B".
490 // If "A op C" simplifies then it can be formed with no cost.
491 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
493 // If "A op C" doesn't simplify then only go on if both of the existing
494 // operations "A op' B" and "C op' D" will be zapped as no longer used.
495 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
496 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
498 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
502 if (SimplifiedInst) {
504 SimplifiedInst->takeName(&I);
506 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
507 // TODO: Check for NUW.
508 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
509 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
511 if (isa<OverflowingBinaryOperator>(&I))
512 HasNSW = I.hasNoSignedWrap();
514 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
515 if (isa<OverflowingBinaryOperator>(Op0))
516 HasNSW &= Op0->hasNoSignedWrap();
518 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
519 if (isa<OverflowingBinaryOperator>(Op1))
520 HasNSW &= Op1->hasNoSignedWrap();
522 // We can propogate 'nsw' if we know that
523 // %Y = mul nsw i16 %X, C
524 // %Z = add nsw i16 %Y, %X
526 // %Z = mul nsw i16 %X, C+1
528 // iff C+1 isn't INT_MIN
530 if (TopLevelOpcode == Instruction::Add &&
531 InnerOpcode == Instruction::Mul)
532 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
533 BO->setHasNoSignedWrap(HasNSW);
537 return SimplifiedInst;
540 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
541 /// which some other binary operation distributes over either by factorizing
542 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
543 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
544 /// a win). Returns the simplified value, or null if it didn't simplify.
545 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
546 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
547 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
548 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
551 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
552 auto TopLevelOpcode = I.getOpcode();
553 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
554 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
556 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
558 if (LHSOpcode == RHSOpcode) {
559 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
563 // The instruction has the form "(A op' B) op (C)". Try to factorize common
565 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
566 getIdentityValue(LHSOpcode, RHS)))
569 // The instruction has the form "(B) op (C op' D)". Try to factorize common
571 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
572 getIdentityValue(RHSOpcode, LHS), C, D))
576 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
577 // The instruction has the form "(A op' B) op C". See if expanding it out
578 // to "(A op C) op' (B op C)" results in simplifications.
579 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
580 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
582 // Do "A op C" and "B op C" both simplify?
583 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
584 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
585 // They do! Return "L op' R".
587 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
588 if ((L == A && R == B) ||
589 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
591 // Otherwise return "L op' R" if it simplifies.
592 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
594 // Otherwise, create a new instruction.
595 C = Builder->CreateBinOp(InnerOpcode, L, R);
601 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
602 // The instruction has the form "A op (B op' C)". See if expanding it out
603 // to "(A op B) op' (A op C)" results in simplifications.
604 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
605 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
607 // Do "A op B" and "A op C" both simplify?
608 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
609 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
610 // They do! Return "L op' R".
612 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
613 if ((L == B && R == C) ||
614 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
616 // Otherwise return "L op' R" if it simplifies.
617 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
619 // Otherwise, create a new instruction.
620 A = Builder->CreateBinOp(InnerOpcode, L, R);
629 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
630 // if the LHS is a constant zero (which is the 'negate' form).
632 Value *InstCombiner::dyn_castNegVal(Value *V) const {
633 if (BinaryOperator::isNeg(V))
634 return BinaryOperator::getNegArgument(V);
636 // Constants can be considered to be negated values if they can be folded.
637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
638 return ConstantExpr::getNeg(C);
640 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
641 if (C->getType()->getElementType()->isIntegerTy())
642 return ConstantExpr::getNeg(C);
647 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
648 // instruction if the LHS is a constant negative zero (which is the 'negate'
651 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
652 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
653 return BinaryOperator::getFNegArgument(V);
655 // Constants can be considered to be negated values if they can be folded.
656 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
657 return ConstantExpr::getFNeg(C);
659 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
660 if (C->getType()->getElementType()->isFloatingPointTy())
661 return ConstantExpr::getFNeg(C);
666 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
668 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
669 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
672 // Figure out if the constant is the left or the right argument.
673 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
674 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
676 if (Constant *SOC = dyn_cast<Constant>(SO)) {
678 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
679 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
682 Value *Op0 = SO, *Op1 = ConstOperand;
686 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
687 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
688 SO->getName()+".op");
689 Instruction *FPInst = dyn_cast<Instruction>(RI);
690 if (FPInst && isa<FPMathOperator>(FPInst))
691 FPInst->copyFastMathFlags(BO);
694 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
695 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
696 SO->getName()+".cmp");
697 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
698 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
699 SO->getName()+".cmp");
700 llvm_unreachable("Unknown binary instruction type!");
703 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
704 // constant as the other operand, try to fold the binary operator into the
705 // select arguments. This also works for Cast instructions, which obviously do
706 // not have a second operand.
707 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
708 // Don't modify shared select instructions
709 if (!SI->hasOneUse()) return nullptr;
710 Value *TV = SI->getOperand(1);
711 Value *FV = SI->getOperand(2);
713 if (isa<Constant>(TV) || isa<Constant>(FV)) {
714 // Bool selects with constant operands can be folded to logical ops.
715 if (SI->getType()->isIntegerTy(1)) return nullptr;
717 // If it's a bitcast involving vectors, make sure it has the same number of
718 // elements on both sides.
719 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
720 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
721 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
723 // Verify that either both or neither are vectors.
724 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
725 // If vectors, verify that they have the same number of elements.
726 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
730 // Test if a CmpInst instruction is used exclusively by a select as
731 // part of a minimum or maximum operation. If so, refrain from doing
732 // any other folding. This helps out other analyses which understand
733 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
734 // and CodeGen. And in this case, at least one of the comparison
735 // operands has at least one user besides the compare (the select),
736 // which would often largely negate the benefit of folding anyway.
737 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
738 if (CI->hasOneUse()) {
739 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
740 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
741 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
746 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
747 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
749 return SelectInst::Create(SI->getCondition(),
750 SelectTrueVal, SelectFalseVal);
755 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
756 /// has a PHI node as operand #0, see if we can fold the instruction into the
757 /// PHI (which is only possible if all operands to the PHI are constants).
759 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
760 PHINode *PN = cast<PHINode>(I.getOperand(0));
761 unsigned NumPHIValues = PN->getNumIncomingValues();
762 if (NumPHIValues == 0)
765 // We normally only transform phis with a single use. However, if a PHI has
766 // multiple uses and they are all the same operation, we can fold *all* of the
767 // uses into the PHI.
768 if (!PN->hasOneUse()) {
769 // Walk the use list for the instruction, comparing them to I.
770 for (User *U : PN->users()) {
771 Instruction *UI = cast<Instruction>(U);
772 if (UI != &I && !I.isIdenticalTo(UI))
775 // Otherwise, we can replace *all* users with the new PHI we form.
778 // Check to see if all of the operands of the PHI are simple constants
779 // (constantint/constantfp/undef). If there is one non-constant value,
780 // remember the BB it is in. If there is more than one or if *it* is a PHI,
781 // bail out. We don't do arbitrary constant expressions here because moving
782 // their computation can be expensive without a cost model.
783 BasicBlock *NonConstBB = nullptr;
784 for (unsigned i = 0; i != NumPHIValues; ++i) {
785 Value *InVal = PN->getIncomingValue(i);
786 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
789 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
790 if (NonConstBB) return nullptr; // More than one non-const value.
792 NonConstBB = PN->getIncomingBlock(i);
794 // If the InVal is an invoke at the end of the pred block, then we can't
795 // insert a computation after it without breaking the edge.
796 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
797 if (II->getParent() == NonConstBB)
800 // If the incoming non-constant value is in I's block, we will remove one
801 // instruction, but insert another equivalent one, leading to infinite
803 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
807 // If there is exactly one non-constant value, we can insert a copy of the
808 // operation in that block. However, if this is a critical edge, we would be
809 // inserting the computation on some other paths (e.g. inside a loop). Only
810 // do this if the pred block is unconditionally branching into the phi block.
811 if (NonConstBB != nullptr) {
812 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
813 if (!BI || !BI->isUnconditional()) return nullptr;
816 // Okay, we can do the transformation: create the new PHI node.
817 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
818 InsertNewInstBefore(NewPN, *PN);
821 // If we are going to have to insert a new computation, do so right before the
822 // predecessors terminator.
824 Builder->SetInsertPoint(NonConstBB->getTerminator());
826 // Next, add all of the operands to the PHI.
827 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
828 // We only currently try to fold the condition of a select when it is a phi,
829 // not the true/false values.
830 Value *TrueV = SI->getTrueValue();
831 Value *FalseV = SI->getFalseValue();
832 BasicBlock *PhiTransBB = PN->getParent();
833 for (unsigned i = 0; i != NumPHIValues; ++i) {
834 BasicBlock *ThisBB = PN->getIncomingBlock(i);
835 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
836 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
837 Value *InV = nullptr;
838 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
839 // even if currently isNullValue gives false.
840 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
841 if (InC && !isa<ConstantExpr>(InC))
842 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
844 InV = Builder->CreateSelect(PN->getIncomingValue(i),
845 TrueVInPred, FalseVInPred, "phitmp");
846 NewPN->addIncoming(InV, ThisBB);
848 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
849 Constant *C = cast<Constant>(I.getOperand(1));
850 for (unsigned i = 0; i != NumPHIValues; ++i) {
851 Value *InV = nullptr;
852 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
853 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
854 else if (isa<ICmpInst>(CI))
855 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
858 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
860 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
862 } else if (I.getNumOperands() == 2) {
863 Constant *C = cast<Constant>(I.getOperand(1));
864 for (unsigned i = 0; i != NumPHIValues; ++i) {
865 Value *InV = nullptr;
866 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
867 InV = ConstantExpr::get(I.getOpcode(), InC, C);
869 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
870 PN->getIncomingValue(i), C, "phitmp");
871 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
874 CastInst *CI = cast<CastInst>(&I);
875 Type *RetTy = CI->getType();
876 for (unsigned i = 0; i != NumPHIValues; ++i) {
878 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
879 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
881 InV = Builder->CreateCast(CI->getOpcode(),
882 PN->getIncomingValue(i), I.getType(), "phitmp");
883 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
887 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
888 Instruction *User = cast<Instruction>(*UI++);
889 if (User == &I) continue;
890 ReplaceInstUsesWith(*User, NewPN);
891 EraseInstFromFunction(*User);
893 return ReplaceInstUsesWith(I, NewPN);
896 /// FindElementAtOffset - Given a pointer type and a constant offset, determine
897 /// whether or not there is a sequence of GEP indices into the pointed type that
898 /// will land us at the specified offset. If so, fill them into NewIndices and
899 /// return the resultant element type, otherwise return null.
900 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
901 SmallVectorImpl<Value *> &NewIndices) {
902 Type *Ty = PtrTy->getElementType();
906 // Start with the index over the outer type. Note that the type size
907 // might be zero (even if the offset isn't zero) if the indexed type
908 // is something like [0 x {int, int}]
909 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
910 int64_t FirstIdx = 0;
911 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
912 FirstIdx = Offset/TySize;
913 Offset -= FirstIdx*TySize;
915 // Handle hosts where % returns negative instead of values [0..TySize).
921 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
924 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
926 // Index into the types. If we fail, set OrigBase to null.
928 // Indexing into tail padding between struct/array elements.
929 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
932 if (StructType *STy = dyn_cast<StructType>(Ty)) {
933 const StructLayout *SL = DL.getStructLayout(STy);
934 assert(Offset < (int64_t)SL->getSizeInBytes() &&
935 "Offset must stay within the indexed type");
937 unsigned Elt = SL->getElementContainingOffset(Offset);
938 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
941 Offset -= SL->getElementOffset(Elt);
942 Ty = STy->getElementType(Elt);
943 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
944 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
945 assert(EltSize && "Cannot index into a zero-sized array");
946 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
948 Ty = AT->getElementType();
950 // Otherwise, we can't index into the middle of this atomic type, bail.
958 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
959 // If this GEP has only 0 indices, it is the same pointer as
960 // Src. If Src is not a trivial GEP too, don't combine
962 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
968 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
969 /// the multiplication is known not to overflow then NoSignedWrap is set.
970 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
971 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
972 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
973 Scale.getBitWidth() && "Scale not compatible with value!");
975 // If Val is zero or Scale is one then Val = Val * Scale.
976 if (match(Val, m_Zero()) || Scale == 1) {
981 // If Scale is zero then it does not divide Val.
982 if (Scale.isMinValue())
985 // Look through chains of multiplications, searching for a constant that is
986 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
987 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
988 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
991 // Val = M1 * X || Analysis starts here and works down
992 // M1 = M2 * Y || Doesn't descend into terms with more
993 // M2 = Z * 4 \/ than one use
995 // Then to modify a term at the bottom:
998 // M1 = Z * Y || Replaced M2 with Z
1000 // Then to work back up correcting nsw flags.
1002 // Op - the term we are currently analyzing. Starts at Val then drills down.
1003 // Replaced with its descaled value before exiting from the drill down loop.
1006 // Parent - initially null, but after drilling down notes where Op came from.
1007 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1008 // 0'th operand of Val.
1009 std::pair<Instruction*, unsigned> Parent;
1011 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
1012 // levels that doesn't overflow.
1013 bool RequireNoSignedWrap = false;
1015 // logScale - log base 2 of the scale. Negative if not a power of 2.
1016 int32_t logScale = Scale.exactLogBase2();
1018 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1020 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1021 // If Op is a constant divisible by Scale then descale to the quotient.
1022 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1023 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1024 if (!Remainder.isMinValue())
1025 // Not divisible by Scale.
1027 // Replace with the quotient in the parent.
1028 Op = ConstantInt::get(CI->getType(), Quotient);
1029 NoSignedWrap = true;
1033 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1035 if (BO->getOpcode() == Instruction::Mul) {
1037 NoSignedWrap = BO->hasNoSignedWrap();
1038 if (RequireNoSignedWrap && !NoSignedWrap)
1041 // There are three cases for multiplication: multiplication by exactly
1042 // the scale, multiplication by a constant different to the scale, and
1043 // multiplication by something else.
1044 Value *LHS = BO->getOperand(0);
1045 Value *RHS = BO->getOperand(1);
1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1048 // Multiplication by a constant.
1049 if (CI->getValue() == Scale) {
1050 // Multiplication by exactly the scale, replace the multiplication
1051 // by its left-hand side in the parent.
1056 // Otherwise drill down into the constant.
1057 if (!Op->hasOneUse())
1060 Parent = std::make_pair(BO, 1);
1064 // Multiplication by something else. Drill down into the left-hand side
1065 // since that's where the reassociate pass puts the good stuff.
1066 if (!Op->hasOneUse())
1069 Parent = std::make_pair(BO, 0);
1073 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1074 isa<ConstantInt>(BO->getOperand(1))) {
1075 // Multiplication by a power of 2.
1076 NoSignedWrap = BO->hasNoSignedWrap();
1077 if (RequireNoSignedWrap && !NoSignedWrap)
1080 Value *LHS = BO->getOperand(0);
1081 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1082 getLimitedValue(Scale.getBitWidth());
1085 if (Amt == logScale) {
1086 // Multiplication by exactly the scale, replace the multiplication
1087 // by its left-hand side in the parent.
1091 if (Amt < logScale || !Op->hasOneUse())
1094 // Multiplication by more than the scale. Reduce the multiplying amount
1095 // by the scale in the parent.
1096 Parent = std::make_pair(BO, 1);
1097 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1102 if (!Op->hasOneUse())
1105 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1106 if (Cast->getOpcode() == Instruction::SExt) {
1107 // Op is sign-extended from a smaller type, descale in the smaller type.
1108 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1109 APInt SmallScale = Scale.trunc(SmallSize);
1110 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1111 // descale Op as (sext Y) * Scale. In order to have
1112 // sext (Y * SmallScale) = (sext Y) * Scale
1113 // some conditions need to hold however: SmallScale must sign-extend to
1114 // Scale and the multiplication Y * SmallScale should not overflow.
1115 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1116 // SmallScale does not sign-extend to Scale.
1118 assert(SmallScale.exactLogBase2() == logScale);
1119 // Require that Y * SmallScale must not overflow.
1120 RequireNoSignedWrap = true;
1122 // Drill down through the cast.
1123 Parent = std::make_pair(Cast, 0);
1128 if (Cast->getOpcode() == Instruction::Trunc) {
1129 // Op is truncated from a larger type, descale in the larger type.
1130 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1131 // trunc (Y * sext Scale) = (trunc Y) * Scale
1132 // always holds. However (trunc Y) * Scale may overflow even if
1133 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1134 // from this point up in the expression (see later).
1135 if (RequireNoSignedWrap)
1138 // Drill down through the cast.
1139 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1140 Parent = std::make_pair(Cast, 0);
1141 Scale = Scale.sext(LargeSize);
1142 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1144 assert(Scale.exactLogBase2() == logScale);
1149 // Unsupported expression, bail out.
1153 // If Op is zero then Val = Op * Scale.
1154 if (match(Op, m_Zero())) {
1155 NoSignedWrap = true;
1159 // We know that we can successfully descale, so from here on we can safely
1160 // modify the IR. Op holds the descaled version of the deepest term in the
1161 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1165 // The expression only had one term.
1168 // Rewrite the parent using the descaled version of its operand.
1169 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1170 assert(Op != Parent.first->getOperand(Parent.second) &&
1171 "Descaling was a no-op?");
1172 Parent.first->setOperand(Parent.second, Op);
1173 Worklist.Add(Parent.first);
1175 // Now work back up the expression correcting nsw flags. The logic is based
1176 // on the following observation: if X * Y is known not to overflow as a signed
1177 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1178 // then X * Z will not overflow as a signed multiplication either. As we work
1179 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1180 // current level has strictly smaller absolute value than the original.
1181 Instruction *Ancestor = Parent.first;
1183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1184 // If the multiplication wasn't nsw then we can't say anything about the
1185 // value of the descaled multiplication, and we have to clear nsw flags
1186 // from this point on up.
1187 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1188 NoSignedWrap &= OpNoSignedWrap;
1189 if (NoSignedWrap != OpNoSignedWrap) {
1190 BO->setHasNoSignedWrap(NoSignedWrap);
1191 Worklist.Add(Ancestor);
1193 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1194 // The fact that the descaled input to the trunc has smaller absolute
1195 // value than the original input doesn't tell us anything useful about
1196 // the absolute values of the truncations.
1197 NoSignedWrap = false;
1199 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1200 "Failed to keep proper track of nsw flags while drilling down?");
1202 if (Ancestor == Val)
1203 // Got to the top, all done!
1206 // Move up one level in the expression.
1207 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1208 Ancestor = Ancestor->user_back();
1212 /// \brief Creates node of binary operation with the same attributes as the
1213 /// specified one but with other operands.
1214 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1215 InstCombiner::BuilderTy *B) {
1216 Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1217 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) {
1218 if (isa<OverflowingBinaryOperator>(NewBO)) {
1219 NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap());
1220 NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap());
1222 if (isa<PossiblyExactOperator>(NewBO))
1223 NewBO->setIsExact(Inst.isExact());
1228 /// \brief Makes transformation of binary operation specific for vector types.
1229 /// \param Inst Binary operator to transform.
1230 /// \return Pointer to node that must replace the original binary operator, or
1231 /// null pointer if no transformation was made.
1232 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1233 if (!Inst.getType()->isVectorTy()) return nullptr;
1235 // It may not be safe to reorder shuffles and things like div, urem, etc.
1236 // because we may trap when executing those ops on unknown vector elements.
1238 if (!isSafeToSpeculativelyExecute(&Inst))
1241 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1242 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1243 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1244 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1246 // If both arguments of binary operation are shuffles, which use the same
1247 // mask and shuffle within a single vector, it is worthwhile to move the
1248 // shuffle after binary operation:
1249 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1250 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1251 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1252 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1253 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1254 isa<UndefValue>(RShuf->getOperand(1)) &&
1255 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
1256 LShuf->getMask() == RShuf->getMask()) {
1257 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1258 RShuf->getOperand(0), Builder);
1259 Value *Res = Builder->CreateShuffleVector(NewBO,
1260 UndefValue::get(NewBO->getType()), LShuf->getMask());
1265 // If one argument is a shuffle within one vector, the other is a constant,
1266 // try moving the shuffle after the binary operation.
1267 ShuffleVectorInst *Shuffle = nullptr;
1268 Constant *C1 = nullptr;
1269 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1270 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1271 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1272 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1273 if (Shuffle && C1 &&
1274 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1275 isa<UndefValue>(Shuffle->getOperand(1)) &&
1276 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1277 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1278 // Find constant C2 that has property:
1279 // shuffle(C2, ShMask) = C1
1280 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1281 // reorder is not possible.
1282 SmallVector<Constant*, 16> C2M(VWidth,
1283 UndefValue::get(C1->getType()->getScalarType()));
1284 bool MayChange = true;
1285 for (unsigned I = 0; I < VWidth; ++I) {
1286 if (ShMask[I] >= 0) {
1287 assert(ShMask[I] < (int)VWidth);
1288 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1292 C2M[ShMask[I]] = C1->getAggregateElement(I);
1296 Constant *C2 = ConstantVector::get(C2M);
1297 Value *NewLHS, *NewRHS;
1298 if (isa<Constant>(LHS)) {
1300 NewRHS = Shuffle->getOperand(0);
1302 NewLHS = Shuffle->getOperand(0);
1305 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1306 Value *Res = Builder->CreateShuffleVector(NewBO,
1307 UndefValue::get(Inst.getType()), Shuffle->getMask());
1315 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1316 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1318 if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC))
1319 return ReplaceInstUsesWith(GEP, V);
1321 Value *PtrOp = GEP.getOperand(0);
1323 // Eliminate unneeded casts for indices, and replace indices which displace
1324 // by multiples of a zero size type with zero.
1325 bool MadeChange = false;
1326 Type *IntPtrTy = DL.getIntPtrType(GEP.getPointerOperandType());
1328 gep_type_iterator GTI = gep_type_begin(GEP);
1329 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1331 // Skip indices into struct types.
1332 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1336 // If the element type has zero size then any index over it is equivalent
1337 // to an index of zero, so replace it with zero if it is not zero already.
1338 if (SeqTy->getElementType()->isSized() &&
1339 DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1340 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1341 *I = Constant::getNullValue(IntPtrTy);
1345 Type *IndexTy = (*I)->getType();
1346 if (IndexTy != IntPtrTy) {
1347 // If we are using a wider index than needed for this platform, shrink
1348 // it to what we need. If narrower, sign-extend it to what we need.
1349 // This explicit cast can make subsequent optimizations more obvious.
1350 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1357 // Check to see if the inputs to the PHI node are getelementptr instructions.
1358 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1359 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1363 // Don't fold a GEP into itself through a PHI node. This can only happen
1364 // through the back-edge of a loop. Folding a GEP into itself means that
1365 // the value of the previous iteration needs to be stored in the meantime,
1366 // thus requiring an additional register variable to be live, but not
1367 // actually achieving anything (the GEP still needs to be executed once per
1374 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1375 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1376 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1379 // As for Op1 above, don't try to fold a GEP into itself.
1383 // Keep track of the type as we walk the GEP.
1384 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1386 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1387 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1390 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1392 // We have not seen any differences yet in the GEPs feeding the
1393 // PHI yet, so we record this one if it is allowed to be a
1396 // The first two arguments can vary for any GEP, the rest have to be
1397 // static for struct slots
1398 if (J > 1 && CurTy->isStructTy())
1403 // The GEP is different by more than one input. While this could be
1404 // extended to support GEPs that vary by more than one variable it
1405 // doesn't make sense since it greatly increases the complexity and
1406 // would result in an R+R+R addressing mode which no backend
1407 // directly supports and would need to be broken into several
1408 // simpler instructions anyway.
1413 // Sink down a layer of the type for the next iteration.
1415 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1416 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1424 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1427 // All the GEPs feeding the PHI are identical. Clone one down into our
1428 // BB so that it can be merged with the current GEP.
1429 GEP.getParent()->getInstList().insert(
1430 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1432 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1433 // into the current block so it can be merged, and create a new PHI to
1435 Instruction *InsertPt = Builder->GetInsertPoint();
1436 Builder->SetInsertPoint(PN);
1437 PHINode *NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1438 PN->getNumOperands());
1439 Builder->SetInsertPoint(InsertPt);
1441 for (auto &I : PN->operands())
1442 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1443 PN->getIncomingBlock(I));
1445 NewGEP->setOperand(DI, NewPN);
1446 GEP.getParent()->getInstList().insert(
1447 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1448 NewGEP->setOperand(DI, NewPN);
1451 GEP.setOperand(0, NewGEP);
1455 // Combine Indices - If the source pointer to this getelementptr instruction
1456 // is a getelementptr instruction, combine the indices of the two
1457 // getelementptr instructions into a single instruction.
1459 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1460 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1463 // Note that if our source is a gep chain itself then we wait for that
1464 // chain to be resolved before we perform this transformation. This
1465 // avoids us creating a TON of code in some cases.
1466 if (GEPOperator *SrcGEP =
1467 dyn_cast<GEPOperator>(Src->getOperand(0)))
1468 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1469 return nullptr; // Wait until our source is folded to completion.
1471 SmallVector<Value*, 8> Indices;
1473 // Find out whether the last index in the source GEP is a sequential idx.
1474 bool EndsWithSequential = false;
1475 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1477 EndsWithSequential = !(*I)->isStructTy();
1479 // Can we combine the two pointer arithmetics offsets?
1480 if (EndsWithSequential) {
1481 // Replace: gep (gep %P, long B), long A, ...
1482 // With: T = long A+B; gep %P, T, ...
1485 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1486 Value *GO1 = GEP.getOperand(1);
1487 if (SO1 == Constant::getNullValue(SO1->getType())) {
1489 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1492 // If they aren't the same type, then the input hasn't been processed
1493 // by the loop above yet (which canonicalizes sequential index types to
1494 // intptr_t). Just avoid transforming this until the input has been
1496 if (SO1->getType() != GO1->getType())
1498 // Only do the combine when GO1 and SO1 are both constants. Only in
1499 // this case, we are sure the cost after the merge is never more than
1500 // that before the merge.
1501 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1503 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1506 // Update the GEP in place if possible.
1507 if (Src->getNumOperands() == 2) {
1508 GEP.setOperand(0, Src->getOperand(0));
1509 GEP.setOperand(1, Sum);
1512 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1513 Indices.push_back(Sum);
1514 Indices.append(GEP.op_begin()+2, GEP.op_end());
1515 } else if (isa<Constant>(*GEP.idx_begin()) &&
1516 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1517 Src->getNumOperands() != 1) {
1518 // Otherwise we can do the fold if the first index of the GEP is a zero
1519 Indices.append(Src->op_begin()+1, Src->op_end());
1520 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1523 if (!Indices.empty())
1524 return GEP.isInBounds() && Src->isInBounds()
1525 ? GetElementPtrInst::CreateInBounds(
1526 Src->getSourceElementType(), Src->getOperand(0), Indices,
1528 : GetElementPtrInst::Create(Src->getSourceElementType(),
1529 Src->getOperand(0), Indices,
1533 if (GEP.getNumIndices() == 1) {
1534 unsigned AS = GEP.getPointerAddressSpace();
1535 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1536 DL.getPointerSizeInBits(AS)) {
1537 Type *PtrTy = GEP.getPointerOperandType();
1538 Type *Ty = PtrTy->getPointerElementType();
1539 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1541 bool Matched = false;
1544 if (TyAllocSize == 1) {
1545 V = GEP.getOperand(1);
1547 } else if (match(GEP.getOperand(1),
1548 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1549 if (TyAllocSize == 1ULL << C)
1551 } else if (match(GEP.getOperand(1),
1552 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1553 if (TyAllocSize == C)
1558 // Canonicalize (gep i8* X, -(ptrtoint Y))
1559 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1560 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1561 // pointer arithmetic.
1562 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1563 Operator *Index = cast<Operator>(V);
1564 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1565 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1566 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1568 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1571 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1572 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1573 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1580 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1581 Value *StrippedPtr = PtrOp->stripPointerCasts();
1582 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1584 // We do not handle pointer-vector geps here.
1588 if (StrippedPtr != PtrOp) {
1589 bool HasZeroPointerIndex = false;
1590 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1591 HasZeroPointerIndex = C->isZero();
1593 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1594 // into : GEP [10 x i8]* X, i32 0, ...
1596 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1597 // into : GEP i8* X, ...
1599 // This occurs when the program declares an array extern like "int X[];"
1600 if (HasZeroPointerIndex) {
1601 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1602 if (ArrayType *CATy =
1603 dyn_cast<ArrayType>(CPTy->getElementType())) {
1604 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1605 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1606 // -> GEP i8* X, ...
1607 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1608 GetElementPtrInst *Res = GetElementPtrInst::Create(
1609 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1610 Res->setIsInBounds(GEP.isInBounds());
1611 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1613 // Insert Res, and create an addrspacecast.
1615 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1617 // %0 = GEP i8 addrspace(1)* X, ...
1618 // addrspacecast i8 addrspace(1)* %0 to i8*
1619 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1622 if (ArrayType *XATy =
1623 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1624 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1625 if (CATy->getElementType() == XATy->getElementType()) {
1626 // -> GEP [10 x i8]* X, i32 0, ...
1627 // At this point, we know that the cast source type is a pointer
1628 // to an array of the same type as the destination pointer
1629 // array. Because the array type is never stepped over (there
1630 // is a leading zero) we can fold the cast into this GEP.
1631 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1632 GEP.setOperand(0, StrippedPtr);
1633 GEP.setSourceElementType(XATy);
1636 // Cannot replace the base pointer directly because StrippedPtr's
1637 // address space is different. Instead, create a new GEP followed by
1638 // an addrspacecast.
1640 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1643 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1644 // addrspacecast i8 addrspace(1)* %0 to i8*
1645 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1646 Value *NewGEP = GEP.isInBounds()
1647 ? Builder->CreateInBoundsGEP(
1648 nullptr, StrippedPtr, Idx, GEP.getName())
1649 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1651 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1655 } else if (GEP.getNumOperands() == 2) {
1656 // Transform things like:
1657 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1658 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1659 Type *SrcElTy = StrippedPtrTy->getElementType();
1660 Type *ResElTy = PtrOp->getType()->getPointerElementType();
1661 if (SrcElTy->isArrayTy() &&
1662 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1663 DL.getTypeAllocSize(ResElTy)) {
1664 Type *IdxType = DL.getIntPtrType(GEP.getType());
1665 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1668 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1670 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1672 // V and GEP are both pointer types --> BitCast
1673 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1677 // Transform things like:
1678 // %V = mul i64 %N, 4
1679 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1680 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1681 if (ResElTy->isSized() && SrcElTy->isSized()) {
1682 // Check that changing the type amounts to dividing the index by a scale
1684 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1685 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1686 if (ResSize && SrcSize % ResSize == 0) {
1687 Value *Idx = GEP.getOperand(1);
1688 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1689 uint64_t Scale = SrcSize / ResSize;
1691 // Earlier transforms ensure that the index has type IntPtrType, which
1692 // considerably simplifies the logic by eliminating implicit casts.
1693 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1694 "Index not cast to pointer width?");
1697 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1698 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1699 // If the multiplication NewIdx * Scale may overflow then the new
1700 // GEP may not be "inbounds".
1702 GEP.isInBounds() && NSW
1703 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1705 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1708 // The NewGEP must be pointer typed, so must the old one -> BitCast
1709 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1715 // Similarly, transform things like:
1716 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1717 // (where tmp = 8*tmp2) into:
1718 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1719 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1720 // Check that changing to the array element type amounts to dividing the
1721 // index by a scale factor.
1722 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1723 uint64_t ArrayEltSize =
1724 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1725 if (ResSize && ArrayEltSize % ResSize == 0) {
1726 Value *Idx = GEP.getOperand(1);
1727 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1728 uint64_t Scale = ArrayEltSize / ResSize;
1730 // Earlier transforms ensure that the index has type IntPtrType, which
1731 // considerably simplifies the logic by eliminating implicit casts.
1732 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1733 "Index not cast to pointer width?");
1736 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1737 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1738 // If the multiplication NewIdx * Scale may overflow then the new
1739 // GEP may not be "inbounds".
1741 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1744 Value *NewGEP = GEP.isInBounds() && NSW
1745 ? Builder->CreateInBoundsGEP(
1746 SrcElTy, StrippedPtr, Off, GEP.getName())
1747 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1749 // The NewGEP must be pointer typed, so must the old one -> BitCast
1750 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1758 // addrspacecast between types is canonicalized as a bitcast, then an
1759 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1760 // through the addrspacecast.
1761 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1762 // X = bitcast A addrspace(1)* to B addrspace(1)*
1763 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1764 // Z = gep Y, <...constant indices...>
1765 // Into an addrspacecasted GEP of the struct.
1766 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1770 /// See if we can simplify:
1771 /// X = bitcast A* to B*
1772 /// Y = gep X, <...constant indices...>
1773 /// into a gep of the original struct. This is important for SROA and alias
1774 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1775 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1776 Value *Operand = BCI->getOperand(0);
1777 PointerType *OpType = cast<PointerType>(Operand->getType());
1778 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1779 APInt Offset(OffsetBits, 0);
1780 if (!isa<BitCastInst>(Operand) &&
1781 GEP.accumulateConstantOffset(DL, Offset)) {
1783 // If this GEP instruction doesn't move the pointer, just replace the GEP
1784 // with a bitcast of the real input to the dest type.
1786 // If the bitcast is of an allocation, and the allocation will be
1787 // converted to match the type of the cast, don't touch this.
1788 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
1789 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1790 if (Instruction *I = visitBitCast(*BCI)) {
1793 BCI->getParent()->getInstList().insert(BCI, I);
1794 ReplaceInstUsesWith(*BCI, I);
1800 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1801 return new AddrSpaceCastInst(Operand, GEP.getType());
1802 return new BitCastInst(Operand, GEP.getType());
1805 // Otherwise, if the offset is non-zero, we need to find out if there is a
1806 // field at Offset in 'A's type. If so, we can pull the cast through the
1808 SmallVector<Value*, 8> NewIndices;
1809 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1812 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1813 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1815 if (NGEP->getType() == GEP.getType())
1816 return ReplaceInstUsesWith(GEP, NGEP);
1817 NGEP->takeName(&GEP);
1819 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1820 return new AddrSpaceCastInst(NGEP, GEP.getType());
1821 return new BitCastInst(NGEP, GEP.getType());
1830 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1831 const TargetLibraryInfo *TLI) {
1832 SmallVector<Instruction*, 4> Worklist;
1833 Worklist.push_back(AI);
1836 Instruction *PI = Worklist.pop_back_val();
1837 for (User *U : PI->users()) {
1838 Instruction *I = cast<Instruction>(U);
1839 switch (I->getOpcode()) {
1841 // Give up the moment we see something we can't handle.
1844 case Instruction::BitCast:
1845 case Instruction::GetElementPtr:
1846 Users.emplace_back(I);
1847 Worklist.push_back(I);
1850 case Instruction::ICmp: {
1851 ICmpInst *ICI = cast<ICmpInst>(I);
1852 // We can fold eq/ne comparisons with null to false/true, respectively.
1853 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1855 Users.emplace_back(I);
1859 case Instruction::Call:
1860 // Ignore no-op and store intrinsics.
1861 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1862 switch (II->getIntrinsicID()) {
1866 case Intrinsic::memmove:
1867 case Intrinsic::memcpy:
1868 case Intrinsic::memset: {
1869 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1870 if (MI->isVolatile() || MI->getRawDest() != PI)
1874 case Intrinsic::dbg_declare:
1875 case Intrinsic::dbg_value:
1876 case Intrinsic::invariant_start:
1877 case Intrinsic::invariant_end:
1878 case Intrinsic::lifetime_start:
1879 case Intrinsic::lifetime_end:
1880 case Intrinsic::objectsize:
1881 Users.emplace_back(I);
1886 if (isFreeCall(I, TLI)) {
1887 Users.emplace_back(I);
1892 case Instruction::Store: {
1893 StoreInst *SI = cast<StoreInst>(I);
1894 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1896 Users.emplace_back(I);
1900 llvm_unreachable("missing a return?");
1902 } while (!Worklist.empty());
1906 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1907 // If we have a malloc call which is only used in any amount of comparisons
1908 // to null and free calls, delete the calls and replace the comparisons with
1909 // true or false as appropriate.
1910 SmallVector<WeakVH, 64> Users;
1911 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1912 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1913 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1916 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1917 ReplaceInstUsesWith(*C,
1918 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1919 C->isFalseWhenEqual()));
1920 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1921 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1922 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1923 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1924 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1925 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1926 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1929 EraseInstFromFunction(*I);
1932 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1933 // Replace invoke with a NOP intrinsic to maintain the original CFG
1934 Module *M = II->getParent()->getParent()->getParent();
1935 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1936 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1937 None, "", II->getParent());
1939 return EraseInstFromFunction(MI);
1944 /// \brief Move the call to free before a NULL test.
1946 /// Check if this free is accessed after its argument has been test
1947 /// against NULL (property 0).
1948 /// If yes, it is legal to move this call in its predecessor block.
1950 /// The move is performed only if the block containing the call to free
1951 /// will be removed, i.e.:
1952 /// 1. it has only one predecessor P, and P has two successors
1953 /// 2. it contains the call and an unconditional branch
1954 /// 3. its successor is the same as its predecessor's successor
1956 /// The profitability is out-of concern here and this function should
1957 /// be called only if the caller knows this transformation would be
1958 /// profitable (e.g., for code size).
1959 static Instruction *
1960 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1961 Value *Op = FI.getArgOperand(0);
1962 BasicBlock *FreeInstrBB = FI.getParent();
1963 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1965 // Validate part of constraint #1: Only one predecessor
1966 // FIXME: We can extend the number of predecessor, but in that case, we
1967 // would duplicate the call to free in each predecessor and it may
1968 // not be profitable even for code size.
1972 // Validate constraint #2: Does this block contains only the call to
1973 // free and an unconditional branch?
1974 // FIXME: We could check if we can speculate everything in the
1975 // predecessor block
1976 if (FreeInstrBB->size() != 2)
1979 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1982 // Validate the rest of constraint #1 by matching on the pred branch.
1983 TerminatorInst *TI = PredBB->getTerminator();
1984 BasicBlock *TrueBB, *FalseBB;
1985 ICmpInst::Predicate Pred;
1986 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1988 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1991 // Validate constraint #3: Ensure the null case just falls through.
1992 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1994 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1995 "Broken CFG: missing edge from predecessor to successor");
2002 Instruction *InstCombiner::visitFree(CallInst &FI) {
2003 Value *Op = FI.getArgOperand(0);
2005 // free undef -> unreachable.
2006 if (isa<UndefValue>(Op)) {
2007 // Insert a new store to null because we cannot modify the CFG here.
2008 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2009 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2010 return EraseInstFromFunction(FI);
2013 // If we have 'free null' delete the instruction. This can happen in stl code
2014 // when lots of inlining happens.
2015 if (isa<ConstantPointerNull>(Op))
2016 return EraseInstFromFunction(FI);
2018 // If we optimize for code size, try to move the call to free before the null
2019 // test so that simplify cfg can remove the empty block and dead code
2020 // elimination the branch. I.e., helps to turn something like:
2021 // if (foo) free(foo);
2025 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2031 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2032 if (RI.getNumOperands() == 0) // ret void
2035 Value *ResultOp = RI.getOperand(0);
2036 Type *VTy = ResultOp->getType();
2037 if (!VTy->isIntegerTy())
2040 // There might be assume intrinsics dominating this return that completely
2041 // determine the value. If so, constant fold it.
2042 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2043 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2044 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2045 if ((KnownZero|KnownOne).isAllOnesValue())
2046 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2051 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2052 // Change br (not X), label True, label False to: br X, label False, True
2054 BasicBlock *TrueDest;
2055 BasicBlock *FalseDest;
2056 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2057 !isa<Constant>(X)) {
2058 // Swap Destinations and condition...
2060 BI.swapSuccessors();
2064 // If the condition is irrelevant, remove the use so that other
2065 // transforms on the condition become more effective.
2066 if (BI.isConditional() &&
2067 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2068 !isa<UndefValue>(BI.getCondition())) {
2069 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2073 // Canonicalize fcmp_one -> fcmp_oeq
2074 FCmpInst::Predicate FPred; Value *Y;
2075 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2076 TrueDest, FalseDest)) &&
2077 BI.getCondition()->hasOneUse())
2078 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2079 FPred == FCmpInst::FCMP_OGE) {
2080 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2081 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2083 // Swap Destinations and condition.
2084 BI.swapSuccessors();
2089 // Canonicalize icmp_ne -> icmp_eq
2090 ICmpInst::Predicate IPred;
2091 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2092 TrueDest, FalseDest)) &&
2093 BI.getCondition()->hasOneUse())
2094 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2095 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2096 IPred == ICmpInst::ICMP_SGE) {
2097 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2098 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2099 // Swap Destinations and condition.
2100 BI.swapSuccessors();
2108 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2109 Value *Cond = SI.getCondition();
2110 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2111 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2112 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2113 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2114 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2116 // Compute the number of leading bits we can ignore.
2117 for (auto &C : SI.cases()) {
2118 LeadingKnownZeros = std::min(
2119 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2120 LeadingKnownOnes = std::min(
2121 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2124 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2126 // Truncate the condition operand if the new type is equal to or larger than
2127 // the largest legal integer type. We need to be conservative here since
2128 // x86 generates redundant zero-extenstion instructions if the operand is
2129 // truncated to i8 or i16.
2130 bool TruncCond = false;
2131 if (NewWidth > 0 && BitWidth > NewWidth &&
2132 NewWidth >= DL.getLargestLegalIntTypeSize()) {
2134 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2135 Builder->SetInsertPoint(&SI);
2136 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2137 SI.setCondition(NewCond);
2139 for (auto &C : SI.cases())
2140 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2141 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2144 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2145 if (I->getOpcode() == Instruction::Add)
2146 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2147 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
2148 // Skip the first item since that's the default case.
2149 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
2151 ConstantInt* CaseVal = i.getCaseValue();
2152 Constant *LHS = CaseVal;
2154 LHS = LeadingKnownZeros
2155 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2156 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2157 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
2158 assert(isa<ConstantInt>(NewCaseVal) &&
2159 "Result of expression should be constant");
2160 i.setValue(cast<ConstantInt>(NewCaseVal));
2162 SI.setCondition(I->getOperand(0));
2168 return TruncCond ? &SI : nullptr;
2171 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2172 Value *Agg = EV.getAggregateOperand();
2174 if (!EV.hasIndices())
2175 return ReplaceInstUsesWith(EV, Agg);
2177 if (Constant *C = dyn_cast<Constant>(Agg)) {
2178 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
2179 if (EV.getNumIndices() == 0)
2180 return ReplaceInstUsesWith(EV, C2);
2181 // Extract the remaining indices out of the constant indexed by the
2183 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
2185 return nullptr; // Can't handle other constants
2188 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2189 // We're extracting from an insertvalue instruction, compare the indices
2190 const unsigned *exti, *exte, *insi, *inse;
2191 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2192 exte = EV.idx_end(), inse = IV->idx_end();
2193 exti != exte && insi != inse;
2196 // The insert and extract both reference distinctly different elements.
2197 // This means the extract is not influenced by the insert, and we can
2198 // replace the aggregate operand of the extract with the aggregate
2199 // operand of the insert. i.e., replace
2200 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2201 // %E = extractvalue { i32, { i32 } } %I, 0
2203 // %E = extractvalue { i32, { i32 } } %A, 0
2204 return ExtractValueInst::Create(IV->getAggregateOperand(),
2207 if (exti == exte && insi == inse)
2208 // Both iterators are at the end: Index lists are identical. Replace
2209 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2210 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2212 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2214 // The extract list is a prefix of the insert list. i.e. replace
2215 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2216 // %E = extractvalue { i32, { i32 } } %I, 1
2218 // %X = extractvalue { i32, { i32 } } %A, 1
2219 // %E = insertvalue { i32 } %X, i32 42, 0
2220 // by switching the order of the insert and extract (though the
2221 // insertvalue should be left in, since it may have other uses).
2222 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2224 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2225 makeArrayRef(insi, inse));
2228 // The insert list is a prefix of the extract list
2229 // We can simply remove the common indices from the extract and make it
2230 // operate on the inserted value instead of the insertvalue result.
2232 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2233 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2235 // %E extractvalue { i32 } { i32 42 }, 0
2236 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2237 makeArrayRef(exti, exte));
2239 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2240 // We're extracting from an intrinsic, see if we're the only user, which
2241 // allows us to simplify multiple result intrinsics to simpler things that
2242 // just get one value.
2243 if (II->hasOneUse()) {
2244 // Check if we're grabbing the overflow bit or the result of a 'with
2245 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2246 // and replace it with a traditional binary instruction.
2247 switch (II->getIntrinsicID()) {
2248 case Intrinsic::uadd_with_overflow:
2249 case Intrinsic::sadd_with_overflow:
2250 if (*EV.idx_begin() == 0) { // Normal result.
2251 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2252 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2253 EraseInstFromFunction(*II);
2254 return BinaryOperator::CreateAdd(LHS, RHS);
2257 // If the normal result of the add is dead, and the RHS is a constant,
2258 // we can transform this into a range comparison.
2259 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2260 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2261 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2262 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2263 ConstantExpr::getNot(CI));
2265 case Intrinsic::usub_with_overflow:
2266 case Intrinsic::ssub_with_overflow:
2267 if (*EV.idx_begin() == 0) { // Normal result.
2268 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2269 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2270 EraseInstFromFunction(*II);
2271 return BinaryOperator::CreateSub(LHS, RHS);
2274 case Intrinsic::umul_with_overflow:
2275 case Intrinsic::smul_with_overflow:
2276 if (*EV.idx_begin() == 0) { // Normal result.
2277 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2278 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
2279 EraseInstFromFunction(*II);
2280 return BinaryOperator::CreateMul(LHS, RHS);
2288 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2289 // If the (non-volatile) load only has one use, we can rewrite this to a
2290 // load from a GEP. This reduces the size of the load.
2291 // FIXME: If a load is used only by extractvalue instructions then this
2292 // could be done regardless of having multiple uses.
2293 if (L->isSimple() && L->hasOneUse()) {
2294 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2295 SmallVector<Value*, 4> Indices;
2296 // Prefix an i32 0 since we need the first element.
2297 Indices.push_back(Builder->getInt32(0));
2298 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2300 Indices.push_back(Builder->getInt32(*I));
2302 // We need to insert these at the location of the old load, not at that of
2303 // the extractvalue.
2304 Builder->SetInsertPoint(L->getParent(), L);
2305 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2306 L->getPointerOperand(), Indices);
2307 // Returning the load directly will cause the main loop to insert it in
2308 // the wrong spot, so use ReplaceInstUsesWith().
2309 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2311 // We could simplify extracts from other values. Note that nested extracts may
2312 // already be simplified implicitly by the above: extract (extract (insert) )
2313 // will be translated into extract ( insert ( extract ) ) first and then just
2314 // the value inserted, if appropriate. Similarly for extracts from single-use
2315 // loads: extract (extract (load)) will be translated to extract (load (gep))
2316 // and if again single-use then via load (gep (gep)) to load (gep).
2317 // However, double extracts from e.g. function arguments or return values
2318 // aren't handled yet.
2322 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
2323 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2324 switch (Personality) {
2325 case EHPersonality::GNU_C:
2326 // The GCC C EH personality only exists to support cleanups, so it's not
2327 // clear what the semantics of catch clauses are.
2329 case EHPersonality::Unknown:
2331 case EHPersonality::GNU_Ada:
2332 // While __gnat_all_others_value will match any Ada exception, it doesn't
2333 // match foreign exceptions (or didn't, before gcc-4.7).
2335 case EHPersonality::GNU_CXX:
2336 case EHPersonality::GNU_ObjC:
2337 case EHPersonality::MSVC_X86SEH:
2338 case EHPersonality::MSVC_Win64SEH:
2339 case EHPersonality::MSVC_CXX:
2340 return TypeInfo->isNullValue();
2342 llvm_unreachable("invalid enum");
2345 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2347 cast<ArrayType>(LHS->getType())->getNumElements()
2349 cast<ArrayType>(RHS->getType())->getNumElements();
2352 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2353 // The logic here should be correct for any real-world personality function.
2354 // However if that turns out not to be true, the offending logic can always
2355 // be conditioned on the personality function, like the catch-all logic is.
2356 EHPersonality Personality =
2357 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2359 // Simplify the list of clauses, eg by removing repeated catch clauses
2360 // (these are often created by inlining).
2361 bool MakeNewInstruction = false; // If true, recreate using the following:
2362 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2363 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2365 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2366 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2367 bool isLastClause = i + 1 == e;
2368 if (LI.isCatch(i)) {
2370 Constant *CatchClause = LI.getClause(i);
2371 Constant *TypeInfo = CatchClause->stripPointerCasts();
2373 // If we already saw this clause, there is no point in having a second
2375 if (AlreadyCaught.insert(TypeInfo).second) {
2376 // This catch clause was not already seen.
2377 NewClauses.push_back(CatchClause);
2379 // Repeated catch clause - drop the redundant copy.
2380 MakeNewInstruction = true;
2383 // If this is a catch-all then there is no point in keeping any following
2384 // clauses or marking the landingpad as having a cleanup.
2385 if (isCatchAll(Personality, TypeInfo)) {
2387 MakeNewInstruction = true;
2388 CleanupFlag = false;
2392 // A filter clause. If any of the filter elements were already caught
2393 // then they can be dropped from the filter. It is tempting to try to
2394 // exploit the filter further by saying that any typeinfo that does not
2395 // occur in the filter can't be caught later (and thus can be dropped).
2396 // However this would be wrong, since typeinfos can match without being
2397 // equal (for example if one represents a C++ class, and the other some
2398 // class derived from it).
2399 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2400 Constant *FilterClause = LI.getClause(i);
2401 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2402 unsigned NumTypeInfos = FilterType->getNumElements();
2404 // An empty filter catches everything, so there is no point in keeping any
2405 // following clauses or marking the landingpad as having a cleanup. By
2406 // dealing with this case here the following code is made a bit simpler.
2407 if (!NumTypeInfos) {
2408 NewClauses.push_back(FilterClause);
2410 MakeNewInstruction = true;
2411 CleanupFlag = false;
2415 bool MakeNewFilter = false; // If true, make a new filter.
2416 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2417 if (isa<ConstantAggregateZero>(FilterClause)) {
2418 // Not an empty filter - it contains at least one null typeinfo.
2419 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2420 Constant *TypeInfo =
2421 Constant::getNullValue(FilterType->getElementType());
2422 // If this typeinfo is a catch-all then the filter can never match.
2423 if (isCatchAll(Personality, TypeInfo)) {
2424 // Throw the filter away.
2425 MakeNewInstruction = true;
2429 // There is no point in having multiple copies of this typeinfo, so
2430 // discard all but the first copy if there is more than one.
2431 NewFilterElts.push_back(TypeInfo);
2432 if (NumTypeInfos > 1)
2433 MakeNewFilter = true;
2435 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2436 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2437 NewFilterElts.reserve(NumTypeInfos);
2439 // Remove any filter elements that were already caught or that already
2440 // occurred in the filter. While there, see if any of the elements are
2441 // catch-alls. If so, the filter can be discarded.
2442 bool SawCatchAll = false;
2443 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2444 Constant *Elt = Filter->getOperand(j);
2445 Constant *TypeInfo = Elt->stripPointerCasts();
2446 if (isCatchAll(Personality, TypeInfo)) {
2447 // This element is a catch-all. Bail out, noting this fact.
2451 if (AlreadyCaught.count(TypeInfo))
2452 // Already caught by an earlier clause, so having it in the filter
2455 // There is no point in having multiple copies of the same typeinfo in
2456 // a filter, so only add it if we didn't already.
2457 if (SeenInFilter.insert(TypeInfo).second)
2458 NewFilterElts.push_back(cast<Constant>(Elt));
2460 // A filter containing a catch-all cannot match anything by definition.
2462 // Throw the filter away.
2463 MakeNewInstruction = true;
2467 // If we dropped something from the filter, make a new one.
2468 if (NewFilterElts.size() < NumTypeInfos)
2469 MakeNewFilter = true;
2471 if (MakeNewFilter) {
2472 FilterType = ArrayType::get(FilterType->getElementType(),
2473 NewFilterElts.size());
2474 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2475 MakeNewInstruction = true;
2478 NewClauses.push_back(FilterClause);
2480 // If the new filter is empty then it will catch everything so there is
2481 // no point in keeping any following clauses or marking the landingpad
2482 // as having a cleanup. The case of the original filter being empty was
2483 // already handled above.
2484 if (MakeNewFilter && !NewFilterElts.size()) {
2485 assert(MakeNewInstruction && "New filter but not a new instruction!");
2486 CleanupFlag = false;
2492 // If several filters occur in a row then reorder them so that the shortest
2493 // filters come first (those with the smallest number of elements). This is
2494 // advantageous because shorter filters are more likely to match, speeding up
2495 // unwinding, but mostly because it increases the effectiveness of the other
2496 // filter optimizations below.
2497 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2499 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2500 for (j = i; j != e; ++j)
2501 if (!isa<ArrayType>(NewClauses[j]->getType()))
2504 // Check whether the filters are already sorted by length. We need to know
2505 // if sorting them is actually going to do anything so that we only make a
2506 // new landingpad instruction if it does.
2507 for (unsigned k = i; k + 1 < j; ++k)
2508 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2509 // Not sorted, so sort the filters now. Doing an unstable sort would be
2510 // correct too but reordering filters pointlessly might confuse users.
2511 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2513 MakeNewInstruction = true;
2517 // Look for the next batch of filters.
2521 // If typeinfos matched if and only if equal, then the elements of a filter L
2522 // that occurs later than a filter F could be replaced by the intersection of
2523 // the elements of F and L. In reality two typeinfos can match without being
2524 // equal (for example if one represents a C++ class, and the other some class
2525 // derived from it) so it would be wrong to perform this transform in general.
2526 // However the transform is correct and useful if F is a subset of L. In that
2527 // case L can be replaced by F, and thus removed altogether since repeating a
2528 // filter is pointless. So here we look at all pairs of filters F and L where
2529 // L follows F in the list of clauses, and remove L if every element of F is
2530 // an element of L. This can occur when inlining C++ functions with exception
2532 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2533 // Examine each filter in turn.
2534 Value *Filter = NewClauses[i];
2535 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2537 // Not a filter - skip it.
2539 unsigned FElts = FTy->getNumElements();
2540 // Examine each filter following this one. Doing this backwards means that
2541 // we don't have to worry about filters disappearing under us when removed.
2542 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2543 Value *LFilter = NewClauses[j];
2544 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2546 // Not a filter - skip it.
2548 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2549 // an element of LFilter, then discard LFilter.
2550 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2551 // If Filter is empty then it is a subset of LFilter.
2554 NewClauses.erase(J);
2555 MakeNewInstruction = true;
2556 // Move on to the next filter.
2559 unsigned LElts = LTy->getNumElements();
2560 // If Filter is longer than LFilter then it cannot be a subset of it.
2562 // Move on to the next filter.
2564 // At this point we know that LFilter has at least one element.
2565 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2566 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2567 // already know that Filter is not longer than LFilter).
2568 if (isa<ConstantAggregateZero>(Filter)) {
2569 assert(FElts <= LElts && "Should have handled this case earlier!");
2571 NewClauses.erase(J);
2572 MakeNewInstruction = true;
2574 // Move on to the next filter.
2577 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2578 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2579 // Since Filter is non-empty and contains only zeros, it is a subset of
2580 // LFilter iff LFilter contains a zero.
2581 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2582 for (unsigned l = 0; l != LElts; ++l)
2583 if (LArray->getOperand(l)->isNullValue()) {
2584 // LFilter contains a zero - discard it.
2585 NewClauses.erase(J);
2586 MakeNewInstruction = true;
2589 // Move on to the next filter.
2592 // At this point we know that both filters are ConstantArrays. Loop over
2593 // operands to see whether every element of Filter is also an element of
2594 // LFilter. Since filters tend to be short this is probably faster than
2595 // using a method that scales nicely.
2596 ConstantArray *FArray = cast<ConstantArray>(Filter);
2597 bool AllFound = true;
2598 for (unsigned f = 0; f != FElts; ++f) {
2599 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2601 for (unsigned l = 0; l != LElts; ++l) {
2602 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2603 if (LTypeInfo == FTypeInfo) {
2613 NewClauses.erase(J);
2614 MakeNewInstruction = true;
2616 // Move on to the next filter.
2620 // If we changed any of the clauses, replace the old landingpad instruction
2622 if (MakeNewInstruction) {
2623 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2625 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2626 NLI->addClause(NewClauses[i]);
2627 // A landing pad with no clauses must have the cleanup flag set. It is
2628 // theoretically possible, though highly unlikely, that we eliminated all
2629 // clauses. If so, force the cleanup flag to true.
2630 if (NewClauses.empty())
2632 NLI->setCleanup(CleanupFlag);
2636 // Even if none of the clauses changed, we may nonetheless have understood
2637 // that the cleanup flag is pointless. Clear it if so.
2638 if (LI.isCleanup() != CleanupFlag) {
2639 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2640 LI.setCleanup(CleanupFlag);
2647 /// TryToSinkInstruction - Try to move the specified instruction from its
2648 /// current block into the beginning of DestBlock, which can only happen if it's
2649 /// safe to move the instruction past all of the instructions between it and the
2650 /// end of its block.
2651 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2652 assert(I->hasOneUse() && "Invariants didn't hold!");
2654 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2655 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2656 isa<TerminatorInst>(I))
2659 // Do not sink alloca instructions out of the entry block.
2660 if (isa<AllocaInst>(I) && I->getParent() ==
2661 &DestBlock->getParent()->getEntryBlock())
2664 // We can only sink load instructions if there is nothing between the load and
2665 // the end of block that could change the value.
2666 if (I->mayReadFromMemory()) {
2667 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2669 if (Scan->mayWriteToMemory())
2673 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2674 I->moveBefore(InsertPos);
2679 bool InstCombiner::run() {
2680 while (!Worklist.isEmpty()) {
2681 Instruction *I = Worklist.RemoveOne();
2682 if (I == nullptr) continue; // skip null values.
2684 // Check to see if we can DCE the instruction.
2685 if (isInstructionTriviallyDead(I, TLI)) {
2686 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2687 EraseInstFromFunction(*I);
2689 MadeIRChange = true;
2693 // Instruction isn't dead, see if we can constant propagate it.
2694 if (!I->use_empty() &&
2695 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2696 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
2697 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2699 // Add operands to the worklist.
2700 ReplaceInstUsesWith(*I, C);
2702 EraseInstFromFunction(*I);
2703 MadeIRChange = true;
2708 // See if we can trivially sink this instruction to a successor basic block.
2709 if (I->hasOneUse()) {
2710 BasicBlock *BB = I->getParent();
2711 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2712 BasicBlock *UserParent;
2714 // Get the block the use occurs in.
2715 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2716 UserParent = PN->getIncomingBlock(*I->use_begin());
2718 UserParent = UserInst->getParent();
2720 if (UserParent != BB) {
2721 bool UserIsSuccessor = false;
2722 // See if the user is one of our successors.
2723 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2724 if (*SI == UserParent) {
2725 UserIsSuccessor = true;
2729 // If the user is one of our immediate successors, and if that successor
2730 // only has us as a predecessors (we'd have to split the critical edge
2731 // otherwise), we can keep going.
2732 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
2733 // Okay, the CFG is simple enough, try to sink this instruction.
2734 if (TryToSinkInstruction(I, UserParent)) {
2735 MadeIRChange = true;
2736 // We'll add uses of the sunk instruction below, but since sinking
2737 // can expose opportunities for it's *operands* add them to the
2739 for (Use &U : I->operands())
2740 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2747 // Now that we have an instruction, try combining it to simplify it.
2748 Builder->SetInsertPoint(I->getParent(), I);
2749 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2754 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2755 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2757 if (Instruction *Result = visit(*I)) {
2759 // Should we replace the old instruction with a new one?
2761 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2762 << " New = " << *Result << '\n');
2764 if (I->getDebugLoc())
2765 Result->setDebugLoc(I->getDebugLoc());
2766 // Everything uses the new instruction now.
2767 I->replaceAllUsesWith(Result);
2769 // Move the name to the new instruction first.
2770 Result->takeName(I);
2772 // Push the new instruction and any users onto the worklist.
2773 Worklist.Add(Result);
2774 Worklist.AddUsersToWorkList(*Result);
2776 // Insert the new instruction into the basic block...
2777 BasicBlock *InstParent = I->getParent();
2778 BasicBlock::iterator InsertPos = I;
2780 // If we replace a PHI with something that isn't a PHI, fix up the
2782 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2783 InsertPos = InstParent->getFirstInsertionPt();
2785 InstParent->getInstList().insert(InsertPos, Result);
2787 EraseInstFromFunction(*I);
2790 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2791 << " New = " << *I << '\n');
2794 // If the instruction was modified, it's possible that it is now dead.
2795 // if so, remove it.
2796 if (isInstructionTriviallyDead(I, TLI)) {
2797 EraseInstFromFunction(*I);
2800 Worklist.AddUsersToWorkList(*I);
2803 MadeIRChange = true;
2808 return MadeIRChange;
2811 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2812 /// all reachable code to the worklist.
2814 /// This has a couple of tricks to make the code faster and more powerful. In
2815 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2816 /// them to the worklist (this significantly speeds up instcombine on code where
2817 /// many instructions are dead or constant). Additionally, if we find a branch
2818 /// whose condition is a known constant, we only visit the reachable successors.
2820 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2821 SmallPtrSetImpl<BasicBlock *> &Visited,
2822 InstCombineWorklist &ICWorklist,
2823 const TargetLibraryInfo *TLI) {
2824 bool MadeIRChange = false;
2825 SmallVector<BasicBlock*, 256> Worklist;
2826 Worklist.push_back(BB);
2828 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2829 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2832 BB = Worklist.pop_back_val();
2834 // We have now visited this block! If we've already been here, ignore it.
2835 if (!Visited.insert(BB).second)
2838 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2839 Instruction *Inst = BBI++;
2841 // DCE instruction if trivially dead.
2842 if (isInstructionTriviallyDead(Inst, TLI)) {
2844 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2845 Inst->eraseFromParent();
2849 // ConstantProp instruction if trivially constant.
2850 if (!Inst->use_empty() &&
2851 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
2852 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2853 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2855 Inst->replaceAllUsesWith(C);
2857 Inst->eraseFromParent();
2861 // See if we can constant fold its operands.
2862 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2864 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2868 Constant *&FoldRes = FoldedConstants[CE];
2870 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2874 if (FoldRes != CE) {
2876 MadeIRChange = true;
2880 InstrsForInstCombineWorklist.push_back(Inst);
2883 // Recursively visit successors. If this is a branch or switch on a
2884 // constant, only visit the reachable successor.
2885 TerminatorInst *TI = BB->getTerminator();
2886 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2887 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2888 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2889 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2890 Worklist.push_back(ReachableBB);
2893 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2894 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2895 // See if this is an explicit destination.
2896 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2898 if (i.getCaseValue() == Cond) {
2899 BasicBlock *ReachableBB = i.getCaseSuccessor();
2900 Worklist.push_back(ReachableBB);
2904 // Otherwise it is the default destination.
2905 Worklist.push_back(SI->getDefaultDest());
2910 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2911 Worklist.push_back(TI->getSuccessor(i));
2912 } while (!Worklist.empty());
2914 // Once we've found all of the instructions to add to instcombine's worklist,
2915 // add them in reverse order. This way instcombine will visit from the top
2916 // of the function down. This jives well with the way that it adds all uses
2917 // of instructions to the worklist after doing a transformation, thus avoiding
2918 // some N^2 behavior in pathological cases.
2919 ICWorklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2920 InstrsForInstCombineWorklist.size());
2922 return MadeIRChange;
2925 /// \brief Populate the IC worklist from a function, and prune any dead basic
2926 /// blocks discovered in the process.
2928 /// This also does basic constant propagation and other forward fixing to make
2929 /// the combiner itself run much faster.
2930 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
2931 TargetLibraryInfo *TLI,
2932 InstCombineWorklist &ICWorklist) {
2933 bool MadeIRChange = false;
2935 // Do a depth-first traversal of the function, populate the worklist with
2936 // the reachable instructions. Ignore blocks that are not reachable. Keep
2937 // track of which blocks we visit.
2938 SmallPtrSet<BasicBlock *, 64> Visited;
2940 AddReachableCodeToWorklist(F.begin(), DL, Visited, ICWorklist, TLI);
2942 // Do a quick scan over the function. If we find any blocks that are
2943 // unreachable, remove any instructions inside of them. This prevents
2944 // the instcombine code from having to deal with some bad special cases.
2945 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2946 if (Visited.count(BB))
2949 // Delete the instructions backwards, as it has a reduced likelihood of
2950 // having to update as many def-use and use-def chains.
2951 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2952 while (EndInst != BB->begin()) {
2953 // Delete the next to last instruction.
2954 BasicBlock::iterator I = EndInst;
2955 Instruction *Inst = --I;
2956 if (!Inst->use_empty())
2957 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2958 if (isa<LandingPadInst>(Inst)) {
2962 if (!isa<DbgInfoIntrinsic>(Inst)) {
2964 MadeIRChange = true;
2966 Inst->eraseFromParent();
2970 return MadeIRChange;
2974 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
2975 AssumptionCache &AC, TargetLibraryInfo &TLI,
2976 DominatorTree &DT, LoopInfo *LI = nullptr) {
2978 bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
2979 auto &DL = F.getParent()->getDataLayout();
2981 /// Builder - This is an IRBuilder that automatically inserts new
2982 /// instructions into the worklist when they are created.
2983 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
2984 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
2986 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2988 bool DbgDeclaresChanged = LowerDbgDeclare(F);
2990 // Iterate while there is work to do.
2994 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2995 << F.getName() << "\n");
2997 bool Changed = false;
2998 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
3001 InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI);
3009 return DbgDeclaresChanged || Iteration > 1;
3012 PreservedAnalyses InstCombinePass::run(Function &F,
3013 AnalysisManager<Function> *AM) {
3014 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3015 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3016 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3018 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3020 if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI))
3021 // No changes, all analyses are preserved.
3022 return PreservedAnalyses::all();
3024 // Mark all the analyses that instcombine updates as preserved.
3025 // FIXME: Need a way to preserve CFG analyses here!
3026 PreservedAnalyses PA;
3027 PA.preserve<DominatorTreeAnalysis>();
3032 /// \brief The legacy pass manager's instcombine pass.
3034 /// This is a basic whole-function wrapper around the instcombine utility. It
3035 /// will try to combine all instructions in the function.
3036 class InstructionCombiningPass : public FunctionPass {
3037 InstCombineWorklist Worklist;
3040 static char ID; // Pass identification, replacement for typeid
3042 InstructionCombiningPass() : FunctionPass(ID) {
3043 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3046 void getAnalysisUsage(AnalysisUsage &AU) const override;
3047 bool runOnFunction(Function &F) override;
3051 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3052 AU.setPreservesCFG();
3053 AU.addRequired<AssumptionCacheTracker>();
3054 AU.addRequired<TargetLibraryInfoWrapperPass>();
3055 AU.addRequired<DominatorTreeWrapperPass>();
3056 AU.addPreserved<DominatorTreeWrapperPass>();
3059 bool InstructionCombiningPass::runOnFunction(Function &F) {
3060 if (skipOptnoneFunction(F))
3063 // Required analyses.
3064 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3065 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3066 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3068 // Optional analyses.
3069 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3070 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3072 return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI);
3075 char InstructionCombiningPass::ID = 0;
3076 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3077 "Combine redundant instructions", false, false)
3078 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3079 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3080 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3081 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3082 "Combine redundant instructions", false, false)
3084 // Initialization Routines
3085 void llvm::initializeInstCombine(PassRegistry &Registry) {
3086 initializeInstructionCombiningPassPass(Registry);
3089 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3090 initializeInstructionCombiningPassPass(*unwrap(R));
3093 FunctionPass *llvm::createInstructionCombiningPass() {
3094 return new InstructionCombiningPass();