blob: ee037a85b706cc8d6c09ba8b089f725a2d050de5 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000068
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069
Dan Gohman844731a2008-05-13 00:00:25 +000070char InstCombiner::ID = 0;
71static RegisterPass<InstCombiner>
72X("instcombine", "Combine redundant instructions");
73
Chris Lattnere0b4b722010-01-04 07:17:19 +000074void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addPreservedID(LCSSAID);
76 AU.setPreservesCFG();
77}
78
79
Chris Lattner4cb170c2004-02-23 06:38:22 +000080// getPromotedType - Return the specified type promoted as it would be to pass
Chris Lattner248a84b2010-01-05 07:04:23 +000081// though a va_arg area.
Chris Lattner4cb170c2004-02-23 06:38:22 +000082static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +000083 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
84 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +000085 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +000086 }
Reid Spencera54b7cb2007-01-12 07:05:14 +000087 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +000088}
89
Chris Lattnerc22d4d12009-11-10 07:23:37 +000090/// ShouldChangeType - Return true if it is desirable to convert a computation
91/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
92/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000093bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000094 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
95
96 // If we don't have TD, we don't know if the source/dest are legal.
97 if (!TD) return false;
98
99 unsigned FromWidth = From->getPrimitiveSizeInBits();
100 unsigned ToWidth = To->getPrimitiveSizeInBits();
101 bool FromLegal = TD->isLegalInteger(FromWidth);
102 bool ToLegal = TD->isLegalInteger(ToWidth);
103
104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
107 return false;
108
109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
112 return false;
113
114 return true;
115}
116
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000117/// getBitCastOperand - If the specified operand is a CastInst, a constant
118/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
119/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000120static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000121 if (Operator *O = dyn_cast<Operator>(V)) {
122 if (O->getOpcode() == Instruction::BitCast)
123 return O->getOperand(0);
124 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
125 if (GEP->hasAllZeroIndices())
126 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000127 }
Chris Lattnereed48272005-09-13 00:40:14 +0000128 return 0;
129}
130
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000131
Chris Lattner33a61132006-05-06 09:00:16 +0000132
Chris Lattner4f98c562003-03-10 21:43:22 +0000133// SimplifyCommutative - This performs a few simplifications for commutative
134// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000135//
Chris Lattner4f98c562003-03-10 21:43:22 +0000136// 1. Order operands such that they are listed from right (least complex) to
137// left (most complex). This puts constants before unary operators before
138// binary operators.
139//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000140// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
141// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000142//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000143bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000144 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000145 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000146 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000147
Chris Lattner4f98c562003-03-10 21:43:22 +0000148 if (!I.isAssociative()) return Changed;
Chris Lattner248a84b2010-01-05 07:04:23 +0000149
Chris Lattner4f98c562003-03-10 21:43:22 +0000150 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000151 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
152 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
153 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000154 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000155 cast<Constant>(I.getOperand(1)),
156 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000157 I.setOperand(0, Op->getOperand(0));
158 I.setOperand(1, Folded);
159 return true;
Chris Lattner248a84b2010-01-05 07:04:23 +0000160 }
161
162 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000163 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner248a84b2010-01-05 07:04:23 +0000164 Op->hasOneUse() && Op1->hasOneUse()) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000165 Constant *C1 = cast<Constant>(Op->getOperand(1));
166 Constant *C2 = cast<Constant>(Op1->getOperand(1));
167
168 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000169 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000170 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000171 Op1->getOperand(0),
172 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000173 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000174 I.setOperand(0, New);
175 I.setOperand(1, Folded);
176 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000177 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000178 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000179 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000180}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000181
Chris Lattner8d969642003-03-10 23:06:50 +0000182// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
183// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000184//
Chris Lattner02446fc2010-01-04 07:37:31 +0000185Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000186 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000187 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000188
Chris Lattner0ce85802004-12-14 20:08:06 +0000189 // Constants can be considered to be negated values if they can be folded.
190 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000191 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000192
193 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
194 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000195 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000196
Chris Lattner8d969642003-03-10 23:06:50 +0000197 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000198}
199
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000200// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
201// instruction if the LHS is a constant negative zero (which is the 'negate'
202// form).
203//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000204Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000205 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 return BinaryOperator::getFNegArgument(V);
207
208 // Constants can be considered to be negated values if they can be folded.
209 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000210 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000211
212 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
213 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000214 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000215
216 return 0;
217}
218
Chris Lattner48b59ec2009-10-26 15:40:07 +0000219/// isFreeToInvert - Return true if the specified value is free to invert (apply
220/// ~ to). This happens in cases where the ~ can be eliminated.
221static inline bool isFreeToInvert(Value *V) {
222 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000223 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000224 return true;
225
226 // Constants can be considered to be not'ed values.
227 if (isa<ConstantInt>(V))
228 return true;
229
230 // Compares can be inverted if they have a single use.
231 if (CmpInst *CI = dyn_cast<CmpInst>(V))
232 return CI->hasOneUse();
233
234 return false;
235}
236
237static inline Value *dyn_castNotVal(Value *V) {
238 // If this is not(not(x)) don't return that this is a not: we want the two
239 // not's to be folded first.
240 if (BinaryOperator::isNot(V)) {
241 Value *Operand = BinaryOperator::getNotArgument(V);
242 if (!isFreeToInvert(Operand))
243 return Operand;
244 }
Chris Lattner8d969642003-03-10 23:06:50 +0000245
246 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000247 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000248 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000249 return 0;
250}
251
Chris Lattner48b59ec2009-10-26 15:40:07 +0000252
253
Chris Lattnerc8802d22003-03-11 00:12:48 +0000254// dyn_castFoldableMul - If this value is a multiply that can be folded into
255// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000256// non-constant operand of the multiply, and set CST to point to the multiplier.
257// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000258//
Dan Gohman186a6362009-08-12 16:04:34 +0000259static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000260 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000261 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000262 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000263 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000264 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000265 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000266 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000267 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000268 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000269 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000270 CST = ConstantInt::get(V->getType()->getContext(),
271 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000272 return I->getOperand(0);
273 }
274 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000275 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000276}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000277
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000278/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000279static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000280 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000281}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000282/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000283static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000284 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000285}
Reid Spencere7816b52007-03-08 01:52:58 +0000286
Dan Gohman45b4e482008-05-19 22:14:15 +0000287
Chris Lattner6e7ba452005-01-01 16:22:27 +0000288static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000289 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000290 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000291 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000292
Chris Lattner2eefe512004-04-09 19:05:30 +0000293 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000294 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
295 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000296
Chris Lattner2eefe512004-04-09 19:05:30 +0000297 if (Constant *SOC = dyn_cast<Constant>(SO)) {
298 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000299 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
300 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000301 }
302
303 Value *Op0 = SO, *Op1 = ConstOperand;
304 if (!ConstIsRHS)
305 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000306
Chris Lattner6e7ba452005-01-01 16:22:27 +0000307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000308 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
309 SO->getName()+".op");
310 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
311 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
312 SO->getName()+".cmp");
313 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
314 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
315 SO->getName()+".cmp");
316 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000317}
318
319// FoldOpIntoSelect - Given an instruction with a select as one operand and a
320// constant as the other operand, try to fold the binary operator into the
321// select arguments. This also works for Cast instructions, which obviously do
322// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000323Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000324 // Don't modify shared select instructions
325 if (!SI->hasOneUse()) return 0;
326 Value *TV = SI->getOperand(1);
327 Value *FV = SI->getOperand(2);
328
329 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000330 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000331 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000332
Chris Lattner80f43d32010-01-04 07:53:58 +0000333 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
334 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000335
Gabor Greif051a9502008-04-06 20:25:17 +0000336 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
337 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000338 }
339 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000340}
341
Chris Lattner4e998b22004-09-29 05:07:12 +0000342
Chris Lattner5d1704d2009-09-27 19:57:57 +0000343/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
344/// has a PHI node as operand #0, see if we can fold the instruction into the
345/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000346///
347/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
348/// that would normally be unprofitable because they strongly encourage jump
349/// threading.
350Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
351 bool AllowAggressive) {
352 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000353 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000354 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000355 if (NumPHIValues == 0 ||
356 // We normally only transform phis with a single use, unless we're trying
357 // hard to make jump threading happen.
358 (!PN->hasOneUse() && !AllowAggressive))
359 return 0;
360
361
Chris Lattner5d1704d2009-09-27 19:57:57 +0000362 // Check to see if all of the operands of the PHI are simple constants
363 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000364 // remember the BB it is in. If there is more than one or if *it* is a PHI,
365 // bail out. We don't do arbitrary constant expressions here because moving
366 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000367 BasicBlock *NonConstBB = 0;
368 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000369 if (!isa<Constant>(PN->getIncomingValue(i)) ||
370 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000371 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000372 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000373 NonConstBB = PN->getIncomingBlock(i);
374
375 // If the incoming non-constant value is in I's block, we have an infinite
376 // loop.
377 if (NonConstBB == I.getParent())
378 return 0;
379 }
380
381 // If there is exactly one non-constant value, we can insert a copy of the
382 // operation in that block. However, if this is a critical edge, we would be
383 // inserting the computation one some other paths (e.g. inside a loop). Only
384 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000385 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000386 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
387 if (!BI || !BI->isUnconditional()) return 0;
388 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000389
390 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000391 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000392 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000393 InsertNewInstBefore(NewPN, *PN);
394 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000395
396 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000397 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
398 // We only currently try to fold the condition of a select when it is a phi,
399 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000400 Value *TrueV = SI->getTrueValue();
401 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000402 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000404 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000405 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
406 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000407 Value *InV = 0;
408 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000409 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000410 } else {
411 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000412 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
413 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000414 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000415 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000416 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000417 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000418 }
419 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000420 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000421 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000422 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000423 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000424 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000425 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000426 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000427 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000428 } else {
429 assert(PN->getIncomingBlock(i) == NonConstBB);
430 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000431 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000432 PN->getIncomingValue(i), C, "phitmp",
433 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000434 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000435 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000436 CI->getPredicate(),
437 PN->getIncomingValue(i), C, "phitmp",
438 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000439 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000440 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000441
442 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000443 }
444 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000445 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000446 } else {
447 CastInst *CI = cast<CastInst>(&I);
448 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000449 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000450 Value *InV;
451 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000452 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000453 } else {
454 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000455 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000456 I.getType(), "phitmp",
457 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000458 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000459 }
460 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000461 }
462 }
463 return ReplaceInstUsesWith(I, NewPN);
464}
465
Chris Lattner2454a2e2008-01-29 06:52:45 +0000466
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000467/// WillNotOverflowSignedAdd - Return true if we can prove that:
468/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
469/// This basically requires proving that the add in the original type would not
470/// overflow to change the sign bit or have a carry out.
471bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
472 // There are different heuristics we can use for this. Here are some simple
473 // ones.
474
475 // Add has the property that adding any two 2's complement numbers can only
476 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000477 // have at least two sign bits, we know that the addition of the two values
478 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000479 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
480 return true;
481
482
483 // If one of the operands only has one non-zero bit, and if the other operand
484 // has a known-zero bit in a more significant place than it (not including the
485 // sign bit) the ripple may go up to and fill the zero, but won't change the
486 // sign. For example, (X & ~4) + 1.
487
488 // TODO: Implement.
489
490 return false;
491}
492
Chris Lattner2454a2e2008-01-29 06:52:45 +0000493
Chris Lattner7e708292002-06-25 16:13:24 +0000494Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000495 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000496 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000497
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000498 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
499 I.hasNoUnsignedWrap(), TD))
500 return ReplaceInstUsesWith(I, V);
501
502
Chris Lattner66331a42004-04-10 22:01:55 +0000503 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +0000504 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000505 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000506 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +0000507 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +0000508 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000509 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +0000510
511 // See if SimplifyDemandedBits can simplify this. This handles stuff like
512 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +0000513 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000514 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +0000515
Eli Friedman709b33d2009-07-13 22:27:52 +0000516 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +0000517 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +0000518 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +0000519 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +0000520 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000521
522 if (isa<PHINode>(LHS))
523 if (Instruction *NV = FoldOpIntoPhi(I))
524 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000525
Chris Lattner4f637d42006-01-06 17:59:59 +0000526 ConstantInt *XorRHS = 0;
527 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +0000528 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000529 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000530 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000531 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +0000532
Zhou Sheng4351c642007-04-02 08:20:41 +0000533 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000534 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
535 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +0000536 do {
537 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +0000538 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
539 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000540 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
541 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +0000542 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +0000543 if (!MaskedValueIsZero(XorLHS,
544 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +0000545 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +0000546 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000547 }
548 }
549 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +0000550 C0080Val = APIntOps::lshr(C0080Val, Size);
551 CFF80Val = APIntOps::ashr(CFF80Val, Size);
552 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +0000553
Reid Spencer35c38852007-03-28 01:36:16 +0000554 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000555 // with funny bit widths then this switch statement should be removed. It
556 // is just here to get the size of the "middle" type back up to something
557 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +0000558 const Type *MiddleType = 0;
559 switch (Size) {
560 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +0000561 case 32:
562 case 16:
563 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +0000564 }
565 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +0000566 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +0000567 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +0000568 }
569 }
Chris Lattner66331a42004-04-10 22:01:55 +0000570 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000571
Chris Lattner4de84762010-01-04 07:02:48 +0000572 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000573 return BinaryOperator::CreateXor(LHS, RHS);
574
Nick Lewycky9419ddb2008-05-31 17:59:52 +0000575 if (I.getType()->isInteger()) {
Chris Lattner32c0cf52010-01-05 06:29:13 +0000576 // X + X --> X << 1
577 if (LHS == RHS)
578 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
Chris Lattner7edc8c22005-04-07 17:14:51 +0000579
580 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
581 if (RHSI->getOpcode() == Instruction::Sub)
582 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
583 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
584 }
585 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
586 if (LHSI->getOpcode() == Instruction::Sub)
587 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
588 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
589 }
Robert Bocchino71698282004-07-27 21:02:21 +0000590 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000591
Chris Lattner5c4afb92002-05-08 22:46:53 +0000592 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +0000593 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000594 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +0000595 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +0000596 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +0000597 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +0000598 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +0000599 }
Chris Lattnerdd12f962008-02-17 21:03:36 +0000600 }
601
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000602 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +0000603 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000604
605 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000606 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000607 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000608 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000609
Misha Brukmanfd939082005-04-21 23:48:37 +0000610
Chris Lattner50af16a2004-11-13 19:50:12 +0000611 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +0000612 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000613 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000614 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000615
616 // X*C1 + X*C2 --> X * (C1+C2)
617 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +0000618 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000619 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000620 }
621
622 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +0000623 if (dyn_castFoldableMul(RHS, C2) == LHS)
624 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +0000625
Chris Lattnere617c9e2007-01-05 02:17:46 +0000626 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +0000627 if (dyn_castNotVal(LHS) == RHS ||
628 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +0000629 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +0000630
Chris Lattnerad3448c2003-02-18 19:57:07 +0000631
Chris Lattner5e0d7182008-05-19 20:01:56 +0000632 // A+B --> A|B iff A and B have no bits set in common.
633 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
634 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
635 APInt LHSKnownOne(IT->getBitWidth(), 0);
636 APInt LHSKnownZero(IT->getBitWidth(), 0);
637 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
638 if (LHSKnownZero != 0) {
639 APInt RHSKnownOne(IT->getBitWidth(), 0);
640 APInt RHSKnownZero(IT->getBitWidth(), 0);
641 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
642
643 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +0000644 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +0000645 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +0000646 }
647 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000648
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000649 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +0000650 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000651 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +0000652 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
653 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000654 if (W != Y) {
655 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000656 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000657 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +0000658 std::swap(W, X);
659 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000660 std::swap(Y, Z);
661 std::swap(W, X);
662 }
663 }
664
665 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +0000666 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000667 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +0000668 }
669 }
670 }
671
Chris Lattner6b032052003-10-02 15:11:26 +0000672 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +0000673 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000674 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +0000675 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000676
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000677 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +0000678 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +0000679 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000680 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000681 if (Anded == CRHS) {
682 // See if all bits from the first bit set in the Add RHS up are included
683 // in the mask. First, get the rightmost bit.
Chris Lattner32c0cf52010-01-05 06:29:13 +0000684 const APInt &AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000685
686 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000687 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000688
689 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000690 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000691
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000692 if (AddRHSHighBits == AddRHSHighBitsAnd) {
693 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +0000694 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000695 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000696 }
697 }
698 }
699
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000700 // Try to fold constant add into select arguments.
701 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner80f43d32010-01-04 07:53:58 +0000702 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000703 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000704 }
705
Chris Lattner42790482007-12-20 01:56:58 +0000706 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +0000707 {
708 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000709 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000710 if (!SI) {
711 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +0000712 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000713 }
Chris Lattner42790482007-12-20 01:56:58 +0000714 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +0000715 Value *TV = SI->getTrueValue();
716 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +0000717 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +0000718
719 // Can we fold the add into the argument of the select?
720 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +0000721 if (match(FV, m_Zero()) &&
722 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000723 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000724 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +0000725 if (match(TV, m_Zero()) &&
726 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +0000727 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +0000728 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +0000729 }
730 }
Andrew Lenharth16d79552006-09-19 18:24:51 +0000731
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000732 // Check for (add (sext x), y), see if we can merge this into an
733 // integer add followed by a sext.
734 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
735 // (add (sext x), cst) --> (sext (add x, cst'))
736 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
737 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000738 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000739 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000740 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000741 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
742 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000743 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
744 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000745 return new SExtInst(NewAdd, I.getType());
746 }
747 }
748
749 // (add (sext x), (sext y)) --> (sext (add int x, y))
750 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
751 // Only do this if x/y have the same type, if at last one of them has a
752 // single use (so we don't increase the number of sexts), and if the
753 // integer add will not overflow.
754 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
755 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
756 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
757 RHSConv->getOperand(0))) {
758 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000759 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
760 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000761 return new SExtInst(NewAdd, I.getType());
762 }
763 }
764 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000765
766 return Changed ? &I : 0;
767}
768
769Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
770 bool Changed = SimplifyCommutative(I);
771 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
772
773 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
774 // X + 0 --> X
775 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000776 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000777 (I.getType())->getValueAPF()))
778 return ReplaceInstUsesWith(I, LHS);
779 }
780
781 if (isa<PHINode>(LHS))
782 if (Instruction *NV = FoldOpIntoPhi(I))
783 return NV;
784 }
785
786 // -A + B --> B - A
787 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +0000788 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000789 return BinaryOperator::CreateFSub(RHS, LHSV);
790
791 // A + -B --> A - B
792 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +0000793 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000794 return BinaryOperator::CreateFSub(LHS, V);
795
796 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
797 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
798 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
799 return ReplaceInstUsesWith(I, LHS);
800
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000801 // Check for (add double (sitofp x), y), see if we can merge this into an
802 // integer add followed by a promotion.
803 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
804 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
805 // ... if the constant fits in the integer value. This is useful for things
806 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
807 // requires a constant pool load, and generally allows the add to be better
808 // instcombined.
809 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
810 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000811 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000812 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +0000813 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000814 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
815 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000816 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
817 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000818 return new SIToFPInst(NewAdd, I.getType());
819 }
820 }
821
822 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
823 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
824 // Only do this if x/y have the same type, if at last one of them has a
825 // single use (so we don't increase the number of int->fp conversions),
826 // and if the integer add will not overflow.
827 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
828 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
829 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
830 RHSConv->getOperand(0))) {
831 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +0000832 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +0000833 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000834 return new SIToFPInst(NewAdd, I.getType());
835 }
836 }
837 }
838
Chris Lattner7e708292002-06-25 16:13:24 +0000839 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000840}
841
Chris Lattner092543c2009-11-04 08:05:20 +0000842
843/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
844/// code necessary to compute the offset from the base pointer (without adding
845/// in the base pointer). Return the result as a signed integer of intptr size.
Chris Lattner02446fc2010-01-04 07:37:31 +0000846Value *InstCombiner::EmitGEPOffset(User *GEP) {
847 TargetData &TD = *getTargetData();
Chris Lattner092543c2009-11-04 08:05:20 +0000848 gep_type_iterator GTI = gep_type_begin(GEP);
849 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
850 Value *Result = Constant::getNullValue(IntPtrTy);
851
852 // Build a mask for high order bits.
853 unsigned IntPtrWidth = TD.getPointerSizeInBits();
854 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
855
856 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
857 ++i, ++GTI) {
858 Value *Op = *i;
859 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
860 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
861 if (OpC->isZero()) continue;
862
863 // Handle a struct index, which adds its field offset to the pointer.
864 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
865 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
866
Chris Lattner02446fc2010-01-04 07:37:31 +0000867 Result = Builder->CreateAdd(Result,
868 ConstantInt::get(IntPtrTy, Size),
869 GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000870 continue;
871 }
872
873 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
874 Constant *OC =
875 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
876 Scale = ConstantExpr::getMul(OC, Scale);
877 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000878 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000879 continue;
880 }
881 // Convert to correct type.
882 if (Op->getType() != IntPtrTy)
Chris Lattner02446fc2010-01-04 07:37:31 +0000883 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattner092543c2009-11-04 08:05:20 +0000884 if (Size != 1) {
885 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
886 // We'll let instcombine(mul) convert this to a shl if possible.
Chris Lattner02446fc2010-01-04 07:37:31 +0000887 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattner092543c2009-11-04 08:05:20 +0000888 }
889
890 // Emit an add instruction.
Chris Lattner02446fc2010-01-04 07:37:31 +0000891 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner092543c2009-11-04 08:05:20 +0000892 }
893 return Result;
894}
895
896
Chris Lattner092543c2009-11-04 08:05:20 +0000897
898
899/// Optimize pointer differences into the same array into a size. Consider:
900/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
901/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
902///
903Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
904 const Type *Ty) {
905 assert(TD && "Must have target data info for this");
906
907 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
908 // this.
Chris Lattner0cb1e9e2010-01-04 18:48:26 +0000909 bool Swapped = false;
Chris Lattner85c1c962010-01-01 22:42:29 +0000910 GetElementPtrInst *GEP = 0;
911 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +0000912
Chris Lattner85c1c962010-01-01 22:42:29 +0000913 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
914 // For now we require one side to be the base pointer "A" or a constant
915 // expression derived from it.
916 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
917 // (gep X, ...) - X
918 if (LHSGEP->getOperand(0) == RHS) {
919 GEP = LHSGEP;
920 Swapped = false;
921 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
922 // (gep X, ...) - (ce_gep X, ...)
923 if (CE->getOpcode() == Instruction::GetElementPtr &&
924 LHSGEP->getOperand(0) == CE->getOperand(0)) {
925 CstGEP = CE;
926 GEP = LHSGEP;
927 Swapped = false;
928 }
929 }
930 }
931
932 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
933 // X - (gep X, ...)
934 if (RHSGEP->getOperand(0) == LHS) {
935 GEP = RHSGEP;
936 Swapped = true;
937 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
938 // (ce_gep X, ...) - (gep X, ...)
939 if (CE->getOpcode() == Instruction::GetElementPtr &&
940 RHSGEP->getOperand(0) == CE->getOperand(0)) {
941 CstGEP = CE;
942 GEP = RHSGEP;
943 Swapped = true;
944 }
945 }
946 }
947
948 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +0000949 return 0;
950
Chris Lattner092543c2009-11-04 08:05:20 +0000951 // Emit the offset of the GEP and an intptr_t.
Chris Lattner02446fc2010-01-04 07:37:31 +0000952 Value *Result = EmitGEPOffset(GEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000953
954 // If we had a constant expression GEP on the other side offsetting the
955 // pointer, subtract it from the offset we have.
956 if (CstGEP) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000957 Value *CstOffset = EmitGEPOffset(CstGEP);
Chris Lattner85c1c962010-01-01 22:42:29 +0000958 Result = Builder->CreateSub(Result, CstOffset);
959 }
960
Chris Lattner092543c2009-11-04 08:05:20 +0000961
962 // If we have p - gep(p, ...) then we have to negate the result.
963 if (Swapped)
964 Result = Builder->CreateNeg(Result, "diff.neg");
965
966 return Builder->CreateIntCast(Result, Ty, true);
967}
968
969
Chris Lattner7e708292002-06-25 16:13:24 +0000970Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000972
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000973 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000975
Chris Lattner3bf68152009-12-21 04:04:05 +0000976 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
977 if (Value *V = dyn_castNegVal(Op1)) {
978 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
979 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
980 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
981 return Res;
982 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000983
Chris Lattnere87597f2004-10-16 18:11:37 +0000984 if (isa<UndefValue>(Op0))
985 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
986 if (isa<UndefValue>(Op1))
987 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +0000988 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +0000989 return BinaryOperator::CreateXor(Op0, Op1);
990
Chris Lattnerd65460f2003-11-05 01:06:05 +0000991 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +0000992 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +0000993 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +0000994 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000995
Chris Lattnerd65460f2003-11-05 01:06:05 +0000996 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000997 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +0000998 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +0000999 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00001000
Chris Lattner76b7a062007-01-15 07:02:54 +00001001 // -(X >>u 31) -> (X >>s 31)
1002 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00001003 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001004 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001005 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001006 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001007 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001008 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00001009 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001010 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001011 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00001012 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001013 }
1014 }
Chris Lattner092543c2009-11-04 08:05:20 +00001015 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001016 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1017 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00001018 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00001019 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00001020 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001021 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00001022 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00001023 }
1024 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001025 }
1026 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001027 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001028
1029 // Try to fold constant sub into select arguments.
1030 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00001031 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001032 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00001033
1034 // C - zext(bool) -> bool ? C - 1 : C
1035 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00001036 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00001037 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00001038 }
1039
Chris Lattner43d84d62005-04-07 16:15:25 +00001040 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001041 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00001042 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001043 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001044 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001045 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001046 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001047 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001048 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1049 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1050 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00001051 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00001052 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00001053 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001054 }
1055
Chris Lattnerfd059242003-10-15 16:48:29 +00001056 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001057 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1058 // is not used by anyone else...
1059 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001060 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00001061 // Swap the two operands of the subexpr...
1062 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1063 Op1I->setOperand(0, IIOp1);
1064 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001065
Chris Lattnera2881962003-02-18 19:28:33 +00001066 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001067 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001068 }
1069
1070 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1071 //
1072 if (Op1I->getOpcode() == Instruction::And &&
1073 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1074 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1075
Chris Lattner74381062009-08-30 07:44:24 +00001076 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001077 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001078 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001079
Reid Spencerac5209e2006-10-16 23:08:08 +00001080 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00001081 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00001082 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00001083 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00001084 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001085 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00001086 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00001087
Chris Lattnerad3448c2003-02-18 19:57:07 +00001088 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001089 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00001090 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001091 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00001092 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00001093 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001094 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001095 }
Chris Lattner40371712002-05-09 01:29:19 +00001096 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001097 }
Chris Lattnera2881962003-02-18 19:28:33 +00001098
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001099 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1100 if (Op0I->getOpcode() == Instruction::Add) {
1101 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1102 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1103 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1104 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1105 } else if (Op0I->getOpcode() == Instruction::Sub) {
1106 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001107 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001108 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001109 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001110 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001111
Chris Lattner50af16a2004-11-13 19:50:12 +00001112 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00001113 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00001114 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00001115 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001116
Chris Lattner50af16a2004-11-13 19:50:12 +00001117 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00001118 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001119 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001120 }
Chris Lattner092543c2009-11-04 08:05:20 +00001121
1122 // Optimize pointer differences into the same array into a size. Consider:
1123 // &A[10] - &A[0]: we should compile this to "10".
1124 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00001125 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001126 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1127 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00001128 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1129 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001130
1131 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00001132 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1133 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1134 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1135 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00001136 }
1137
Chris Lattner3f5b8772002-05-06 16:14:14 +00001138 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001139}
1140
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001141Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1142 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1143
1144 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00001145 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001146 return BinaryOperator::CreateFAdd(Op0, V);
1147
1148 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1149 if (Op1I->getOpcode() == Instruction::FAdd) {
1150 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001151 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001152 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001153 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00001154 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001155 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001156 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001157 }
1158
1159 return 0;
1160}
1161
Reid Spencere4d87aa2006-12-23 06:05:41 +00001162/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001163/// are carefully arranged to allow folding of expressions such as:
1164///
1165/// (A < B) | (A > B) --> (A != B)
1166///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001167/// Note that this is only valid if the first and second predicates have the
1168/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001169///
Reid Spencere4d87aa2006-12-23 06:05:41 +00001170/// Three bits are used to represent the condition, as follows:
1171/// 0 A > B
1172/// 1 A == B
1173/// 2 A < B
1174///
1175/// <=> Value Definition
1176/// 000 0 Always false
1177/// 001 1 A > B
1178/// 010 2 A == B
1179/// 011 3 A >= B
1180/// 100 4 A < B
1181/// 101 5 A != B
1182/// 110 6 A <= B
1183/// 111 7 Always true
1184///
1185static unsigned getICmpCode(const ICmpInst *ICI) {
1186 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001187 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00001188 case ICmpInst::ICMP_UGT: return 1; // 001
1189 case ICmpInst::ICMP_SGT: return 1; // 001
1190 case ICmpInst::ICMP_EQ: return 2; // 010
1191 case ICmpInst::ICMP_UGE: return 3; // 011
1192 case ICmpInst::ICMP_SGE: return 3; // 011
1193 case ICmpInst::ICMP_ULT: return 4; // 100
1194 case ICmpInst::ICMP_SLT: return 4; // 100
1195 case ICmpInst::ICMP_NE: return 5; // 101
1196 case ICmpInst::ICMP_ULE: return 6; // 110
1197 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001198 // True -> 7
1199 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001200 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001201 return 0;
1202 }
1203}
1204
Evan Cheng8db90722008-10-14 17:15:11 +00001205/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
1206/// predicate into a three bit mask. It also returns whether it is an ordered
1207/// predicate by reference.
1208static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
1209 isOrdered = false;
1210 switch (CC) {
1211 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
1212 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00001213 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
1214 case FCmpInst::FCMP_UGT: return 1; // 001
1215 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
1216 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00001217 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
1218 case FCmpInst::FCMP_UGE: return 3; // 011
1219 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
1220 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00001221 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
1222 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00001223 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
1224 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00001225 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00001226 default:
1227 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00001228 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00001229 return 0;
1230 }
1231}
1232
Reid Spencere4d87aa2006-12-23 06:05:41 +00001233/// getICmpValue - This is the complement of getICmpCode, which turns an
1234/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00001235/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00001236/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +00001237static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
1238 switch (Code) {
1239 default: assert(0 && "Illegal ICmp code!");
1240 case 0:
1241 return ConstantInt::getFalse(LHS->getContext());
1242 case 1:
1243 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001244 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001245 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
1246 case 2:
1247 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
1248 case 3:
1249 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001250 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001251 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
1252 case 4:
1253 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001254 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001255 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
1256 case 5:
1257 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
1258 case 6:
1259 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001260 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +00001261 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
1262 case 7:
1263 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001264 }
1265}
1266
Evan Cheng8db90722008-10-14 17:15:11 +00001267/// getFCmpValue - This is the complement of getFCmpCode, which turns an
1268/// opcode and two operands into either a FCmp instruction. isordered is passed
1269/// in to determine which kind of predicate to use in the new fcmp instruction.
1270static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00001271 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00001272 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001273 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00001274 case 0:
1275 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001276 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001277 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001278 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001279 case 1:
1280 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001281 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001282 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001283 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001284 case 2:
1285 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001286 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001287 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001288 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001289 case 3:
1290 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001291 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001292 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001293 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001294 case 4:
1295 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001296 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001297 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001298 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001299 case 5:
1300 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001301 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001302 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001303 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00001304 case 6:
1305 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001306 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00001307 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001308 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00001309 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00001310 }
1311}
1312
Chris Lattnerb9553d62008-11-16 04:55:20 +00001313/// PredicatesFoldable - Return true if both predicates match sign or if at
1314/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00001315static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00001316 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
1317 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
1318 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001319}
1320
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001321// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1322// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00001323// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001324Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001325 ConstantInt *OpRHS,
1326 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001327 BinaryOperator &TheAnd) {
1328 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001329 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00001330 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001331 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001332
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001333 switch (Op->getOpcode()) {
1334 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001335 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001336 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00001337 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001338 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001339 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001340 }
1341 break;
1342 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001343 if (Together == AndRHS) // (X | C) & C --> C
1344 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001345
Chris Lattner6e7ba452005-01-01 16:22:27 +00001346 if (Op->hasOneUse() && Together != OpRHS) {
1347 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00001348 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00001349 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001350 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001351 }
1352 break;
1353 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001354 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001355 // Adding a one to a single bit bit-field should be turned into an XOR
1356 // of the bit. First thing to check is to see if this AND is with a
1357 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +00001358 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001359
Chris Lattnerc6334b92010-01-05 06:03:12 +00001360 // If there is only one bit set.
1361 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001362 // Ok, at this point, we know that we are masking the result of the
1363 // ADD down to exactly one bit. If the constant we are adding has
1364 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001365 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001366
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001367 // Check to see if any bits below the one bit set in AndRHSV are set.
1368 if ((AddRHS & (AndRHSV-1)) == 0) {
1369 // If not, the only thing that can effect the output of the AND is
1370 // the bit specified by AndRHSV. If that bit is set, the effect of
1371 // the XOR is to toggle the bit. If it is clear, then the ADD has
1372 // no effect.
1373 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1374 TheAnd.setOperand(0, X);
1375 return &TheAnd;
1376 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001377 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00001378 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001379 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001380 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001381 }
1382 }
1383 }
1384 }
1385 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001386
1387 case Instruction::Shl: {
1388 // We know that the AND will not produce any of the bits shifted in, so if
1389 // the anded constant includes them, clear them now!
1390 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001391 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001392 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001393 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001394 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
1395 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001396
Zhou Sheng290bec52007-03-29 08:15:12 +00001397 if (CI->getValue() == ShlMask) {
1398 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00001399 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1400 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001401 TheAnd.setOperand(1, CI);
1402 return &TheAnd;
1403 }
1404 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001405 }
Chris Lattner4de84762010-01-04 07:02:48 +00001406 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00001407 // We know that the AND will not produce any of the bits shifted in, so if
1408 // the anded constant includes them, clear them now! This only applies to
1409 // unsigned shifts, because a signed shr may bring in set bits!
1410 //
Zhou Sheng290bec52007-03-29 08:15:12 +00001411 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001412 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001413 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001414 ConstantInt *CI = ConstantInt::get(Op->getContext(),
1415 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00001416
Zhou Sheng290bec52007-03-29 08:15:12 +00001417 if (CI->getValue() == ShrMask) {
1418 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00001419 return ReplaceInstUsesWith(TheAnd, Op);
1420 } else if (CI != AndRHS) {
1421 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1422 return &TheAnd;
1423 }
1424 break;
1425 }
1426 case Instruction::AShr:
1427 // Signed shr.
1428 // See if this is shifting in some sign extension, then masking it out
1429 // with an and.
1430 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00001431 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001432 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00001433 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00001434 Constant *C = ConstantInt::get(Op->getContext(),
1435 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00001436 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00001437 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00001438 // Make the argument unsigned.
1439 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00001440 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001441 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00001442 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001443 }
1444 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001445 }
1446 return 0;
1447}
1448
Chris Lattner8b170942002-08-09 23:47:40 +00001449
Chris Lattnera96879a2004-09-29 17:40:11 +00001450/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1451/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00001452/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
1453/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00001454/// insert new instructions.
1455Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001456 bool isSigned, bool Inside,
1457 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001458 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00001459 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00001460 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001461
Chris Lattnera96879a2004-09-29 17:40:11 +00001462 if (Inside) {
1463 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001464 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00001465
Reid Spencere4d87aa2006-12-23 06:05:41 +00001466 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001467 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00001468 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00001469 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001470 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001471 }
1472
1473 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00001474 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00001475 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001476 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001477 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001478 }
1479
1480 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001481 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00001482
Reid Spencere4e40032007-03-21 23:19:50 +00001483 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00001484 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001485 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001486 ICmpInst::Predicate pred = (isSigned ?
1487 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001488 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001489 }
Reid Spencerb83eb642006-10-20 07:07:24 +00001490
Reid Spencere4e40032007-03-21 23:19:50 +00001491 // Emit V-Lo >u Hi-1-Lo
1492 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00001493 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00001494 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001495 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001496 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00001497}
1498
Chris Lattner7203e152005-09-18 07:22:02 +00001499// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1500// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1501// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1502// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00001503static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001504 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00001505 uint32_t BitWidth = Val->getType()->getBitWidth();
1506 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00001507
1508 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00001509 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00001510 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00001511 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00001512 return true;
1513}
1514
Chris Lattner7203e152005-09-18 07:22:02 +00001515/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1516/// where isSub determines whether the operator is a sub. If we can fold one of
1517/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001518///
1519/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1520/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1521/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1522///
1523/// return (A +/- B).
1524///
1525Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001526 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00001527 Instruction &I) {
1528 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1529 if (!LHSI || LHSI->getNumOperands() != 2 ||
1530 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1531
1532 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1533
1534 switch (LHSI->getOpcode()) {
1535 default: return 0;
1536 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00001537 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00001538 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00001539 if ((Mask->getValue().countLeadingZeros() +
1540 Mask->getValue().countPopulation()) ==
1541 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00001542 break;
1543
1544 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1545 // part, we don't need any explicit masks to take them out of A. If that
1546 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001547 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00001548 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00001549 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00001550 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00001551 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00001552 break;
1553 }
1554 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001555 return 0;
1556 case Instruction::Or:
1557 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001558 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00001559 if ((Mask->getValue().countLeadingZeros() +
1560 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00001561 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001562 break;
1563 return 0;
1564 }
1565
Chris Lattnerc8e77562005-09-18 04:24:45 +00001566 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00001567 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
1568 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00001569}
1570
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001571/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
1572Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
1573 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001574 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1575
1576 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1577 if (PredicatesFoldable(LHSCC, RHSCC)) {
1578 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1579 LHS->getOperand(1) == RHS->getOperand(0))
1580 LHS->swapOperands();
1581 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1582 LHS->getOperand(1) == RHS->getOperand(1)) {
1583 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1584 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
1585 bool isSigned = LHS->isSigned() || RHS->isSigned();
1586 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1587 if (Instruction *I = dyn_cast<Instruction>(RV))
1588 return I;
1589 // Otherwise, it's a constant boolean value.
1590 return ReplaceInstUsesWith(I, RV);
1591 }
1592 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001593
Chris Lattnerea065fb2008-11-16 05:10:52 +00001594 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001595 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1596 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1597 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1598 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00001599
Chris Lattner3f40e232009-11-29 00:51:17 +00001600 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1601 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1602 // where C is a power of 2
1603 if (LHSCC == ICmpInst::ICMP_ULT &&
1604 LHSCst->getValue().isPowerOf2()) {
1605 Value *NewOr = Builder->CreateOr(Val, Val2);
1606 return new ICmpInst(LHSCC, NewOr, LHSCst);
1607 }
1608
1609 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1610 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1611 Value *NewOr = Builder->CreateOr(Val, Val2);
1612 return new ICmpInst(LHSCC, NewOr, LHSCst);
1613 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00001614 }
1615
1616 // From here on, we only handle:
1617 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1618 if (Val != Val2) return 0;
1619
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001620 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1621 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1622 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1623 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1624 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1625 return 0;
1626
1627 // We can't fold (ugt x, C) & (sgt x, C2).
1628 if (!PredicatesFoldable(LHSCC, RHSCC))
1629 return 0;
1630
1631 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00001632 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001633 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001634 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001635 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00001636 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001637 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00001638 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1639
1640 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001641 std::swap(LHS, RHS);
1642 std::swap(LHSCst, RHSCst);
1643 std::swap(LHSCC, RHSCC);
1644 }
1645
1646 // At this point, we know we have have two icmp instructions
1647 // comparing a value against two constants and and'ing the result
1648 // together. Because of the above check, we know that we only have
1649 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +00001650 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001651 // are not equal and that the larger constant is on the RHS
1652 assert(LHSCst != RHSCst && "Compares not folded above?");
1653
1654 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001655 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001656 case ICmpInst::ICMP_EQ:
1657 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001658 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001659 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
1660 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
1661 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001662 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001663 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1664 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1665 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
1666 return ReplaceInstUsesWith(I, LHS);
1667 }
1668 case ICmpInst::ICMP_NE:
1669 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001670 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001671 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00001672 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001673 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001674 break; // (X != 13 & X u< 15) -> no change
1675 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00001676 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001677 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001678 break; // (X != 13 & X s< 15) -> no change
1679 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1680 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1681 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
1682 return ReplaceInstUsesWith(I, RHS);
1683 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001684 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00001685 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001686 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001687 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00001688 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001689 }
1690 break; // (X != 13 & X != 15) -> no change
1691 }
1692 break;
1693 case ICmpInst::ICMP_ULT:
1694 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001695 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001696 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1697 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001698 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001699 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1700 break;
1701 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1702 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
1703 return ReplaceInstUsesWith(I, LHS);
1704 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1705 break;
1706 }
1707 break;
1708 case ICmpInst::ICMP_SLT:
1709 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001710 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001711 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
1712 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00001713 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001714 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1715 break;
1716 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1717 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
1718 return ReplaceInstUsesWith(I, LHS);
1719 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1720 break;
1721 }
1722 break;
1723 case ICmpInst::ICMP_UGT:
1724 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001725 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001726 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1727 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1728 return ReplaceInstUsesWith(I, RHS);
1729 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1730 break;
1731 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001732 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001733 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001734 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001735 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001736 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001737 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001738 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1739 break;
1740 }
1741 break;
1742 case ICmpInst::ICMP_SGT:
1743 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001744 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001745 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1746 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1747 return ReplaceInstUsesWith(I, RHS);
1748 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1749 break;
1750 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001751 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001752 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001753 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001754 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001755 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001756 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001757 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1758 break;
1759 }
1760 break;
1761 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001762
1763 return 0;
1764}
1765
Chris Lattner42d1be02009-07-23 05:14:02 +00001766Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1767 FCmpInst *RHS) {
1768
1769 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1770 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1771 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1772 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1773 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1774 // If either of the constants are nans, then the whole thing returns
1775 // false.
1776 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001777 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001778 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001779 LHS->getOperand(0), RHS->getOperand(0));
1780 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001781
1782 // Handle vector zeros. This occurs because the canonical form of
1783 // "fcmp ord x,x" is "fcmp ord x, 0".
1784 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1785 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001786 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001787 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001788 return 0;
1789 }
1790
1791 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1792 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1793 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1794
1795
1796 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1797 // Swap RHS operands to match LHS.
1798 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1799 std::swap(Op1LHS, Op1RHS);
1800 }
1801
1802 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1803 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1804 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001805 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001806
1807 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001808 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001809 if (Op0CC == FCmpInst::FCMP_TRUE)
1810 return ReplaceInstUsesWith(I, RHS);
1811 if (Op1CC == FCmpInst::FCMP_TRUE)
1812 return ReplaceInstUsesWith(I, LHS);
1813
1814 bool Op0Ordered;
1815 bool Op1Ordered;
1816 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1817 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1818 if (Op1Pred == 0) {
1819 std::swap(LHS, RHS);
1820 std::swap(Op0Pred, Op1Pred);
1821 std::swap(Op0Ordered, Op1Ordered);
1822 }
1823 if (Op0Pred == 0) {
1824 // uno && ueq -> uno && (uno || eq) -> ueq
1825 // ord && olt -> ord && (ord && lt) -> olt
1826 if (Op0Ordered == Op1Ordered)
1827 return ReplaceInstUsesWith(I, RHS);
1828
1829 // uno && oeq -> uno && (ord && eq) -> false
1830 // uno && ord -> false
1831 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001832 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001833 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001834 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001835 }
1836 }
1837
1838 return 0;
1839}
1840
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001841
Chris Lattner7e708292002-06-25 16:13:24 +00001842Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001843 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001845
Chris Lattnerd06094f2009-11-10 00:55:12 +00001846 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1847 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001848
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001849 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001850 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001851 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001852 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001853
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001854 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001855 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001856 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001857
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001858 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001859 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001860 Value *Op0LHS = Op0I->getOperand(0);
1861 Value *Op0RHS = Op0I->getOperand(1);
1862 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001863 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001864 case Instruction::Xor:
1865 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001866 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001867 if (!Op0I->hasOneUse()) break;
1868
1869 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1870 // Not masking anything out for the LHS, move to RHS.
1871 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1872 Op0RHS->getName()+".masked");
1873 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1874 }
1875 if (!isa<Constant>(Op0RHS) &&
1876 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1877 // Not masking anything out for the RHS, move to LHS.
1878 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1879 Op0LHS->getName()+".masked");
1880 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001881 }
1882
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001884 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001885 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1886 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1887 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1888 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001889 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001890 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001891 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001892 break;
1893
1894 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001895 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1896 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1897 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1898 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001899 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001900
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001901 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1902 // has 1's for all bits that the subtraction with A might affect.
1903 if (Op0I->hasOneUse()) {
1904 uint32_t BitWidth = AndRHSMask.getBitWidth();
1905 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1906 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1907
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001908 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001909 if (!(A && A->isZero()) && // avoid infinite recursion.
1910 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001911 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001912 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1913 }
1914 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001915 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001916
1917 case Instruction::Shl:
1918 case Instruction::LShr:
1919 // (1 << x) & 1 --> zext(x == 0)
1920 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001921 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001922 Value *NewICmp =
1923 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001924 return new ZExtInst(NewICmp, I.getType());
1925 }
1926 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001927 }
1928
Chris Lattner58403262003-07-23 19:25:52 +00001929 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001931 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001933 // If this is an integer truncation or change from signed-to-unsigned, and
1934 // if the source is an and/or with immediate, transform it. This
1935 // frequently occurs for bitfield accesses.
1936 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001937 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001938 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001939 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001940 if (CastOp->getOpcode() == Instruction::And) {
1941 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001942 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1943 // This will fold the two constants together, which may allow
1944 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001945 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001946 CastOp->getOperand(0), I.getType(),
1947 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001948 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001949 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001950 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001951 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001952 } else if (CastOp->getOpcode() == Instruction::Or) {
1953 // Change: and (cast (or X, C1) to T), C2
1954 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001955 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001956 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001957 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001958 return ReplaceInstUsesWith(I, AndRHS);
1959 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001960 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001961 }
Chris Lattner06782f82003-07-23 19:36:21 +00001962 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001963
1964 // Try to fold constant and into select arguments.
1965 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001966 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001967 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001968 if (isa<PHINode>(Op0))
1969 if (Instruction *NV = FoldOpIntoPhi(I))
1970 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001971 }
1972
Chris Lattner5b62aa72004-06-18 06:07:51 +00001973
Misha Brukmancb6267b2004-07-30 12:50:08 +00001974 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001975 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1976 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1977 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1978 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1979 I.getName()+".demorgan");
1980 return BinaryOperator::CreateNot(Or);
1981 }
1982
Chris Lattner2082ad92006-02-13 23:07:23 +00001983 {
Chris Lattner003b6202007-06-15 05:58:24 +00001984 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001985 // (A|B) & ~(A&B) -> A^B
1986 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1987 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1988 ((A == C && B == D) || (A == D && B == C)))
1989 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00001990
Chris Lattnerd06094f2009-11-10 00:55:12 +00001991 // ~(A&B) & (A|B) -> A^B
1992 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1993 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1994 ((A == C && B == D) || (A == D && B == C)))
1995 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00001996
1997 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001998 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001999 if (A == Op1) { // (A^B)&A -> A&(A^B)
2000 I.swapOperands(); // Simplify below
2001 std::swap(Op0, Op1);
2002 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2003 cast<BinaryOperator>(Op0)->swapOperands();
2004 I.swapOperands(); // Simplify below
2005 std::swap(Op0, Op1);
2006 }
2007 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002008
Chris Lattner64daab52006-04-01 08:03:55 +00002009 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002010 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00002011 if (B == Op0) { // B&(A^B) -> B&(B^A)
2012 cast<BinaryOperator>(Op1)->swapOperands();
2013 std::swap(A, B);
2014 }
Chris Lattner74381062009-08-30 07:44:24 +00002015 if (A == Op0) // A&(A^B) -> A & ~B
2016 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00002017 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00002018
2019 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00002020 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
2021 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002022 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00002023 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
2024 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00002025 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00002026 }
2027
Chris Lattnera317e042010-01-05 06:59:49 +00002028 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00002029 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
2030 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
2031 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00002032
Chris Lattner6fc205f2006-05-05 06:39:07 +00002033 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002034 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
2035 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2036 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
2037 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002038 if (SrcTy == Op1C->getOperand(0)->getType() &&
2039 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002040 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00002041 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
2042 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002043 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002044 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002045 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
2046 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002048 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002049 }
Chris Lattnere511b742006-11-14 07:46:50 +00002050
2051 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002052 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2053 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2054 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002055 SI0->getOperand(1) == SI1->getOperand(1) &&
2056 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002057 Value *NewOp =
2058 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
2059 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002060 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002061 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002062 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002063 }
2064
Evan Cheng8db90722008-10-14 17:15:11 +00002065 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00002066 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00002067 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2068 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
2069 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002070 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00002071
Chris Lattner7e708292002-06-25 16:13:24 +00002072 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002073}
2074
Chris Lattner8c34cd22008-10-05 02:13:19 +00002075/// CollectBSwapParts - Analyze the specified subexpression and see if it is
2076/// capable of providing pieces of a bswap. The subexpression provides pieces
2077/// of a bswap if it is proven that each of the non-zero bytes in the output of
2078/// the expression came from the corresponding "byte swapped" byte in some other
2079/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
2080/// we know that the expression deposits the low byte of %X into the high byte
2081/// of the bswap result and that all other bytes are zero. This expression is
2082/// accepted, the high byte of ByteValues is set to X to indicate a correct
2083/// match.
2084///
2085/// This function returns true if the match was unsuccessful and false if so.
2086/// On entry to the function the "OverallLeftShift" is a signed integer value
2087/// indicating the number of bytes that the subexpression is later shifted. For
2088/// example, if the expression is later right shifted by 16 bits, the
2089/// OverallLeftShift value would be -2 on entry. This is used to specify which
2090/// byte of ByteValues is actually being set.
2091///
2092/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
2093/// byte is masked to zero by a user. For example, in (X & 255), X will be
2094/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
2095/// this function to working on up to 32-byte (256 bit) values. ByteMask is
2096/// always in the local (OverallLeftShift) coordinate space.
2097///
2098static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
2099 SmallVector<Value*, 8> &ByteValues) {
2100 if (Instruction *I = dyn_cast<Instruction>(V)) {
2101 // If this is an or instruction, it may be an inner node of the bswap.
2102 if (I->getOpcode() == Instruction::Or) {
2103 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2104 ByteValues) ||
2105 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
2106 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002107 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00002108
2109 // If this is a logical shift by a constant multiple of 8, recurse with
2110 // OverallLeftShift and ByteMask adjusted.
2111 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2112 unsigned ShAmt =
2113 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2114 // Ensure the shift amount is defined and of a byte value.
2115 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
2116 return true;
2117
2118 unsigned ByteShift = ShAmt >> 3;
2119 if (I->getOpcode() == Instruction::Shl) {
2120 // X << 2 -> collect(X, +2)
2121 OverallLeftShift += ByteShift;
2122 ByteMask >>= ByteShift;
2123 } else {
2124 // X >>u 2 -> collect(X, -2)
2125 OverallLeftShift -= ByteShift;
2126 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00002127 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00002128 }
2129
2130 if (OverallLeftShift >= (int)ByteValues.size()) return true;
2131 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
2132
2133 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2134 ByteValues);
2135 }
2136
2137 // If this is a logical 'and' with a mask that clears bytes, clear the
2138 // corresponding bytes in ByteMask.
2139 if (I->getOpcode() == Instruction::And &&
2140 isa<ConstantInt>(I->getOperand(1))) {
2141 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
2142 unsigned NumBytes = ByteValues.size();
2143 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
2144 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2145
2146 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
2147 // If this byte is masked out by a later operation, we don't care what
2148 // the and mask is.
2149 if ((ByteMask & (1 << i)) == 0)
2150 continue;
2151
2152 // If the AndMask is all zeros for this byte, clear the bit.
2153 APInt MaskB = AndMask & Byte;
2154 if (MaskB == 0) {
2155 ByteMask &= ~(1U << i);
2156 continue;
2157 }
2158
2159 // If the AndMask is not all ones for this byte, it's not a bytezap.
2160 if (MaskB != Byte)
2161 return true;
2162
2163 // Otherwise, this byte is kept.
2164 }
2165
2166 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
2167 ByteValues);
2168 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002169 }
2170
Chris Lattner8c34cd22008-10-05 02:13:19 +00002171 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
2172 // the input value to the bswap. Some observations: 1) if more than one byte
2173 // is demanded from this input, then it could not be successfully assembled
2174 // into a byteswap. At least one of the two bytes would not be aligned with
2175 // their ultimate destination.
2176 if (!isPowerOf2_32(ByteMask)) return true;
2177 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002178
Chris Lattner8c34cd22008-10-05 02:13:19 +00002179 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
2180 // is demanded, it needs to go into byte 0 of the result. This means that the
2181 // byte needs to be shifted until it lands in the right byte bucket. The
2182 // shift amount depends on the position: if the byte is coming from the high
2183 // part of the value (e.g. byte 3) then it must be shifted right. If from the
2184 // low part, it must be shifted left.
2185 unsigned DestByteNo = InputByteNo + OverallLeftShift;
2186 if (InputByteNo < ByteValues.size()/2) {
2187 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2188 return true;
2189 } else {
2190 if (ByteValues.size()-1-DestByteNo != InputByteNo)
2191 return true;
2192 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00002193
2194 // If the destination byte value is already defined, the values are or'd
2195 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00002196 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00002197 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00002198 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00002199 return false;
2200}
2201
2202/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2203/// If so, insert the new bswap intrinsic and return it.
2204Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00002205 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00002206 if (!ITy || ITy->getBitWidth() % 16 ||
2207 // ByteMask only allows up to 32-byte values.
2208 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00002209 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00002210
2211 /// ByteValues - For each byte of the result, we keep track of which value
2212 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00002213 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00002214 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002215
2216 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00002217 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
2218 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00002219 return 0;
2220
2221 // Check to see if all of the bytes come from the same value.
2222 Value *V = ByteValues[0];
2223 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2224
2225 // Check to make sure that all of the bytes come from the same value.
2226 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2227 if (ByteValues[i] != V)
2228 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00002229 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00002230 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00002231 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00002232 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00002233}
2234
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002235/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
2236/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
2237/// we can simplify this expression to "cond ? C : D or B".
2238static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00002239 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00002240 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00002241 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002242 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002243 return 0;
2244
Chris Lattnera6a474d2008-11-16 04:26:55 +00002245 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00002246 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002247 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00002248 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002249 return SelectInst::Create(Cond, C, B);
2250 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00002251 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002252 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00002253 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00002254 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002255 return 0;
2256}
Chris Lattnerafe91a52006-06-15 19:07:26 +00002257
Chris Lattner69d4ced2008-11-16 05:20:07 +00002258/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
2259Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
2260 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00002261 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
2262
2263 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2264 if (PredicatesFoldable(LHSCC, RHSCC)) {
2265 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2266 LHS->getOperand(1) == RHS->getOperand(0))
2267 LHS->swapOperands();
2268 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2269 LHS->getOperand(1) == RHS->getOperand(1)) {
2270 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2271 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2272 bool isSigned = LHS->isSigned() || RHS->isSigned();
2273 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2274 if (Instruction *I = dyn_cast<Instruction>(RV))
2275 return I;
2276 // Otherwise, it's a constant boolean value.
2277 return ReplaceInstUsesWith(I, RV);
2278 }
2279 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002280
2281 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00002282 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
2283 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
2284 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
2285 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00002286
Chris Lattner3f40e232009-11-29 00:51:17 +00002287 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2288 if (LHSCst == RHSCst && LHSCC == RHSCC &&
2289 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
2290 Value *NewOr = Builder->CreateOr(Val, Val2);
2291 return new ICmpInst(LHSCC, NewOr, LHSCst);
2292 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00002293
2294 // From here on, we only handle:
2295 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2296 if (Val != Val2) return 0;
2297
2298 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
2299 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
2300 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
2301 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
2302 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
2303 return 0;
2304
2305 // We can't fold (ugt x, C) | (sgt x, C2).
2306 if (!PredicatesFoldable(LHSCC, RHSCC))
2307 return 0;
2308
2309 // Ensure that the larger constant is on the RHS.
2310 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00002311 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00002312 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00002313 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002314 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
2315 else
2316 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
2317
2318 if (ShouldSwap) {
2319 std::swap(LHS, RHS);
2320 std::swap(LHSCst, RHSCst);
2321 std::swap(LHSCC, RHSCC);
2322 }
2323
2324 // At this point, we know we have have two icmp instructions
2325 // comparing a value against two constants and or'ing the result
2326 // together. Because of the above check, we know that we only have
2327 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00002328 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00002329 // equal.
2330 assert(LHSCst != RHSCst && "Compares not folded above?");
2331
2332 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002333 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002334 case ICmpInst::ICMP_EQ:
2335 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002336 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002337 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00002338 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002339 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00002340 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00002341 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00002342 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002343 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002344 }
2345 break; // (X == 13 | X == 15) -> no change
2346 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2347 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2348 break;
2349 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
2350 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
2351 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
2352 return ReplaceInstUsesWith(I, RHS);
2353 }
2354 break;
2355 case ICmpInst::ICMP_NE:
2356 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002357 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002358 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
2359 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
2360 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
2361 return ReplaceInstUsesWith(I, LHS);
2362 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
2363 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
2364 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002365 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002366 }
2367 break;
2368 case ICmpInst::ICMP_ULT:
2369 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002370 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002371 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2372 break;
2373 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2374 // If RHSCst is [us]MAXINT, it is always false. Not handling
2375 // this can cause overflow.
2376 if (RHSCst->isMaxValue(false))
2377 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002378 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002379 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002380 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
2381 break;
2382 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
2383 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
2384 return ReplaceInstUsesWith(I, RHS);
2385 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
2386 break;
2387 }
2388 break;
2389 case ICmpInst::ICMP_SLT:
2390 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002391 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002392 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2393 break;
2394 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2395 // If RHSCst is [us]MAXINT, it is always false. Not handling
2396 // this can cause overflow.
2397 if (RHSCst->isMaxValue(true))
2398 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00002399 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00002400 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00002401 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2402 break;
2403 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2404 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
2405 return ReplaceInstUsesWith(I, RHS);
2406 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2407 break;
2408 }
2409 break;
2410 case ICmpInst::ICMP_UGT:
2411 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002412 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002413 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2414 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
2415 return ReplaceInstUsesWith(I, LHS);
2416 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2417 break;
2418 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2419 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002420 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002421 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2422 break;
2423 }
2424 break;
2425 case ICmpInst::ICMP_SGT:
2426 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002427 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00002428 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2429 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
2430 return ReplaceInstUsesWith(I, LHS);
2431 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2432 break;
2433 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2434 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00002435 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00002436 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2437 break;
2438 }
2439 break;
2440 }
2441 return 0;
2442}
2443
Chris Lattner5414cc52009-07-23 05:46:22 +00002444Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
2445 FCmpInst *RHS) {
2446 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2447 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2448 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2449 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2450 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2451 // If either of the constants are nans, then the whole thing returns
2452 // true.
2453 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00002454 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002455
2456 // Otherwise, no need to compare the two constants, compare the
2457 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002458 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002459 LHS->getOperand(0), RHS->getOperand(0));
2460 }
2461
2462 // Handle vector zeros. This occurs because the canonical form of
2463 // "fcmp uno x,x" is "fcmp uno x, 0".
2464 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2465 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002466 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00002467 LHS->getOperand(0), RHS->getOperand(0));
2468
2469 return 0;
2470 }
2471
2472 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2473 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2474 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2475
2476 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2477 // Swap RHS operands to match LHS.
2478 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2479 std::swap(Op1LHS, Op1RHS);
2480 }
2481 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2482 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2483 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002484 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00002485 Op0LHS, Op0RHS);
2486 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00002487 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00002488 if (Op0CC == FCmpInst::FCMP_FALSE)
2489 return ReplaceInstUsesWith(I, RHS);
2490 if (Op1CC == FCmpInst::FCMP_FALSE)
2491 return ReplaceInstUsesWith(I, LHS);
2492 bool Op0Ordered;
2493 bool Op1Ordered;
2494 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2495 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2496 if (Op0Ordered == Op1Ordered) {
2497 // If both are ordered or unordered, return a new fcmp with
2498 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00002499 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00002500 if (Instruction *I = dyn_cast<Instruction>(RV))
2501 return I;
2502 // Otherwise, it's a constant boolean value...
2503 return ReplaceInstUsesWith(I, RV);
2504 }
2505 }
2506 return 0;
2507}
2508
Bill Wendlinga698a472008-12-01 08:23:25 +00002509/// FoldOrWithConstants - This helper function folds:
2510///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002511/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00002512///
2513/// into:
2514///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002515/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00002516///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00002517/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00002518Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00002519 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00002520 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2521 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002522
Bill Wendling286a0542008-12-02 06:24:20 +00002523 Value *V1 = 0;
2524 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002525 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00002526
Bill Wendling29976b92008-12-02 06:18:11 +00002527 APInt Xor = CI1->getValue() ^ CI2->getValue();
2528 if (!Xor.isAllOnesValue()) return 0;
2529
Bill Wendling286a0542008-12-02 06:24:20 +00002530 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00002531 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00002532 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00002533 }
2534
2535 return 0;
2536}
2537
Chris Lattner7e708292002-06-25 16:13:24 +00002538Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002539 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002541
Chris Lattnerd06094f2009-11-10 00:55:12 +00002542 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
2543 return ReplaceInstUsesWith(I, V);
2544
2545
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002546 // See if we can simplify any instructions used by the instruction whose sole
2547 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002548 if (SimplifyDemandedInstructionBits(I))
2549 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00002550
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002551 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002552 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002553 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002554 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00002555 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00002556 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002557 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002559 ConstantInt::get(I.getContext(),
2560 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002561 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002562
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002563 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00002564 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00002565 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00002566 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00002567 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00002569 ConstantInt::get(I.getContext(),
2570 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002571 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002572
2573 // Try to fold constant and into select arguments.
2574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002575 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002576 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002577 if (isa<PHINode>(Op0))
2578 if (Instruction *NV = FoldOpIntoPhi(I))
2579 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002580 }
2581
Chris Lattner4f637d42006-01-06 17:59:59 +00002582 Value *A = 0, *B = 0;
2583 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002584
Chris Lattner6423d4c2006-07-10 20:25:24 +00002585 // (A | B) | C and A | (B | C) -> bswap if possible.
2586 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00002587 if (match(Op0, m_Or(m_Value(), m_Value())) ||
2588 match(Op1, m_Or(m_Value(), m_Value())) ||
2589 (match(Op0, m_Shift(m_Value(), m_Value())) &&
2590 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00002591 if (Instruction *BSwap = MatchBSwap(I))
2592 return BSwap;
2593 }
2594
Chris Lattner6e4c6492005-05-09 04:58:36 +00002595 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002596 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002597 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002598 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002599 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002600 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002601 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002602 }
2603
2604 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002605 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002606 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00002607 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00002608 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00002609 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002610 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00002611 }
2612
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002613 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00002614 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002615 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2616 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002617 Value *V1 = 0, *V2 = 0, *V3 = 0;
2618 C1 = dyn_cast<ConstantInt>(C);
2619 C2 = dyn_cast<ConstantInt>(D);
2620 if (C1 && C2) { // (A & C1)|(B & C2)
2621 // If we have: ((V + N) & C1) | (V & C2)
2622 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2623 // replace with V+N.
2624 if (C1->getValue() == ~C2->getValue()) {
2625 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00002626 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002627 // Add commutes, try both ways.
2628 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2629 return ReplaceInstUsesWith(I, A);
2630 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2631 return ReplaceInstUsesWith(I, A);
2632 }
2633 // Or commutes, try both ways.
2634 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002635 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00002636 // Add commutes, try both ways.
2637 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2638 return ReplaceInstUsesWith(I, B);
2639 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2640 return ReplaceInstUsesWith(I, B);
2641 }
2642 }
Chris Lattnere4412c12010-01-04 06:03:59 +00002643
2644 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2645 // iff (C1&C2) == 0 and (N&~C1) == 0
2646 if ((C1->getValue() & C2->getValue()) == 0) {
2647 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2648 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2649 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2650 return BinaryOperator::CreateAnd(A,
2651 ConstantInt::get(A->getContext(),
2652 C1->getValue()|C2->getValue()));
2653 // Or commutes, try both ways.
2654 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2655 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2656 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2657 return BinaryOperator::CreateAnd(B,
2658 ConstantInt::get(B->getContext(),
2659 C1->getValue()|C2->getValue()));
2660 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00002661 }
2662
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002663 // Check to see if we have any common things being and'ed. If so, find the
2664 // terms for V1 & (V2|V3).
Chris Lattner248a84b2010-01-05 07:04:23 +00002665 if (Op0->hasOneUse() || Op1->hasOneUse()) {
Chris Lattnere4412c12010-01-04 06:03:59 +00002666 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002667 if (A == B) // (A & C)|(A & D) == A & (C|D)
2668 V1 = A, V2 = C, V3 = D;
2669 else if (A == D) // (A & C)|(B & A) == A & (B|C)
2670 V1 = A, V2 = B, V3 = C;
2671 else if (C == B) // (A & C)|(C & D) == C & (A|D)
2672 V1 = C, V2 = A, V3 = D;
2673 else if (C == D) // (A & C)|(B & C) == C & (A|B)
2674 V1 = C, V2 = A, V3 = B;
2675
2676 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00002677 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002679 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00002680 }
Dan Gohmanb493b272008-10-28 22:38:57 +00002681
Dan Gohman1975d032008-10-30 20:40:10 +00002682 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00002683 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002684 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002685 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002686 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002687 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002688 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00002689 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00002690 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00002691
Bill Wendlingb01865c2008-11-30 13:52:49 +00002692 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002693 if ((match(C, m_Not(m_Specific(D))) &&
2694 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002695 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002696 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002697 if ((match(A, m_Not(m_Specific(D))) &&
2698 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002699 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002700 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002701 if ((match(C, m_Not(m_Specific(B))) &&
2702 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002703 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00002704 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00002705 if ((match(A, m_Not(m_Specific(B))) &&
2706 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00002707 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002708 }
Chris Lattnere511b742006-11-14 07:46:50 +00002709
2710 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00002711 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2712 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2713 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00002714 SI0->getOperand(1) == SI1->getOperand(1) &&
2715 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002716 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2717 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002718 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00002719 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00002720 }
2721 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002722
Bill Wendlingb3833d12008-12-01 01:07:11 +00002723 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002724 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2725 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002726 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002727 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002728 }
2729 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002730 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2731 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002732 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002733 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002734 }
2735
Chris Lattnerd06094f2009-11-10 00:55:12 +00002736 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2737 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2738 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2739 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2740 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2741 I.getName()+".demorgan");
2742 return BinaryOperator::CreateNot(And);
2743 }
Chris Lattnera2881962003-02-18 19:28:33 +00002744
Chris Lattnera317e042010-01-05 06:59:49 +00002745 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002746 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2747 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2748 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002749
2750 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002751 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002752 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002753 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002754 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2755 !isa<ICmpInst>(Op1C->getOperand(0))) {
2756 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002757 if (SrcTy == Op1C->getOperand(0)->getType() &&
2758 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002759 // Only do this if the casts both really cause code to be
2760 // generated.
2761 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002762 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002763 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002764 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002765 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2766 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002768 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002769 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002770 }
Chris Lattner99c65742007-10-24 05:38:08 +00002771 }
2772
2773
2774 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2775 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002776 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2777 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2778 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002779 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002780
Chris Lattner7e708292002-06-25 16:13:24 +00002781 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002782}
2783
Chris Lattner7e708292002-06-25 16:13:24 +00002784Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002785 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002786 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002787
Evan Chengd34af782008-03-25 20:07:13 +00002788 if (isa<UndefValue>(Op1)) {
2789 if (isa<UndefValue>(Op0))
2790 // Handle undef ^ undef -> 0 special case. This is a common
2791 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002793 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002794 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002795
Chris Lattnerdea34da2010-01-05 07:01:16 +00002796 // xor X, X = 0
2797 if (Op0 == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002798 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002799
2800 // See if we can simplify any instructions used by the instruction whose sole
2801 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002802 if (SimplifyDemandedInstructionBits(I))
2803 return &I;
2804 if (isa<VectorType>(I.getType()))
2805 if (isa<ConstantAggregateZero>(Op1))
2806 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002807
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002808 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002809 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002810 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2811 if (Op0I->getOpcode() == Instruction::And ||
2812 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002813 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2814 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2815 if (dyn_castNotVal(Op0I->getOperand(1)))
2816 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002817 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002818 Value *NotY =
2819 Builder->CreateNot(Op0I->getOperand(1),
2820 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002821 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002822 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002823 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002824 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002825
2826 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2827 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2828 if (isFreeToInvert(Op0I->getOperand(0)) &&
2829 isFreeToInvert(Op0I->getOperand(1))) {
2830 Value *NotX =
2831 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2832 Value *NotY =
2833 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2834 if (Op0I->getOpcode() == Instruction::And)
2835 return BinaryOperator::CreateOr(NotX, NotY);
2836 return BinaryOperator::CreateAnd(NotX, NotY);
2837 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002838 }
2839 }
2840 }
2841
2842
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002843 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002844 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002845 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002846 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002847 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002848 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002849
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002850 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002851 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002852 FCI->getOperand(0), FCI->getOperand(1));
2853 }
2854
Nick Lewycky517e1f52008-05-31 19:01:33 +00002855 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2856 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2857 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2858 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2859 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002860 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2861 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002862 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002863 Op0C->getDestTy()))) {
2864 CI->setPredicate(CI->getInversePredicate());
2865 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002866 }
2867 }
2868 }
2869 }
2870
Reid Spencere4d87aa2006-12-23 06:05:41 +00002871 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002872 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002873 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2874 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002875 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2876 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002877 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002878 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002879 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002880
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002881 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002882 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002883 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002884 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002885 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002886 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002887 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002888 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002889 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002890 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002891 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002892 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002893 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002894 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002895
Chris Lattner7c4049c2004-01-12 19:35:11 +00002896 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002897 } else if (Op0I->getOpcode() == Instruction::Or) {
2898 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002899 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002900 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002901 // Anything in both C1 and C2 is known to be zero, remove it from
2902 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002903 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2904 NewRHS = ConstantExpr::getAnd(NewRHS,
2905 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002906 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002907 I.setOperand(0, Op0I->getOperand(0));
2908 I.setOperand(1, NewRHS);
2909 return &I;
2910 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002911 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002912 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002913 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002914
2915 // Try to fold constant and into select arguments.
2916 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002917 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002918 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002919 if (isa<PHINode>(Op0))
2920 if (Instruction *NV = FoldOpIntoPhi(I))
2921 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002922 }
2923
Dan Gohman186a6362009-08-12 16:04:34 +00002924 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002925 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002926 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002927
Dan Gohman186a6362009-08-12 16:04:34 +00002928 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002929 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002930 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002931
Chris Lattner318bf792007-03-18 22:51:34 +00002932
2933 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2934 if (Op1I) {
2935 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002936 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002937 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002938 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002939 I.swapOperands();
2940 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002941 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002942 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002943 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002944 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002945 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002946 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002947 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002948 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002949 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002950 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002951 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002952 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002953 std::swap(A, B);
2954 }
Chris Lattner318bf792007-03-18 22:51:34 +00002955 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002956 I.swapOperands(); // Simplified below.
2957 std::swap(Op0, Op1);
2958 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002959 }
Chris Lattner318bf792007-03-18 22:51:34 +00002960 }
2961
2962 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2963 if (Op0I) {
2964 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002965 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002966 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00002967 if (A == Op1) // (B|A)^B == (A|B)^B
2968 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00002969 if (B == Op1) // (A|B)^B == A & ~B
2970 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00002971 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002972 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002973 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002974 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002975 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002976 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00002977 if (A == Op1) // (A&B)^A -> (B&A)^A
2978 std::swap(A, B);
2979 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00002980 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00002981 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00002982 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002983 }
Chris Lattner318bf792007-03-18 22:51:34 +00002984 }
2985
2986 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2987 if (Op0I && Op1I && Op0I->isShift() &&
2988 Op0I->getOpcode() == Op1I->getOpcode() &&
2989 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2990 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002991 Value *NewOp =
2992 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2993 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002994 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00002995 Op1I->getOperand(1));
2996 }
2997
2998 if (Op0I && Op1I) {
2999 Value *A, *B, *C, *D;
3000 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003001 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3002 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003003 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003004 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003005 }
3006 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00003007 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
3008 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003009 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00003011 }
3012
3013 // (A & B)^(C & D)
3014 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00003015 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
3016 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00003017 // (X & Y)^(X & Y) -> (Y^Z) & X
3018 Value *X = 0, *Y = 0, *Z = 0;
3019 if (A == C)
3020 X = A, Y = B, Z = D;
3021 else if (A == D)
3022 X = A, Y = B, Z = C;
3023 else if (B == C)
3024 X = B, Y = A, Z = D;
3025 else if (B == D)
3026 X = B, Y = A, Z = C;
3027
3028 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00003029 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00003031 }
3032 }
3033 }
3034
Reid Spencere4d87aa2006-12-23 06:05:41 +00003035 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3036 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00003037 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3038 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
3039 if (LHS->getOperand(0) == RHS->getOperand(1) &&
3040 LHS->getOperand(1) == RHS->getOperand(0))
3041 LHS->swapOperands();
3042 if (LHS->getOperand(0) == RHS->getOperand(0) &&
3043 LHS->getOperand(1) == RHS->getOperand(1)) {
3044 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
3045 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
3046 bool isSigned = LHS->isSigned() || RHS->isSigned();
3047 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
3048 if (Instruction *I = dyn_cast<Instruction>(RV))
3049 return I;
3050 // Otherwise, it's a constant boolean value.
3051 return ReplaceInstUsesWith(I, RV);
3052 }
3053 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003054
Chris Lattner6fc205f2006-05-05 06:39:07 +00003055 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00003056 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003057 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003058 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3059 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003060 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003061 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003062 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003063 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00003064 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00003065 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00003066 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
3067 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003069 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003070 }
Chris Lattner99c65742007-10-24 05:38:08 +00003071 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00003072
Chris Lattner7e708292002-06-25 16:13:24 +00003073 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003074}
3075
Chris Lattner3f5b8772002-05-06 16:14:14 +00003076
Reid Spencer832254e2007-02-02 02:16:23 +00003077Instruction *InstCombiner::visitShl(BinaryOperator &I) {
3078 return commonShiftTransforms(I);
3079}
3080
3081Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
3082 return commonShiftTransforms(I);
3083}
3084
3085Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00003086 if (Instruction *R = commonShiftTransforms(I))
3087 return R;
3088
3089 Value *Op0 = I.getOperand(0);
3090
3091 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
3092 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3093 if (CSI->isAllOnesValue())
3094 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00003095
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003096 // See if we can turn a signed shr into an unsigned shr.
3097 if (MaskedValueIsZero(Op0,
3098 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
3099 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
3100
3101 // Arithmetic shifting an all-sign-bit value is a no-op.
3102 unsigned NumSignBits = ComputeNumSignBits(Op0);
3103 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
3104 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00003105
Chris Lattner348f6652007-12-06 01:59:46 +00003106 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003107}
3108
3109Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
3110 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00003111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003112
3113 // shl X, 0 == X and shr X, 0 == X
3114 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003115 if (Op1 == Constant::getNullValue(Op1->getType()) ||
3116 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00003117 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003118
Reid Spencere4d87aa2006-12-23 06:05:41 +00003119 if (isa<UndefValue>(Op0)) {
3120 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00003121 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003122 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003124 }
3125 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003126 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
3127 return ReplaceInstUsesWith(I, Op0);
3128 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003130 }
3131
Dan Gohman9004c8a2009-05-21 02:28:33 +00003132 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00003133 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00003134 return &I;
3135
Chris Lattner2eefe512004-04-09 19:05:30 +00003136 // Try to fold constant and into select arguments.
3137 if (isa<Constant>(Op0))
3138 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00003139 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00003140 return R;
3141
Reid Spencerb83eb642006-10-20 07:07:24 +00003142 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00003143 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3144 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003145 return 0;
3146}
3147
Reid Spencerb83eb642006-10-20 07:07:24 +00003148Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00003149 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00003150 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003151
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003152 // See if we can simplify any instructions used by the instruction whose sole
3153 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003154 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00003155
Dan Gohmana119de82009-06-14 23:30:43 +00003156 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
3157 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00003158 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003159 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00003160 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003161 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003162 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00003163 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003164 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00003165 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003166 }
3167
3168 // ((X*C1) << C2) == (X * (C1 << C2))
3169 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3170 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3171 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003172 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003173 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00003174
3175 // Try to fold constant and into select arguments.
3176 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00003177 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00003178 return R;
3179 if (isa<PHINode>(Op0))
3180 if (Instruction *NV = FoldOpIntoPhi(I))
3181 return NV;
3182
Chris Lattner8999dd32007-12-22 09:07:47 +00003183 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
3184 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
3185 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
3186 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
3187 // place. Don't try to do this transformation in this case. Also, we
3188 // require that the input operand is a shift-by-constant so that we have
3189 // confidence that the shifts will get folded together. We could do this
3190 // xform in more cases, but it is unlikely to be profitable.
3191 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
3192 isa<ConstantInt>(TrOp->getOperand(1))) {
3193 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003194 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00003195 // (shift2 (shift1 & 0x00FF), c2)
3196 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003197
3198 // For logical shifts, the truncation has the effect of making the high
3199 // part of the register be zeros. Emulate this by inserting an AND to
3200 // clear the top bits as needed. This 'and' will usually be zapped by
3201 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00003202 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
3203 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00003204 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
3205
3206 // The mask we constructed says what the trunc would do if occurring
3207 // between the shifts. We want to know the effect *after* the second
3208 // shift. We know that it is a logical shift by a constant, so adjust the
3209 // mask as appropriate.
3210 if (I.getOpcode() == Instruction::Shl)
3211 MaskV <<= Op1->getZExtValue();
3212 else {
3213 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
3214 MaskV = MaskV.lshr(Op1->getZExtValue());
3215 }
3216
Chris Lattner74381062009-08-30 07:44:24 +00003217 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00003218 Value *And = Builder->CreateAnd(NSh,
3219 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00003220 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00003221
3222 // Return the value truncated to the interesting size.
3223 return new TruncInst(And, I.getType());
3224 }
3225 }
3226
Chris Lattner4d5542c2006-01-06 07:12:35 +00003227 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00003228 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3229 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3230 Value *V1, *V2;
3231 ConstantInt *CC;
3232 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00003233 default: break;
3234 case Instruction::Add:
3235 case Instruction::And:
3236 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00003237 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003238 // These operators commute.
3239 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003240 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003241 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003242 m_Specific(Op1)))) {
3243 Value *YS = // (Y << C)
3244 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
3245 // (X + (Y << C))
3246 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
3247 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003248 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003249 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003250 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003251 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003252
Chris Lattner150f12a2005-09-18 06:30:59 +00003253 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00003254 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00003255 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00003256 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00003257 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003258 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00003259 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003260 Value *YS = // (Y << C)
3261 Builder->CreateShl(Op0BO->getOperand(0), Op1,
3262 Op0BO->getName());
3263 // X & (CC << C)
3264 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3265 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003266 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00003267 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00003268 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003269
Reid Spencera07cb7d2007-02-02 14:41:37 +00003270 // FALL THROUGH.
3271 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00003272 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003273 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003274 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00003275 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003276 Value *YS = // (Y << C)
3277 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3278 // (X + (Y << C))
3279 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
3280 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00003281 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00003282 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00003283 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00003284 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003285
Chris Lattner13d4ab42006-05-31 21:14:00 +00003286 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003287 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3288 match(Op0BO->getOperand(0),
3289 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00003290 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00003291 cast<BinaryOperator>(Op0BO->getOperand(0))
3292 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003293 Value *YS = // (Y << C)
3294 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
3295 // X & (CC << C)
3296 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
3297 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00003298
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003299 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00003300 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003301
Chris Lattner11021cb2005-09-18 05:12:10 +00003302 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00003303 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00003304 }
3305
3306
3307 // If the operand is an bitwise operator with a constant RHS, and the
3308 // shift is the only use, we can pull it out of the shift.
3309 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3310 bool isValid = true; // Valid only for And, Or, Xor
3311 bool highBitSet = false; // Transform if high bit of constant set?
3312
3313 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00003314 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003315 case Instruction::Add:
3316 isValid = isLeftShift;
3317 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003318 case Instruction::Or:
3319 case Instruction::Xor:
3320 highBitSet = false;
3321 break;
3322 case Instruction::And:
3323 highBitSet = true;
3324 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003325 }
3326
3327 // If this is a signed shift right, and the high bit is modified
3328 // by the logical operation, do not perform the transformation.
3329 // The highBitSet boolean indicates the value of the high bit of
3330 // the constant which would cause it to be modified for this
3331 // operation.
3332 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00003333 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00003334 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00003335
3336 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003337 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003338
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003339 Value *NewShift =
3340 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003341 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00003342
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003343 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00003344 NewRHS);
3345 }
3346 }
3347 }
3348 }
3349
Chris Lattnerad0124c2006-01-06 07:52:12 +00003350 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00003351 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
3352 if (ShiftOp && !ShiftOp->isShift())
3353 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003354
Reid Spencerb83eb642006-10-20 07:07:24 +00003355 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003356 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003357 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
3358 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003359 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
3360 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
3361 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00003362
Zhou Sheng4351c642007-04-02 08:20:41 +00003363 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00003364
3365 const IntegerType *Ty = cast<IntegerType>(I.getType());
3366
3367 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00003368 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003369 // If this is oversized composite shift, then unsigned shifts get 0, ashr
3370 // saturates.
3371 if (AmtSum >= TypeBits) {
3372 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00003373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003374 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
3375 }
3376
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003377 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00003378 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003379 }
3380
3381 if (ShiftOp->getOpcode() == Instruction::LShr &&
3382 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00003383 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00003384 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00003385
Chris Lattnerb87056f2007-02-05 00:57:54 +00003386 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00003387 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003388 }
3389
3390 if (ShiftOp->getOpcode() == Instruction::AShr &&
3391 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00003392 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00003393 if (AmtSum >= TypeBits)
3394 AmtSum = TypeBits-1;
3395
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003396 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003397
Zhou Shenge9e03f62007-03-28 15:02:20 +00003398 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00003399 return BinaryOperator::CreateAnd(Shift,
3400 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003401 }
3402
Chris Lattnerb87056f2007-02-05 00:57:54 +00003403 // Okay, if we get here, one shift must be left, and the other shift must be
3404 // right. See if the amounts are equal.
3405 if (ShiftAmt1 == ShiftAmt2) {
3406 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
3407 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00003408 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003409 return BinaryOperator::CreateAnd(X,
3410 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003411 }
3412 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
3413 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003414 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00003415 return BinaryOperator::CreateAnd(X,
3416 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003417 }
3418 // We can simplify ((X << C) >>s C) into a trunc + sext.
3419 // NOTE: we could do this for any C, but that would make 'unusual' integer
3420 // types. For now, just stick to ones well-supported by the code
3421 // generators.
3422 const Type *SExtType = 0;
3423 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00003424 case 1 :
3425 case 8 :
3426 case 16 :
3427 case 32 :
3428 case 64 :
3429 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00003430 SExtType = IntegerType::get(I.getContext(),
3431 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00003432 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003433 default: break;
3434 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003435 if (SExtType)
3436 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00003437 // Otherwise, we can't handle it yet.
3438 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003439 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00003440
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003441 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003442 if (I.getOpcode() == Instruction::Shl) {
3443 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3444 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003445 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00003446
Reid Spencer55702aa2007-03-25 21:11:44 +00003447 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003448 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003449 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003450 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003451
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003452 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003453 if (I.getOpcode() == Instruction::LShr) {
3454 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003455 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00003456
Reid Spencerd5e30f02007-03-26 17:18:58 +00003457 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003458 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003459 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00003460 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00003461
3462 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
3463 } else {
3464 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00003465 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00003466
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003467 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003468 if (I.getOpcode() == Instruction::Shl) {
3469 assert(ShiftOp->getOpcode() == Instruction::LShr ||
3470 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003471 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
3472 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003473
Reid Spencer55702aa2007-03-25 21:11:44 +00003474 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003475 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003476 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003477 }
3478
Chris Lattnerb0b991a2007-02-05 05:57:49 +00003479 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00003480 if (I.getOpcode() == Instruction::LShr) {
3481 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003482 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003483
Reid Spencer68d27cf2007-03-26 23:45:51 +00003484 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00003485 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00003486 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00003487 }
3488
3489 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00003490 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00003491 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003492 return 0;
3493}
3494
Chris Lattnera1be5662002-05-02 17:06:02 +00003495
Reid Spencer3da59db2006-11-27 01:05:10 +00003496
Chris Lattner46cd5a12009-01-09 05:44:56 +00003497/// FindElementAtOffset - Given a type and a constant offset, determine whether
3498/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00003499/// the specified offset. If so, fill them into NewIndices and return the
3500/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00003501const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
3502 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003503 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00003504 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003505
3506 // Start with the index over the outer type. Note that the type size
3507 // might be zero (even if the offset isn't zero) if the indexed type
3508 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00003509 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00003510 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00003511 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003512 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00003513 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003514
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003515 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00003516 if (Offset < 0) {
3517 --FirstIdx;
3518 Offset += TySize;
3519 assert(Offset >= 0);
3520 }
3521 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
3522 }
3523
Owen Andersoneed707b2009-07-24 23:12:02 +00003524 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003525
3526 // Index into the types. If we fail, set OrigBase to null.
3527 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003528 // Indexing into tail padding between struct/array elements.
3529 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00003530 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003531
Chris Lattner46cd5a12009-01-09 05:44:56 +00003532 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
3533 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003534 assert(Offset < (int64_t)SL->getSizeInBytes() &&
3535 "Offset must stay within the indexed type");
3536
Chris Lattner46cd5a12009-01-09 05:44:56 +00003537 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00003538 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
3539 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003540
3541 Offset -= SL->getElementOffset(Elt);
3542 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00003543 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00003544 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003545 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00003546 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003547 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00003548 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00003549 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00003550 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00003551 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003552 }
3553 }
3554
Chris Lattner3914f722009-01-24 01:00:13 +00003555 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00003556}
3557
Chris Lattner8a2a3112001-12-14 16:52:21 +00003558
Dan Gohmaneee962e2008-04-10 18:43:06 +00003559/// EnforceKnownAlignment - If the specified pointer points to an object that
3560/// we control, modify the object's alignment to PrefAlign. This isn't
3561/// often possible though. If alignment is important, a more reliable approach
3562/// is to simply align all global variables and allocation instructions to
3563/// their preferred alignment from the beginning.
3564///
3565static unsigned EnforceKnownAlignment(Value *V,
3566 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00003567
Dan Gohmaneee962e2008-04-10 18:43:06 +00003568 User *U = dyn_cast<User>(V);
3569 if (!U) return Align;
3570
Dan Gohmanca178902009-07-17 20:47:02 +00003571 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003572 default: break;
3573 case Instruction::BitCast:
3574 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
3575 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00003576 // If all indexes are zero, it is just the alignment of the base pointer.
3577 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00003578 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00003579 if (!isa<Constant>(*i) ||
3580 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00003581 AllZeroOperands = false;
3582 break;
3583 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00003584
3585 if (AllZeroOperands) {
3586 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00003587 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00003588 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003589 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00003590 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003591 }
3592
3593 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3594 // If there is a large requested alignment and we can, bump up the alignment
3595 // of the global.
3596 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00003597 if (GV->getAlignment() >= PrefAlign)
3598 Align = GV->getAlignment();
3599 else {
3600 GV->setAlignment(PrefAlign);
3601 Align = PrefAlign;
3602 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00003603 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00003604 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
3605 // If there is a requested alignment and if this is an alloca, round up.
3606 if (AI->getAlignment() >= PrefAlign)
3607 Align = AI->getAlignment();
3608 else {
3609 AI->setAlignment(PrefAlign);
3610 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00003611 }
3612 }
3613
3614 return Align;
3615}
3616
3617/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
3618/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
3619/// and it is more than the alignment of the ultimate object, see if we can
3620/// increase the alignment of the ultimate object, making this check succeed.
3621unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
3622 unsigned PrefAlign) {
3623 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
3624 sizeof(PrefAlign) * CHAR_BIT;
3625 APInt Mask = APInt::getAllOnesValue(BitWidth);
3626 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3627 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
3628 unsigned TrailZ = KnownZero.countTrailingOnes();
3629 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
3630
3631 if (PrefAlign > Align)
3632 Align = EnforceKnownAlignment(V, Align, PrefAlign);
3633
3634 // We don't need to make any adjustment.
3635 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00003636}
3637
Chris Lattnerf497b022008-01-13 23:50:23 +00003638Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00003639 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00003640 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00003641 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003642 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00003643
3644 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003645 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003646 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00003647 return MI;
3648 }
3649
3650 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
3651 // load/store.
3652 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
3653 if (MemOpLength == 0) return 0;
3654
Chris Lattner37ac6082008-01-14 00:28:35 +00003655 // Source and destination pointer types are always "i8*" for intrinsic. See
3656 // if the size is something we can handle with a single primitive load/store.
3657 // A single load+store correctly handles overlapping memory in the memmove
3658 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00003659 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003660 if (Size == 0) return MI; // Delete this mem transfer.
3661
3662 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00003663 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00003664
Chris Lattner37ac6082008-01-14 00:28:35 +00003665 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00003666 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +00003667 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00003668
3669 // Memcpy forces the use of i8* for the source and destination. That means
3670 // that if you're using memcpy to move one double around, you'll get a cast
3671 // from double* to i8*. We'd much rather use a double load+store rather than
3672 // an i64 load+store, here because this improves the odds that the source or
3673 // dest address will be promotable. See if we can find a better type than the
3674 // integer datatype.
3675 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
3676 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003677 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003678 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
3679 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00003680 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00003681 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
3682 if (STy->getNumElements() == 1)
3683 SrcETy = STy->getElementType(0);
3684 else
3685 break;
3686 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
3687 if (ATy->getNumElements() == 1)
3688 SrcETy = ATy->getElementType();
3689 else
3690 break;
3691 } else
3692 break;
3693 }
3694
Dan Gohman8f8e2692008-05-23 01:52:21 +00003695 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00003696 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003697 }
3698 }
3699
3700
Chris Lattnerf497b022008-01-13 23:50:23 +00003701 // If the memcpy/memmove provides better alignment info than we can
3702 // infer, use it.
3703 SrcAlign = std::max(SrcAlign, CopyAlign);
3704 DstAlign = std::max(DstAlign, CopyAlign);
3705
Chris Lattner08142f22009-08-30 19:47:22 +00003706 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
3707 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00003708 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
3709 InsertNewInstBefore(L, *MI);
3710 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
3711
3712 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003713 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00003714 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00003715}
Chris Lattner3d69f462004-03-12 05:52:32 +00003716
Chris Lattner69ea9d22008-04-30 06:39:11 +00003717Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
3718 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003719 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003720 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00003721 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003722 return MI;
3723 }
3724
3725 // Extract the length and alignment and fill if they are constant.
3726 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
3727 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +00003728 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +00003729 return 0;
3730 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00003731 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00003732
3733 // If the length is zero, this is a no-op
3734 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
3735
3736 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
3737 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +00003738 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00003739
3740 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00003741 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003742
3743 // Alignment 0 is identity for alignment 1 for memset, but not store.
3744 if (Alignment == 0) Alignment = 1;
3745
3746 // Extract the fill value and store.
3747 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00003748 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00003749 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00003750
3751 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00003752 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00003753 return MI;
3754 }
3755
3756 return 0;
3757}
3758
3759
Chris Lattner8b0ea312006-01-13 20:11:04 +00003760/// visitCallInst - CallInst simplification. This mostly only handles folding
3761/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
3762/// the heavy lifting.
3763///
Chris Lattner9fe38862003-06-19 17:00:31 +00003764Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003765 if (isFreeCall(&CI))
3766 return visitFree(CI);
3767
Chris Lattneraab6ec42009-05-13 17:39:14 +00003768 // If the caller function is nounwind, mark the call as nounwind, even if the
3769 // callee isn't.
3770 if (CI.getParent()->getParent()->doesNotThrow() &&
3771 !CI.doesNotThrow()) {
3772 CI.setDoesNotThrow();
3773 return &CI;
3774 }
3775
Chris Lattner8b0ea312006-01-13 20:11:04 +00003776 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
3777 if (!II) return visitCallSite(&CI);
3778
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003779 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3780 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00003781 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003782 bool Changed = false;
3783
3784 // memmove/cpy/set of zero bytes is a noop.
3785 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3786 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3787
Chris Lattner35b9e482004-10-12 04:52:52 +00003788 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00003789 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003790 // Replace the instruction with just byte operations. We would
3791 // transform other cases to loads/stores, but we don't know if
3792 // alignment is sufficient.
3793 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003794 }
3795
Chris Lattner35b9e482004-10-12 04:52:52 +00003796 // If we have a memmove and the source operation is a constant global,
3797 // then the source and dest pointers can't alias, so we can change this
3798 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00003799 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00003800 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3801 if (GVSrc->isConstant()) {
3802 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00003803 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
3804 const Type *Tys[1];
3805 Tys[0] = CI.getOperand(3)->getType();
3806 CI.setOperand(0,
3807 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00003808 Changed = true;
3809 }
Eli Friedman0c826d92009-12-17 21:07:31 +00003810 }
Chris Lattnera935db82008-05-28 05:30:41 +00003811
Eli Friedman0c826d92009-12-17 21:07:31 +00003812 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00003813 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00003814 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00003815 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00003816 }
Chris Lattner35b9e482004-10-12 04:52:52 +00003817
Chris Lattner95a959d2006-03-06 20:18:44 +00003818 // If we can determine a pointer alignment that is bigger than currently
3819 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00003820 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00003821 if (Instruction *I = SimplifyMemTransfer(MI))
3822 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00003823 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
3824 if (Instruction *I = SimplifyMemSet(MSI))
3825 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00003826 }
3827
Chris Lattner8b0ea312006-01-13 20:11:04 +00003828 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003829 }
3830
3831 switch (II->getIntrinsicID()) {
3832 default: break;
3833 case Intrinsic::bswap:
3834 // bswap(bswap(x)) -> x
3835 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
3836 if (Operand->getIntrinsicID() == Intrinsic::bswap)
3837 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +00003838
3839 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
3840 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
3841 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
3842 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
3843 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
3844 TI->getType()->getPrimitiveSizeInBits();
3845 Value *CV = ConstantInt::get(Operand->getType(), C);
3846 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
3847 return new TruncInst(V, TI->getType());
3848 }
3849 }
3850
Chris Lattner0521e3c2008-06-18 04:33:20 +00003851 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +00003852 case Intrinsic::powi:
3853 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
3854 // powi(x, 0) -> 1.0
3855 if (Power->isZero())
3856 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
3857 // powi(x, 1) -> x
3858 if (Power->isOne())
3859 return ReplaceInstUsesWith(CI, II->getOperand(1));
3860 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +00003861 if (Power->isAllOnesValue())
3862 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
3863 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +00003864 }
3865 break;
3866
Chris Lattner2bbac752009-11-26 21:42:47 +00003867 case Intrinsic::uadd_with_overflow: {
3868 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3869 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
3870 uint32_t BitWidth = IT->getBitWidth();
3871 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00003872 APInt LHSKnownZero(BitWidth, 0);
3873 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003874 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
3875 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
3876 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
3877
3878 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00003879 APInt RHSKnownZero(BitWidth, 0);
3880 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003881 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
3882 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
3883 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
3884 if (LHSKnownNegative && RHSKnownNegative) {
3885 // The sign bit is set in both cases: this MUST overflow.
3886 // Create a simple add instruction, and insert it into the struct.
3887 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
3888 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003889 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003890 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003891 };
Chris Lattner4de84762010-01-04 07:02:48 +00003892 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003893 return InsertValueInst::Create(Struct, Add, 0);
3894 }
3895
3896 if (LHSKnownPositive && RHSKnownPositive) {
3897 // The sign bit is clear in both cases: this CANNOT overflow.
3898 // Create a simple add instruction, and insert it into the struct.
3899 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
3900 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00003901 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +00003902 UndefValue::get(LHS->getType()),
3903 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003904 };
Chris Lattner4de84762010-01-04 07:02:48 +00003905 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003906 return InsertValueInst::Create(Struct, Add, 0);
3907 }
3908 }
3909 }
3910 // FALL THROUGH uadd into sadd
3911 case Intrinsic::sadd_with_overflow:
3912 // Canonicalize constants into the RHS.
3913 if (isa<Constant>(II->getOperand(1)) &&
3914 !isa<Constant>(II->getOperand(2))) {
3915 Value *LHS = II->getOperand(1);
3916 II->setOperand(1, II->getOperand(2));
3917 II->setOperand(2, LHS);
3918 return II;
3919 }
3920
3921 // X + undef -> undef
3922 if (isa<UndefValue>(II->getOperand(2)))
3923 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3924
3925 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3926 // X + 0 -> {X, false}
3927 if (RHS->isZero()) {
3928 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003929 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003930 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003931 };
Chris Lattner4de84762010-01-04 07:02:48 +00003932 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003933 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3934 }
3935 }
3936 break;
3937 case Intrinsic::usub_with_overflow:
3938 case Intrinsic::ssub_with_overflow:
3939 // undef - X -> undef
3940 // X - undef -> undef
3941 if (isa<UndefValue>(II->getOperand(1)) ||
3942 isa<UndefValue>(II->getOperand(2)))
3943 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3944
3945 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
3946 // X - 0 -> {X, false}
3947 if (RHS->isZero()) {
3948 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00003949 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003950 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +00003951 };
Chris Lattner4de84762010-01-04 07:02:48 +00003952 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +00003953 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
3954 }
3955 }
3956 break;
3957 case Intrinsic::umul_with_overflow:
3958 case Intrinsic::smul_with_overflow:
3959 // Canonicalize constants into the RHS.
3960 if (isa<Constant>(II->getOperand(1)) &&
3961 !isa<Constant>(II->getOperand(2))) {
3962 Value *LHS = II->getOperand(1);
3963 II->setOperand(1, II->getOperand(2));
3964 II->setOperand(2, LHS);
3965 return II;
3966 }
3967
3968 // X * undef -> undef
3969 if (isa<UndefValue>(II->getOperand(2)))
3970 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
3971
3972 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
3973 // X*0 -> {0, false}
3974 if (RHSI->isZero())
3975 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
3976
3977 // X * 1 -> {X, false}
3978 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +00003979 Constant *V[] = {
3980 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +00003981 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +00003982 };
Chris Lattner4de84762010-01-04 07:02:48 +00003983 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +00003984 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00003985 }
3986 }
3987 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +00003988 case Intrinsic::ppc_altivec_lvx:
3989 case Intrinsic::ppc_altivec_lvxl:
3990 case Intrinsic::x86_sse_loadu_ps:
3991 case Intrinsic::x86_sse2_loadu_pd:
3992 case Intrinsic::x86_sse2_loadu_dq:
3993 // Turn PPC lvx -> load if the pointer is known aligned.
3994 // Turn X86 loadups -> load if the pointer is known aligned.
3995 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00003996 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
3997 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00003998 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00003999 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004000 break;
4001 case Intrinsic::ppc_altivec_stvx:
4002 case Intrinsic::ppc_altivec_stvxl:
4003 // Turn stvx -> store if the pointer is known aligned.
4004 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
4005 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004006 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004007 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004008 return new StoreInst(II->getOperand(1), Ptr);
4009 }
4010 break;
4011 case Intrinsic::x86_sse_storeu_ps:
4012 case Intrinsic::x86_sse2_storeu_pd:
4013 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00004014 // Turn X86 storeu -> store if the pointer is known aligned.
4015 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
4016 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00004017 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00004018 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00004019 return new StoreInst(II->getOperand(2), Ptr);
4020 }
4021 break;
4022
4023 case Intrinsic::x86_sse_cvttss2si: {
4024 // These intrinsics only demands the 0th element of its input vector. If
4025 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00004026 unsigned VWidth =
4027 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
4028 APInt DemandedElts(VWidth, 1);
4029 APInt UndefElts(VWidth, 0);
4030 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00004031 UndefElts)) {
4032 II->setOperand(1, V);
4033 return II;
4034 }
4035 break;
4036 }
4037
4038 case Intrinsic::ppc_altivec_vperm:
4039 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
4040 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
4041 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00004042
Chris Lattner0521e3c2008-06-18 04:33:20 +00004043 // Check that all of the elements are integer constants or undefs.
4044 bool AllEltsOk = true;
4045 for (unsigned i = 0; i != 16; ++i) {
4046 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
4047 !isa<UndefValue>(Mask->getOperand(i))) {
4048 AllEltsOk = false;
4049 break;
4050 }
4051 }
4052
4053 if (AllEltsOk) {
4054 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00004055 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
4056 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004057 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004058
Chris Lattner0521e3c2008-06-18 04:33:20 +00004059 // Only extract each element once.
4060 Value *ExtractedElts[32];
4061 memset(ExtractedElts, 0, sizeof(ExtractedElts));
4062
Chris Lattnere2ed0572006-04-06 19:19:17 +00004063 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004064 if (isa<UndefValue>(Mask->getOperand(i)))
4065 continue;
4066 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
4067 Idx &= 31; // Match the hardware behavior.
4068
4069 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004070 ExtractedElts[Idx] =
4071 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +00004072 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4073 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004074 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00004075
Chris Lattner0521e3c2008-06-18 04:33:20 +00004076 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004077 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +00004078 ConstantInt::get(Type::getInt32Ty(II->getContext()),
4079 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00004080 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004081 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00004082 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004083 }
4084 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00004085
Chris Lattner0521e3c2008-06-18 04:33:20 +00004086 case Intrinsic::stackrestore: {
4087 // If the save is right next to the restore, remove the restore. This can
4088 // happen when variable allocas are DCE'd.
4089 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4090 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4091 BasicBlock::iterator BI = SS;
4092 if (&*++BI == II)
4093 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00004094 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004095 }
4096
4097 // Scan down this block to see if there is another stack restore in the
4098 // same block without an intervening call/alloca.
4099 BasicBlock::iterator BI = II;
4100 TerminatorInst *TI = II->getParent()->getTerminator();
4101 bool CannotRemove = false;
4102 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00004103 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00004104 CannotRemove = true;
4105 break;
4106 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00004107 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
4108 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
4109 // If there is a stackrestore below this one, remove this one.
4110 if (II->getIntrinsicID() == Intrinsic::stackrestore)
4111 return EraseInstFromFunction(CI);
4112 // Otherwise, ignore the intrinsic.
4113 } else {
4114 // If we found a non-intrinsic call, we can't remove the stack
4115 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00004116 CannotRemove = true;
4117 break;
4118 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004119 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00004120 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00004121
4122 // If the stack restore is in a return/unwind block and if there are no
4123 // allocas or calls between the restore and the return, nuke the restore.
4124 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
4125 return EraseInstFromFunction(CI);
4126 break;
4127 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004128 }
4129
Chris Lattner8b0ea312006-01-13 20:11:04 +00004130 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004131}
4132
4133// InvokeInst simplification
4134//
4135Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004136 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004137}
4138
Dale Johannesenda30ccb2008-04-25 21:16:07 +00004139/// isSafeToEliminateVarargsCast - If this cast does not affect the value
4140/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00004141static bool isSafeToEliminateVarargsCast(const CallSite CS,
4142 const CastInst * const CI,
4143 const TargetData * const TD,
4144 const int ix) {
4145 if (!CI->isLosslessCast())
4146 return false;
4147
4148 // The size of ByVal arguments is derived from the type, so we
4149 // can't change to a type with a different size. If the size were
4150 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00004151 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004152 return true;
4153
4154 const Type* SrcTy =
4155 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4156 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4157 if (!SrcTy->isSized() || !DstTy->isSized())
4158 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004159 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00004160 return false;
4161 return true;
4162}
4163
Chris Lattnera44d8a22003-10-07 22:32:43 +00004164// visitCallSite - Improvements for call and invoke instructions.
4165//
4166Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004167 bool Changed = false;
4168
4169 // If the callee is a constexpr cast of a function, attempt to move the cast
4170 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004171 if (transformConstExprCastCall(CS)) return 0;
4172
Chris Lattner6c266db2003-10-07 22:54:13 +00004173 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004174
Chris Lattner08b22ec2005-05-13 07:09:09 +00004175 if (Function *CalleeF = dyn_cast<Function>(Callee))
4176 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4177 Instruction *OldCall = CS.getInstruction();
4178 // If the call and callee calling conventions don't match, this call must
4179 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +00004180 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4181 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +00004182 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +00004183 // If OldCall dues not return void then replaceAllUsesWith undef.
4184 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004185 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004186 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00004187 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4188 return EraseInstFromFunction(*OldCall);
4189 return 0;
4190 }
4191
Chris Lattner17be6352004-10-18 02:59:09 +00004192 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4193 // This instruction is not reachable, just remove it. We insert a store to
4194 // undef so that we know that this code is not reachable, despite the fact
4195 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004196 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4197 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +00004198 CS.getInstruction());
4199
Devang Patel228ebd02009-10-13 22:56:32 +00004200 // If CS dues not return void then replaceAllUsesWith undef.
4201 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00004202 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00004203 CS.getInstruction()->
4204 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00004205
4206 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4207 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00004208 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +00004209 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004210 }
Chris Lattner17be6352004-10-18 02:59:09 +00004211 return EraseInstFromFunction(*CS.getInstruction());
4212 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004213
Duncan Sandscdb6d922007-09-17 10:26:40 +00004214 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
4215 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
4216 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
4217 return transformCallThroughTrampoline(CS);
4218
Chris Lattner6c266db2003-10-07 22:54:13 +00004219 const PointerType *PTy = cast<PointerType>(Callee->getType());
4220 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4221 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00004222 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00004223 // See if we can optimize any arguments passed through the varargs area of
4224 // the call.
4225 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00004226 E = CS.arg_end(); I != E; ++I, ++ix) {
4227 CastInst *CI = dyn_cast<CastInst>(*I);
4228 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
4229 *I = CI->getOperand(0);
4230 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00004231 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00004232 }
Chris Lattner6c266db2003-10-07 22:54:13 +00004233 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004234
Duncan Sandsf0c33542007-12-19 21:13:37 +00004235 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00004236 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00004237 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00004238 Changed = true;
4239 }
4240
Chris Lattner6c266db2003-10-07 22:54:13 +00004241 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004242}
4243
Chris Lattner9fe38862003-06-19 17:00:31 +00004244// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4245// attempt to move the cast to the arguments of the call/invoke.
4246//
4247bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4248 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4249 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00004250 if (CE->getOpcode() != Instruction::BitCast ||
4251 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004252 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004253 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004254 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00004255 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00004256
4257 // Okay, this is a cast from a function to a different type. Unless doing so
4258 // would cause a type conversion of one of our arguments, change this call to
4259 // be a direct call with arguments casted to the appropriate types.
4260 //
4261 const FunctionType *FT = Callee->getFunctionType();
4262 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004263 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00004264
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004265 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00004266 return false; // TODO: Handle multiple return values.
4267
Chris Lattnerf78616b2004-01-14 06:06:08 +00004268 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004269 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00004270 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004271 // Conversion is ok if changing from one pointer type to another or from
4272 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004273 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004274 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004275 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004276 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00004277 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00004278
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004279 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004280 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +00004281 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004282 return false; // Cannot transform this return value.
4283
Chris Lattner58d74912008-03-12 17:45:29 +00004284 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00004285 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00004286 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00004287 return false; // Attribute not compatible with transformed value.
4288 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004289
Chris Lattnerf78616b2004-01-14 06:06:08 +00004290 // If the callsite is an invoke instruction, and the return value is used by
4291 // a PHI node in a successor, we cannot change the return type of the call
4292 // because there is no place to put the cast instruction (without breaking
4293 // the critical edge). Bail out in this case.
4294 if (!Caller->use_empty())
4295 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4296 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4297 UI != E; ++UI)
4298 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4299 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004300 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004301 return false;
4302 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004303
4304 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4305 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004306
Chris Lattner9fe38862003-06-19 17:00:31 +00004307 CallSite::arg_iterator AI = CS.arg_begin();
4308 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4309 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00004310 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004311
4312 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004313 return false; // Cannot transform this parameter value.
4314
Devang Patel19c87462008-09-26 22:53:05 +00004315 if (CallerPAL.getParamAttributes(i + 1)
4316 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00004317 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004318
Duncan Sandsf413cdf2008-06-01 07:38:42 +00004319 // Converting from one pointer type to another or between a pointer and an
4320 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00004321 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +00004322 (TD && ((isa<PointerType>(ParamTy) ||
4323 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
4324 (isa<PointerType>(ActTy) ||
4325 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +00004326 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004327 }
4328
4329 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00004330 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00004331 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00004332
Chris Lattner58d74912008-03-12 17:45:29 +00004333 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4334 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004335 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00004336 // won't be dropping them. Check that these extra arguments have attributes
4337 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00004338 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
4339 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00004340 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00004341 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00004342 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00004343 return false;
4344 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004345
Chris Lattner9fe38862003-06-19 17:00:31 +00004346 // Okay, we decided that this is a safe thing to do: go ahead and start
4347 // inserting cast instructions as necessary...
4348 std::vector<Value*> Args;
4349 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00004350 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004351 attrVec.reserve(NumCommonArgs);
4352
4353 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004354 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004355
4356 // If the return value is not being used, the type may not be compatible
4357 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00004358 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004359
4360 // Add the new return attributes.
4361 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00004362 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004363
4364 AI = CS.arg_begin();
4365 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4366 const Type *ParamTy = FT->getParamType(i);
4367 if ((*AI)->getType() == ParamTy) {
4368 Args.push_back(*AI);
4369 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00004370 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00004371 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004372 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004373 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004374
4375 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004376 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004377 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00004378 }
4379
4380 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004381 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +00004382 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +00004383 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +00004384
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004385 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004386 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00004387 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00004388 errs() << "WARNING: While resolving call to function '"
4389 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00004390 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004391 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +00004392 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4393 const Type *PTy = getPromotedType((*AI)->getType());
4394 if (PTy != (*AI)->getType()) {
4395 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004396 Instruction::CastOps opcode =
4397 CastInst::getCastOpcode(*AI, false, PTy, false);
4398 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +00004399 } else {
4400 Args.push_back(*AI);
4401 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004402
Duncan Sandse1e520f2008-01-13 08:02:44 +00004403 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00004404 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00004405 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00004406 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004407 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004408 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004409
Devang Patel19c87462008-09-26 22:53:05 +00004410 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
4411 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
4412
Devang Patel9674d152009-10-14 17:29:00 +00004413 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +00004414 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00004415
Eric Christophera66297a2009-07-25 02:45:27 +00004416 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
4417 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00004418
Chris Lattner9fe38862003-06-19 17:00:31 +00004419 Instruction *NC;
4420 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004421 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00004422 Args.begin(), Args.end(),
4423 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00004424 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004425 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004426 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004427 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
4428 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00004429 CallInst *CI = cast<CallInst>(Caller);
4430 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00004431 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00004432 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004433 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00004434 }
4435
Chris Lattner6934a042007-02-11 01:23:03 +00004436 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00004437 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004438 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +00004439 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00004440 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00004441 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004442 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004443
4444 // If this is an invoke instruction, we should insert it after the first
4445 // non-phi, instruction in the normal successor block.
4446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00004447 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00004448 InsertNewInstBefore(NC, *I);
4449 } else {
4450 // Otherwise, it's a call, just insert cast right after the call instr
4451 InsertNewInstBefore(NC, *Caller);
4452 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +00004453 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004454 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004455 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004456 }
4457 }
4458
Devang Patel1bf5ebc2009-10-13 21:41:20 +00004459
Chris Lattner931f8f32009-08-31 05:17:58 +00004460 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +00004461 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +00004462
4463 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004464 return true;
4465}
4466
Duncan Sandscdb6d922007-09-17 10:26:40 +00004467// transformCallThroughTrampoline - Turn a call to a function created by the
4468// init_trampoline intrinsic into a direct call to the underlying function.
4469//
4470Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
4471 Value *Callee = CS.getCalledValue();
4472 const PointerType *PTy = cast<PointerType>(Callee->getType());
4473 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00004474 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004475
4476 // If the call already has the 'nest' attribute somewhere then give up -
4477 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00004478 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004479 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004480
4481 IntrinsicInst *Tramp =
4482 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
4483
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00004484 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004485 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
4486 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
4487
Devang Patel05988662008-09-25 21:00:45 +00004488 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00004489 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004490 unsigned NestIdx = 1;
4491 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00004492 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004493
4494 // Look for a parameter marked with the 'nest' attribute.
4495 for (FunctionType::param_iterator I = NestFTy->param_begin(),
4496 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00004497 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00004498 // Record the parameter type and any other attributes.
4499 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00004500 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004501 break;
4502 }
4503
4504 if (NestTy) {
4505 Instruction *Caller = CS.getInstruction();
4506 std::vector<Value*> NewArgs;
4507 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
4508
Devang Patel05988662008-09-25 21:00:45 +00004509 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00004510 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004511
Duncan Sandscdb6d922007-09-17 10:26:40 +00004512 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004513 // mean appending it. Likewise for attributes.
4514
Devang Patel19c87462008-09-26 22:53:05 +00004515 // Add any result attributes.
4516 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00004517 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004518
Duncan Sandscdb6d922007-09-17 10:26:40 +00004519 {
4520 unsigned Idx = 1;
4521 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4522 do {
4523 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004524 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004525 Value *NestVal = Tramp->getOperand(3);
4526 if (NestVal->getType() != NestTy)
4527 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
4528 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00004529 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004530 }
4531
4532 if (I == E)
4533 break;
4534
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004535 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004536 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00004537 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004538 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00004539 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00004540
4541 ++Idx, ++I;
4542 } while (1);
4543 }
4544
Devang Patel19c87462008-09-26 22:53:05 +00004545 // Add any function attributes.
4546 if (Attributes Attr = Attrs.getFnAttributes())
4547 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
4548
Duncan Sandscdb6d922007-09-17 10:26:40 +00004549 // The trampoline may have been bitcast to a bogus type (FTy).
4550 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004551 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004552
Duncan Sandscdb6d922007-09-17 10:26:40 +00004553 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00004554 NewTypes.reserve(FTy->getNumParams()+1);
4555
Duncan Sandscdb6d922007-09-17 10:26:40 +00004556 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004557 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004558 {
4559 unsigned Idx = 1;
4560 FunctionType::param_iterator I = FTy->param_begin(),
4561 E = FTy->param_end();
4562
4563 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004564 if (Idx == NestIdx)
4565 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004566 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004567
4568 if (I == E)
4569 break;
4570
Duncan Sandsb0c9b932008-01-14 19:52:09 +00004571 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00004572 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004573
4574 ++Idx, ++I;
4575 } while (1);
4576 }
4577
4578 // Replace the trampoline call with a direct call. Let the generic
4579 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +00004580 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +00004581 FTy->isVarArg());
4582 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +00004583 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +00004584 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +00004585 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +00004586 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
4587 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00004588
4589 Instruction *NewCaller;
4590 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00004591 NewCaller = InvokeInst::Create(NewCallee,
4592 II->getNormalDest(), II->getUnwindDest(),
4593 NewArgs.begin(), NewArgs.end(),
4594 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004595 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004596 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004597 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00004598 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
4599 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004600 if (cast<CallInst>(Caller)->isTailCall())
4601 cast<CallInst>(NewCaller)->setTailCall();
4602 cast<CallInst>(NewCaller)->
4603 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00004604 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004605 }
Devang Patel9674d152009-10-14 17:29:00 +00004606 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +00004607 Caller->replaceAllUsesWith(NewCaller);
4608 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +00004609 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004610 return 0;
4611 }
4612 }
4613
4614 // Replace the trampoline call with a direct call. Since there is no 'nest'
4615 // parameter, there is no need to adjust the argument list. Let the generic
4616 // code sort out any function type mismatches.
4617 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +00004618 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +00004619 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00004620 CS.setCalledFunction(NewCallee);
4621 return CS.getInstruction();
4622}
4623
Reid Spencere4d87aa2006-12-23 06:05:41 +00004624
Chris Lattner473945d2002-05-06 18:06:38 +00004625
Chris Lattner7e708292002-06-25 16:13:24 +00004626Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004627 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
4628
4629 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
4630 return ReplaceInstUsesWith(GEP, V);
4631
Chris Lattner620ce142004-05-07 22:09:22 +00004632 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004633
Chris Lattnere87597f2004-10-16 18:11:37 +00004634 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00004635 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004636
Chris Lattner28977af2004-04-05 01:30:19 +00004637 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00004638 if (TD) {
4639 bool MadeChange = false;
4640 unsigned PtrSize = TD->getPointerSizeInBits();
4641
4642 gep_type_iterator GTI = gep_type_begin(GEP);
4643 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
4644 I != E; ++I, ++GTI) {
4645 if (!isa<SequentialType>(*GTI)) continue;
4646
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004647 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00004648 // to what we need. If narrower, sign-extend it to what we need. This
4649 // explicit cast can make subsequent optimizations more obvious.
4650 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00004651 if (OpBits == PtrSize)
4652 continue;
4653
Chris Lattner2345d1d2009-08-30 20:01:10 +00004654 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004655 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00004656 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00004657 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00004658 }
Chris Lattner28977af2004-04-05 01:30:19 +00004659
Chris Lattner90ac28c2002-08-02 19:29:35 +00004660 // Combine Indices - If the source pointer to this getelementptr instruction
4661 // is a getelementptr instruction, combine the indices of the two
4662 // getelementptr instructions into a single instruction.
4663 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004664 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00004665 // Note that if our source is a gep chain itself that we wait for that
4666 // chain to be resolved before we perform this transformation. This
4667 // avoids us creating a TON of code in some cases.
4668 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004669 if (GetElementPtrInst *SrcGEP =
4670 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
4671 if (SrcGEP->getNumOperands() == 2)
4672 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00004673
Chris Lattner72588fc2007-02-15 22:48:32 +00004674 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004675
4676 // Find out whether the last index in the source GEP is a sequential idx.
4677 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00004678 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
4679 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004680 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004681
Chris Lattner90ac28c2002-08-02 19:29:35 +00004682 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004683 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004684 // Replace: gep (gep %P, long B), long A, ...
4685 // With: T = long A+B; gep %P, T, ...
4686 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004687 Value *Sum;
4688 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
4689 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00004690 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004691 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00004692 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00004693 Sum = SO1;
4694 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00004695 // If they aren't the same type, then the input hasn't been processed
4696 // by the loop above yet (which canonicalizes sequential index types to
4697 // intptr_t). Just avoid transforming this until the input has been
4698 // normalized.
4699 if (SO1->getType() != GO1->getType())
4700 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004701 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00004702 }
Chris Lattner620ce142004-05-07 22:09:22 +00004703
Chris Lattnerab984842009-08-30 05:30:55 +00004704 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004705 if (Src->getNumOperands() == 2) {
4706 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00004707 GEP.setOperand(1, Sum);
4708 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00004709 }
Chris Lattnerab984842009-08-30 05:30:55 +00004710 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00004711 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00004712 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00004713 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004714 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004715 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004716 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00004717 Indices.append(Src->op_begin()+1, Src->op_end());
4718 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004719 }
4720
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004721 if (!Indices.empty())
4722 return (cast<GEPOperator>(&GEP)->isInBounds() &&
4723 Src->isInBounds()) ?
4724 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
4725 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004726 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00004727 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00004728 }
4729
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00004730 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
4731 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00004732 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00004733
Chris Lattner2de23192009-08-30 20:38:21 +00004734 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
4735 // want to change the gep until the bitcasts are eliminated.
4736 if (getBitCastOperand(X)) {
4737 Worklist.AddValue(PtrOp);
4738 return 0;
4739 }
4740
Chris Lattnerc514c1f2009-11-27 00:29:05 +00004741 bool HasZeroPointerIndex = false;
4742 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
4743 HasZeroPointerIndex = C->isZero();
4744
Chris Lattner963f4ba2009-08-30 20:36:46 +00004745 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
4746 // into : GEP [10 x i8]* X, i32 0, ...
4747 //
4748 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
4749 // into : GEP i8* X, ...
4750 //
4751 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00004752 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00004753 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4754 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004755 if (const ArrayType *CATy =
4756 dyn_cast<ArrayType>(CPTy->getElementType())) {
4757 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
4758 if (CATy->getElementType() == XTy->getElementType()) {
4759 // -> GEP i8* X, ...
4760 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004761 return cast<GEPOperator>(&GEP)->isInBounds() ?
4762 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
4763 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00004764 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
4765 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00004766 }
4767
4768 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004769 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00004770 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004771 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00004772 // At this point, we know that the cast source type is a pointer
4773 // to an array of the same type as the destination pointer
4774 // array. Because the array type is never stepped over (there
4775 // is a leading zero) we can fold the cast into this GEP.
4776 GEP.setOperand(0, X);
4777 return &GEP;
4778 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00004779 }
4780 }
Chris Lattnereed48272005-09-13 00:40:14 +00004781 } else if (GEP.getNumOperands() == 2) {
4782 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004783 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
4784 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00004785 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4786 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004787 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00004788 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4789 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00004790 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004791 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004792 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004793 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4794 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004795 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004796 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004797 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004798 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00004799
4800 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004801 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00004802 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004803 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00004804
Chris Lattner4de84762010-01-04 07:02:48 +00004805 if (TD && isa<ArrayType>(SrcElTy) &&
4806 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00004807 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00004808 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004809
4810 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4811 // allow either a mul, shift, or constant here.
4812 Value *NewIdx = 0;
4813 ConstantInt *Scale = 0;
4814 if (ArrayEltSize == 1) {
4815 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00004816 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004817 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004818 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004819 Scale = CI;
4820 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4821 if (Inst->getOpcode() == Instruction::Shl &&
4822 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004823 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
4824 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00004825 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00004826 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00004827 NewIdx = Inst->getOperand(0);
4828 } else if (Inst->getOpcode() == Instruction::Mul &&
4829 isa<ConstantInt>(Inst->getOperand(1))) {
4830 Scale = cast<ConstantInt>(Inst->getOperand(1));
4831 NewIdx = Inst->getOperand(0);
4832 }
4833 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004834
Chris Lattner7835cdd2005-09-13 18:36:04 +00004835 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004836 // out, perform the transformation. Note, we don't know whether Scale is
4837 // signed or not. We'll use unsigned version of division/modulo
4838 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00004839 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004840 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004841 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00004842 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00004843 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00004844 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
4845 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004846 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00004847 }
4848
4849 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00004850 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00004851 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00004852 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004853 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4854 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
4855 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00004856 // The NewGEP must be pointer typed, so must the old one -> BitCast
4857 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00004858 }
4859 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004860 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00004861 }
Chris Lattner58407792009-01-09 04:53:57 +00004862
Chris Lattner46cd5a12009-01-09 05:44:56 +00004863 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00004864 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00004865 /// Y = gep X, <...constant indices...>
4866 /// into a gep of the original struct. This is important for SROA and alias
4867 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00004868 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00004869 if (TD &&
4870 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004871 // Determine how much the GEP moves the pointer. We are guaranteed to get
4872 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00004873 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00004874 int64_t Offset = OffsetV->getSExtValue();
4875
4876 // If this GEP instruction doesn't move the pointer, just replace the GEP
4877 // with a bitcast of the real input to the dest type.
4878 if (Offset == 0) {
4879 // If the bitcast is of an allocation, and the allocation will be
4880 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00004881 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00004882 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00004883 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
4884 if (Instruction *I = visitBitCast(*BCI)) {
4885 if (I != BCI) {
4886 I->takeName(BCI);
4887 BCI->getParent()->getInstList().insert(BCI, I);
4888 ReplaceInstUsesWith(*BCI, I);
4889 }
4890 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00004891 }
Chris Lattner58407792009-01-09 04:53:57 +00004892 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004893 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00004894 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00004895
4896 // Otherwise, if the offset is non-zero, we need to find out if there is a
4897 // field at Offset in 'A's type. If so, we can pull the cast through the
4898 // GEP.
4899 SmallVector<Value*, 8> NewIndices;
4900 const Type *InTy =
4901 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00004902 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00004903 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
4904 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
4905 NewIndices.end()) :
4906 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
4907 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00004908
4909 if (NGEP->getType() == GEP.getType())
4910 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00004911 NGEP->takeName(&GEP);
4912 return new BitCastInst(NGEP, GEP.getType());
4913 }
Chris Lattner58407792009-01-09 04:53:57 +00004914 }
4915 }
4916
Chris Lattner8a2a3112001-12-14 16:52:21 +00004917 return 0;
4918}
4919
Victor Hernandez66284e02009-10-24 04:23:03 +00004920Instruction *InstCombiner::visitFree(Instruction &FI) {
4921 Value *Op = FI.getOperand(1);
4922
4923 // free undef -> unreachable.
4924 if (isa<UndefValue>(Op)) {
4925 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00004926 new StoreInst(ConstantInt::getTrue(FI.getContext()),
4927 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00004928 return EraseInstFromFunction(FI);
4929 }
4930
4931 // If we have 'free null' delete the instruction. This can happen in stl code
4932 // when lots of inlining happens.
4933 if (isa<ConstantPointerNull>(Op))
4934 return EraseInstFromFunction(FI);
4935
Victor Hernandez046e78c2009-10-26 23:43:48 +00004936 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00004937 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00004938 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
4939 if (Op->hasOneUse() && CI->hasOneUse()) {
4940 EraseInstFromFunction(FI);
4941 EraseInstFromFunction(*CI);
4942 return EraseInstFromFunction(*cast<Instruction>(Op));
4943 }
4944 } else {
4945 // Op is a call to malloc
4946 if (Op->hasOneUse()) {
4947 EraseInstFromFunction(FI);
4948 return EraseInstFromFunction(*cast<Instruction>(Op));
4949 }
4950 }
Dan Gohman7f712a12009-10-27 00:11:02 +00004951 }
Victor Hernandez66284e02009-10-24 04:23:03 +00004952
4953 return 0;
4954}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00004955
Chris Lattner3284d1f2007-04-15 00:07:55 +00004956
Chris Lattner2f503e62005-01-31 05:36:43 +00004957
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00004958Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4959 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00004960 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004961 BasicBlock *TrueDest;
4962 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00004963 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004964 !isa<Constant>(X)) {
4965 // Swap Destinations and condition...
4966 BI.setCondition(X);
4967 BI.setSuccessor(0, FalseDest);
4968 BI.setSuccessor(1, TrueDest);
4969 return &BI;
4970 }
4971
Reid Spencere4d87aa2006-12-23 06:05:41 +00004972 // Cannonicalize fcmp_one -> fcmp_oeq
4973 FCmpInst::Predicate FPred; Value *Y;
4974 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004975 TrueDest, FalseDest)) &&
4976 BI.getCondition()->hasOneUse())
4977 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
4978 FPred == FCmpInst::FCMP_OGE) {
4979 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
4980 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
4981
4982 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004983 BI.setSuccessor(0, FalseDest);
4984 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00004985 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004986 return &BI;
4987 }
4988
4989 // Cannonicalize icmp_ne -> icmp_eq
4990 ICmpInst::Predicate IPred;
4991 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00004992 TrueDest, FalseDest)) &&
4993 BI.getCondition()->hasOneUse())
4994 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
4995 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
4996 IPred == ICmpInst::ICMP_SGE) {
4997 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
4998 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
4999 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00005000 BI.setSuccessor(0, FalseDest);
5001 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00005002 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00005003 return &BI;
5004 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005005
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005006 return 0;
5007}
Chris Lattner0864acf2002-11-04 16:18:53 +00005008
Chris Lattner46238a62004-07-03 00:26:11 +00005009Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5010 Value *Cond = SI.getCondition();
5011 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5012 if (I->getOpcode() == Instruction::Add)
5013 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5014 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5015 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00005016 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00005017 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005018 AddRHS));
5019 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005020 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00005021 return &SI;
5022 }
5023 }
5024 return 0;
5025}
5026
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005027Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005028 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005029
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005030 if (!EV.hasIndices())
5031 return ReplaceInstUsesWith(EV, Agg);
5032
5033 if (Constant *C = dyn_cast<Constant>(Agg)) {
5034 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00005035 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005036
5037 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00005038 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005039
5040 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
5041 // Extract the element indexed by the first index out of the constant
5042 Value *V = C->getOperand(*EV.idx_begin());
5043 if (EV.getNumIndices() > 1)
5044 // Extract the remaining indices out of the constant indexed by the
5045 // first index
5046 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
5047 else
5048 return ReplaceInstUsesWith(EV, V);
5049 }
5050 return 0; // Can't handle other constants
5051 }
5052 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
5053 // We're extracting from an insertvalue instruction, compare the indices
5054 const unsigned *exti, *exte, *insi, *inse;
5055 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
5056 exte = EV.idx_end(), inse = IV->idx_end();
5057 exti != exte && insi != inse;
5058 ++exti, ++insi) {
5059 if (*insi != *exti)
5060 // The insert and extract both reference distinctly different elements.
5061 // This means the extract is not influenced by the insert, and we can
5062 // replace the aggregate operand of the extract with the aggregate
5063 // operand of the insert. i.e., replace
5064 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5065 // %E = extractvalue { i32, { i32 } } %I, 0
5066 // with
5067 // %E = extractvalue { i32, { i32 } } %A, 0
5068 return ExtractValueInst::Create(IV->getAggregateOperand(),
5069 EV.idx_begin(), EV.idx_end());
5070 }
5071 if (exti == exte && insi == inse)
5072 // Both iterators are at the end: Index lists are identical. Replace
5073 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5074 // %C = extractvalue { i32, { i32 } } %B, 1, 0
5075 // with "i32 42"
5076 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
5077 if (exti == exte) {
5078 // The extract list is a prefix of the insert list. i.e. replace
5079 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
5080 // %E = extractvalue { i32, { i32 } } %I, 1
5081 // with
5082 // %X = extractvalue { i32, { i32 } } %A, 1
5083 // %E = insertvalue { i32 } %X, i32 42, 0
5084 // by switching the order of the insert and extract (though the
5085 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00005086 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
5087 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005088 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
5089 insi, inse);
5090 }
5091 if (insi == inse)
5092 // The insert list is a prefix of the extract list
5093 // We can simply remove the common indices from the extract and make it
5094 // operate on the inserted value instead of the insertvalue result.
5095 // i.e., replace
5096 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
5097 // %E = extractvalue { i32, { i32 } } %I, 1, 0
5098 // with
5099 // %E extractvalue { i32 } { i32 42 }, 0
5100 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
5101 exti, exte);
5102 }
Chris Lattner7e606e22009-11-09 07:07:56 +00005103 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
5104 // We're extracting from an intrinsic, see if we're the only user, which
5105 // allows us to simplify multiple result intrinsics to simpler things that
5106 // just get one value..
5107 if (II->hasOneUse()) {
5108 // Check if we're grabbing the overflow bit or the result of a 'with
5109 // overflow' intrinsic. If it's the latter we can remove the intrinsic
5110 // and replace it with a traditional binary instruction.
5111 switch (II->getIntrinsicID()) {
5112 case Intrinsic::uadd_with_overflow:
5113 case Intrinsic::sadd_with_overflow:
5114 if (*EV.idx_begin() == 0) { // Normal result.
5115 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5116 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5117 EraseInstFromFunction(*II);
5118 return BinaryOperator::CreateAdd(LHS, RHS);
5119 }
5120 break;
5121 case Intrinsic::usub_with_overflow:
5122 case Intrinsic::ssub_with_overflow:
5123 if (*EV.idx_begin() == 0) { // Normal result.
5124 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5125 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5126 EraseInstFromFunction(*II);
5127 return BinaryOperator::CreateSub(LHS, RHS);
5128 }
5129 break;
5130 case Intrinsic::umul_with_overflow:
5131 case Intrinsic::smul_with_overflow:
5132 if (*EV.idx_begin() == 0) { // Normal result.
5133 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
5134 II->replaceAllUsesWith(UndefValue::get(II->getType()));
5135 EraseInstFromFunction(*II);
5136 return BinaryOperator::CreateMul(LHS, RHS);
5137 }
5138 break;
5139 default:
5140 break;
5141 }
5142 }
5143 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00005144 // Can't simplify extracts from other values. Note that nested extracts are
5145 // already simplified implicitely by the above (extract ( extract (insert) )
5146 // will be translated into extract ( insert ( extract ) ) first and then just
5147 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00005148 return 0;
5149}
5150
Chris Lattnera844fc4c2006-04-10 22:45:52 +00005151
Robert Bocchino1d7456d2006-01-13 22:48:06 +00005152
Chris Lattnerea1c4542004-12-08 23:43:58 +00005153
5154/// TryToSinkInstruction - Try to move the specified instruction from its
5155/// current block into the beginning of DestBlock, which can only happen if it's
5156/// safe to move the instruction past all of the instructions between it and the
5157/// end of its block.
5158static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5159 assert(I->hasOneUse() && "Invariants didn't hold!");
5160
Chris Lattner108e9022005-10-27 17:13:11 +00005161 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00005162 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00005163 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005164
Chris Lattnerea1c4542004-12-08 23:43:58 +00005165 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005166 if (isa<AllocaInst>(I) && I->getParent() ==
5167 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005168 return false;
5169
Chris Lattner96a52a62004-12-09 07:14:34 +00005170 // We can only sink load instructions if there is nothing between the load and
5171 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00005172 if (I->mayReadFromMemory()) {
5173 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00005174 Scan != E; ++Scan)
5175 if (Scan->mayWriteToMemory())
5176 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005177 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005178
Dan Gohman02dea8b2008-05-23 21:05:58 +00005179 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00005180
Chris Lattner4bc5f802005-08-08 19:11:57 +00005181 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005182 ++NumSunkInst;
5183 return true;
5184}
5185
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005186
5187/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
5188/// all reachable code to the worklist.
5189///
5190/// This has a couple of tricks to make the code faster and more powerful. In
5191/// particular, we constant fold and DCE instructions as we go, to avoid adding
5192/// them to the worklist (this significantly speeds up instcombine on code where
5193/// many instructions are dead or constant). Additionally, if we find a branch
5194/// whose condition is a known constant, we only visit the reachable successors.
5195///
Chris Lattner2ee743b2009-10-15 04:59:28 +00005196static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00005197 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00005198 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005199 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00005200 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00005201 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00005202 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00005203
5204 std::vector<Instruction*> InstrsForInstCombineWorklist;
5205 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005206
Chris Lattner2ee743b2009-10-15 04:59:28 +00005207 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
5208
Chris Lattner2c7718a2007-03-23 19:17:18 +00005209 while (!Worklist.empty()) {
5210 BB = Worklist.back();
5211 Worklist.pop_back();
5212
5213 // We have now visited this block! If we've already been here, ignore it.
5214 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00005215
Chris Lattner2c7718a2007-03-23 19:17:18 +00005216 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5217 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005218
Chris Lattner2c7718a2007-03-23 19:17:18 +00005219 // DCE instruction if trivially dead.
5220 if (isInstructionTriviallyDead(Inst)) {
5221 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00005222 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00005223 Inst->eraseFromParent();
5224 continue;
5225 }
5226
5227 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005228 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005229 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005230 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
5231 << *Inst << '\n');
5232 Inst->replaceAllUsesWith(C);
5233 ++NumConstProp;
5234 Inst->eraseFromParent();
5235 continue;
5236 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00005237
5238
5239
5240 if (TD) {
5241 // See if we can constant fold its operands.
5242 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
5243 i != e; ++i) {
5244 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
5245 if (CE == 0) continue;
5246
5247 // If we already folded this constant, don't try again.
5248 if (!FoldedConstants.insert(CE))
5249 continue;
5250
Chris Lattner7b550cc2009-11-06 04:27:31 +00005251 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00005252 if (NewC && NewC != CE) {
5253 *i = NewC;
5254 MadeIRChange = true;
5255 }
5256 }
5257 }
5258
Devang Patel7fe1dec2008-11-19 18:56:50 +00005259
Chris Lattner67f7d542009-10-12 03:58:40 +00005260 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005261 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00005262
5263 // Recursively visit successors. If this is a branch or switch on a
5264 // constant, only visit the reachable successor.
5265 TerminatorInst *TI = BB->getTerminator();
5266 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
5267 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
5268 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00005269 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005270 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005271 continue;
5272 }
5273 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
5274 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
5275 // See if this is an explicit destination.
5276 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
5277 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00005278 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00005279 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00005280 continue;
5281 }
5282
5283 // Otherwise it is the default destination.
5284 Worklist.push_back(SI->getSuccessor(0));
5285 continue;
5286 }
5287 }
5288
5289 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
5290 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005291 }
Chris Lattner67f7d542009-10-12 03:58:40 +00005292
5293 // Once we've found all of the instructions to add to instcombine's worklist,
5294 // add them in reverse order. This way instcombine will visit from the top
5295 // of the function down. This jives well with the way that it adds all uses
5296 // of instructions to the worklist after doing a transformation, thus avoiding
5297 // some N^2 behavior in pathological cases.
5298 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
5299 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00005300
5301 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005302}
5303
Chris Lattnerec9c3582007-03-03 02:04:50 +00005304bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005305 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005306
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00005307 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
5308 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00005309
Chris Lattnerb3d59702005-07-07 20:40:38 +00005310 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00005311 // Do a depth-first traversal of the function, populate the worklist with
5312 // the reachable instructions. Ignore blocks that are not reachable. Keep
5313 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00005314 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00005315 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00005316
Chris Lattnerb3d59702005-07-07 20:40:38 +00005317 // Do a quick scan over the function. If we find any blocks that are
5318 // unreachable, remove any instructions inside of them. This prevents
5319 // the instcombine code from having to deal with some bad special cases.
5320 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5321 if (!Visited.count(BB)) {
5322 Instruction *Term = BB->getTerminator();
5323 while (Term != BB->begin()) { // Remove instrs bottom-up
5324 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005325
Chris Lattnerbdff5482009-08-23 04:37:46 +00005326 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00005327 // A debug intrinsic shouldn't force another iteration if we weren't
5328 // going to do one without it.
5329 if (!isa<DbgInfoIntrinsic>(I)) {
5330 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005331 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00005332 }
Devang Patel228ebd02009-10-13 22:56:32 +00005333
Devang Patel228ebd02009-10-13 22:56:32 +00005334 // If I is not void type then replaceAllUsesWith undef.
5335 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00005336 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00005337 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00005338 I->eraseFromParent();
5339 }
5340 }
5341 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005342
Chris Lattner873ff012009-08-30 05:55:36 +00005343 while (!Worklist.isEmpty()) {
5344 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00005345 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00005346
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005347 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005348 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005349 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00005350 EraseInstFromFunction(*I);
5351 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005352 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005353 continue;
5354 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005355
Chris Lattner8c8c66a2006-05-11 17:11:52 +00005356 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005357 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00005358 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005359 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00005360
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005361 // Add operands to the worklist.
5362 ReplaceInstUsesWith(*I, C);
5363 ++NumConstProp;
5364 EraseInstFromFunction(*I);
5365 MadeIRChange = true;
5366 continue;
5367 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005368
Chris Lattnerea1c4542004-12-08 23:43:58 +00005369 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00005370 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00005371 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00005372 Instruction *UserInst = cast<Instruction>(I->use_back());
5373 BasicBlock *UserParent;
5374
5375 // Get the block the use occurs in.
5376 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
5377 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
5378 else
5379 UserParent = UserInst->getParent();
5380
Chris Lattnerea1c4542004-12-08 23:43:58 +00005381 if (UserParent != BB) {
5382 bool UserIsSuccessor = false;
5383 // See if the user is one of our successors.
5384 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5385 if (*SI == UserParent) {
5386 UserIsSuccessor = true;
5387 break;
5388 }
5389
5390 // If the user is one of our immediate successors, and if that successor
5391 // only has us as a predecessors (we'd have to split the critical edge
5392 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00005393 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00005394 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005395 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005396 }
5397 }
5398
Chris Lattner74381062009-08-30 07:44:24 +00005399 // Now that we have an instruction, try combining it to simplify it.
5400 Builder->SetInsertPoint(I->getParent(), I);
5401
Reid Spencera9b81012007-03-26 17:44:01 +00005402#ifndef NDEBUG
5403 std::string OrigI;
5404#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00005405 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00005406 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
5407
Chris Lattner90ac28c2002-08-02 19:29:35 +00005408 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005409 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005410 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005411 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00005412 DEBUG(errs() << "IC: Old = " << *I << '\n'
5413 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00005414
Chris Lattnerf523d062004-06-09 05:08:07 +00005415 // Everything uses the new instruction now.
5416 I->replaceAllUsesWith(Result);
5417
5418 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00005419 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005420 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005421
Chris Lattner6934a042007-02-11 01:23:03 +00005422 // Move the name to the new instruction first.
5423 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005424
5425 // Insert the new instruction into the basic block...
5426 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005427 BasicBlock::iterator InsertPos = I;
5428
5429 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5430 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5431 ++InsertPos;
5432
5433 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005434
Chris Lattner7a1e9242009-08-30 06:13:40 +00005435 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00005436 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00005437#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00005438 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
5439 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00005440#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00005441
Chris Lattner90ac28c2002-08-02 19:29:35 +00005442 // If the instruction was modified, it's possible that it is now dead.
5443 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005444 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005445 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00005446 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00005447 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00005448 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005449 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005450 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005451 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005452 }
5453 }
5454
Chris Lattner873ff012009-08-30 05:55:36 +00005455 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00005456 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005457}
5458
Chris Lattnerec9c3582007-03-03 02:04:50 +00005459
5460bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00005461 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005462 TD = getAnalysisIfAvailable<TargetData>();
5463
Chris Lattner74381062009-08-30 07:44:24 +00005464
5465 /// Builder - This is an IRBuilder that automatically inserts new
5466 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00005467 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00005468 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00005469 InstCombineIRInserter(Worklist));
5470 Builder = &TheBuilder;
5471
Chris Lattnerec9c3582007-03-03 02:04:50 +00005472 bool EverMadeChange = false;
5473
5474 // Iterate while there is work to do.
5475 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00005476 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00005477 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00005478
5479 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00005480 return EverMadeChange;
5481}
5482
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005483FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005484 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005485}